问:
Use header file (.h) from a static library (.a)
I'm trying to use a static library (.a) in another project. I want to make an #include of a header from this .a, but i'm with errors.

First, I tried to search .h file in the .a file, in order to understand if it exists under .a and I get:

```<code>Binary file libtest.a matches
</code>```

So, the header in under the static library. Then, I insert this way in the CMakeFiles.txt:

```<code>cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

# Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log
                     /home/prvs/android-ndk/hello/jni/app/src/main/cpp/libtest.a
              )
</code>```

However, when I run the app in Android-Studio I got:

```<code>Fatal error: 'example.h' file not found
</code>```

And I'm importing to the C like this:

```<code>#include <example.h>
</code>```

In order to import a header file, it is necessary another steps?

答:
Static library files (.a on Unix/Linux .lib on Windows) do normally not contain headers. Yes, technically it is possible to pack arbitrary files along the object files, but most linkers will just choke on that and refuse to go to work when presented with such an abomination.

The most likely reason that when searching for the header name in the archive matches is, that the header file name is part of the debugging metadata that's part of the library (so that a debugger can translate binary locations to source file locations).

You have to install the headers separately and specify the installation location when compiling as additional include directory.

Body:
I'm trying to use a static library (.a) in another project. I want to make an #include of a header from this .a, but i'm with errors.

First, I tried to search .h file in the .a file, in order to understand if it exists under .a and I get:

Binary file libtest.a matches

So, the header in under the static library. Then, I insert this way in the CMakeFiles.txt:

cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

# Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log
                     /home/prvs/android-ndk/hello/jni/app/src/main/cpp/libtest.a
              )

However, when I run the app in Android-Studio I got:

Fatal error: 'example.h' file not found

And I'm importing to the C like this:

#include <example.h>

In order to import a header file, it is necessary another steps?


来源: stackexchange

答:
To use a library you need two things: the compiled code for the library (in a .a file, a .so file, a .lib file, or whatever) and, separately a header file that describes the entry points for the library. In general you can't derive the header from the library.

For example, to use the C++ standard library (which comes with your compiler as some form of library file) you use the standard header files, which have names like "iostream", "string", and so on.

For example, if you have a library that contains compiled code from one source file:

```<code>// source.cpp
#include <iostream>
void f(int i) {
    std::cout << i << '\n';
}
</code>```

you need a header file that describes that entry point:

```<code>// mylibrary.h
void f(int i);
</code>```

In every source file that calls f you need #include "mylibrary.h" and when you link your executable you need to link with the compiled code in the library.

ContentLicense: CC BY-SA 3.0

Title: Use header file (.h) from a static library (.a)

Body:
To use a library you need two things: the compiled code for the library (in a .a file, a .so file, a .lib file, or whatever) and, separately a header file that describes the entry points for the library. In general you can't derive the header from the library.

For example, to use the C++ standard library (which comes with your compiler as some form of library file) you use the standard header files, which have names like "iostream", "string", and so on.

For example, if you have a library that contains compiled code from one source file:

// source.cpp
#include <iostream>
void f(int i) {
    std::cout << i << '\n';
}

you need a header file that describes that entry point:

// mylibrary.h
void f(int i);

In every source file that calls f you need #include "mylibrary.h" and when you link your executable you need to link with the compiled code in the library.


问:
Can't figure out a Linq join
In LinqPad, I have this working, and the underlying SQL query is what I want:

```<code>from userProcesses in UserProcesses
join formProcesses in FormProcesses
   on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms
    on formProcesses.Form_FormID equals forms.FormID
join userForms in UserForms
    on new {userProcesses.UserProcessID, forms.FormID} equals
       new {userForms.UserProcessID, userForms.FormID} into combined
from c in combined.DefaultIfEmpty()
select new
{
    UserFormID = c == null ? (int?) null : c.UserFormID,
    FormID = forms.FormID,
    Name = forms.Name
}
</code>```

The problem is, in my actual code, the FormProcesses table is not exposed itself, but is a navigation property.  I've been struggling with how to write this query in my software.

Here is a skeleton view of my models so you can see the navigation properties:

```<code>public class UserProcess : BaseModel
    {
        [Key]
        public int UserProcessID { get; set; }

        [Required]
        [ForeignKey("Process")]
        public int ProcessID { get; set; }

        public Process Process { get; set; }

        public virtual ICollection<UserForm> UserForms { get; set; }
    }

 public class Form : Common.BaseModel
    {
        [Key]
        public int FormID { get; set; }

        public virtual ICollection<Process> Processes { get; set; }
    }

public class UserForm : Common.BaseModel
    {
        [Key]
        public int UserFormID { get; set; }

        [Required]
        [ForeignKey("UserProcess")]
        public int UserProcessID { get; set; }

        public UserProcess UserProcess { get; set; }

        [Required]
        [ForeignKey("Form")]
        public int FormID { get; set; }

        public Form Form { get; set; }
    }

public class Process : Common.BaseModel
    {
        [Key]
        public int ProcessID { get; set; }

        public virtual ICollection<Form> Forms { get; set; }
    }
</code>```

What am I doing wrong - how can I get this working?

答:
You can replace all explicit joins with "navigating" through navigation properties.

For instance, the following joins

```<code>join formProcesses in FormProcesses
    on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms
    on formProcesses.Form_FormID equals forms.FormID
</code>```

become:

```<code>from forms in userProcesses.Process.Forms
</code>```

which should solve the issue in question.

Optionally, LINQ to Entities way of writing the following join:

```<code>join userForms in UserForms
    on new { userProcesses.UserProcessID, forms.FormID } equals
       new { userForms.UserProcessID, userForms.FormID } into combined
</code>```

is:

```<code>let combined = from userForms in userProcesses.UserForms
               where userForms.FormID == forms.FormID
               select userForms
</code>```

Title: Can't figure out a Linq join

Body:
In LinqPad, I have this working, and the underlying SQL query is what I want:

from userProcesses in UserProcesses
join formProcesses in FormProcesses
   on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms
    on formProcesses.Form_FormID equals forms.FormID
join userForms in UserForms
    on new {userProcesses.UserProcessID, forms.FormID} equals
       new {userForms.UserProcessID, userForms.FormID} into combined
from c in combined.DefaultIfEmpty()
select new
{
    UserFormID = c == null ? (int?) null : c.UserFormID,
    FormID = forms.FormID,
    Name = forms.Name
}

The problem is, in my actual code, the FormProcesses table is not exposed itself, but is a navigation property.  I've been struggling with how to write this query in my software.

Here is a skeleton view of my models so you can see the navigation properties:

public class UserProcess : BaseModel
    {
        [Key]
        public int UserProcessID { get; set; }

        [Required]
        [ForeignKey("Process")]
        public int ProcessID { get; set; }

        public Process Process { get; set; }

        public virtual ICollection<UserForm> UserForms { get; set; }
    }

 public class Form : Common.BaseModel
    {
        [Key]
        public int FormID { get; set; }

        public virtual ICollection<Process> Processes { get; set; }
    }

public class UserForm : Common.BaseModel
    {
        [Key]
        public int UserFormID { get; set; }

        [Required]
        [ForeignKey("UserProcess")]
        public int UserProcessID { get; set; }

        public UserProcess UserProcess { get; set; }

        [Required]
        [ForeignKey("Form")]
        public int FormID { get; set; }

        public Form Form { get; set; }
    }

public class Process : Common.BaseModel
    {
        [Key]
        public int ProcessID { get; set; }

        public virtual ICollection<Form> Forms { get; set; }
    }

What am I doing wrong - how can I get this working?

Body:
You can replace all explicit joins with "navigating" through navigation properties.

For instance, the following joins

join formProcesses in FormProcesses
    on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms
    on formProcesses.Form_FormID equals forms.FormID

become:

from forms in userProcesses.Process.Forms

which should solve the issue in question.

Optionally, LINQ to Entities way of writing the following join:

join userForms in UserForms
    on new { userProcesses.UserProcessID, forms.FormID } equals
       new { userForms.UserProcessID, userForms.FormID } into combined

is:

let combined = from userForms in userProcesses.UserForms
               where userForms.FormID == forms.FormID
               select userForms


问:
How to implement Antizer in clojurescript
I am trying to use Antizer (https://github.com/priornix/antizer) in my clojurescript project, and cannot figure out where to/how to import the css file in order to make the UI elements appear as Ant.design elements. </p>

<p>This is my current require statement: </p>

```<code>(:require [reagent.core :as reagent :refer [atom]]
          [secretary.core :as secretary :include-macros true]
          [accountant.core :as accountant]
          [antizer.reagent :as ant]
</code>```

答:
Ok, so I finally figured it out.
The reagent template doesn't have a traditional index.html file; it has the handler.clj which creates the index.html whenever it is served.

To include the ant.d stylesheet, you need to go to the handler.clj file, and under the head function, add:

(include-css "https://cdnjs.cloudflare.com/ajax/libs/antd/2.13.10/antd.css")])

This will solve the problem.

Body:
I am trying to use Antizer (https://github.com/priornix/antizer) in my clojurescript project, and cannot figure out where to/how to import the css file in order to make the UI elements appear as Ant.design elements.

This is my current require statement:

(:require [reagent.core :as reagent :refer [atom]]
          [secretary.core :as secretary :include-macros true]
          [accountant.core :as accountant]
          [antizer.reagent :as ant]


问:
Can't access ServiceController (InvalidOperationException) when trying to read on remote/another computer
I have a local service running on my computer and trying to get other computers to be able to read the status of my service (whether it's running, stopped, etc.) However, I am unable to as I get an InvalidOperationException error, saying that I am unable to open Service Control Manager. Locally, I am able to, but on another remote computer I am unable to. The ServiceController (cs) object just returns an object with properties that all have the InvalidOperationException error.

I've tried closing down all the firewalls on the other computers, tried running Visual Studio on Administrator privileges, but nothing seems to be working. I've noticed that others suggested hard coding your admin credentials and using WindowsIdentity and Impersonation but that wouldn't work for my project (as it wouldn't be a viable solution at my workplace - wouldn't make sense with the business logic as don't want to give clients any in-house credentials).

Here's my snippet of code:

```<code>    public bool CheckServiceStatus()
    {
        try
        {
            string machineName = pubSubConfig.MachineName;
            string serviceName = pubSubConfig.ServiceName;

            System.ServiceProcess.ServiceController cs = new System.ServiceProcess.ServiceController(serviceName, machineName);

            if (cs != null && cs.ServiceName == serviceName && cs.Status == System.ServiceProcess.ServiceControllerStatus.Running)
            {
                return true;
            }
        }
        catch(Exception ex)
        {
            Trace.TraceError("Unable to check service status: /r/n {0}", ex.Message);
        }
        return false;
    }
</code>```

The error is this:

```<code>System.InvalidOperationException: Cannot open Service Control Manager on computer '___'.
This operation might require other privileges. ---> System.ComponentModel.Win32Exception: Access is denied
</code>```

Does anyone know any workarounds as to how I can get other computers running my C# program to be able to read the ServiceController object?

Thanks!

答:
So as I said in the comments, I was not able to get around the SCM (Service Control Manager) due to admin privileges when accessing another remote computer (makes sense if you think about security). However, I did find another solution that was more or less a workaround. I'll post the solution here in case anyone finds it helpful.

So to check the status of the Windows Service (like if it's running or not), I added an additional WCF service that is hosted in the Windows Service. So now the service can expose a method that literally just returns true.

Essentially the thought-process around it was that if the WCF service is accessible then that means the Window Service is running, and thus will always return true. If the Windows service is down, the WCF service will also be down and thus making that method not available. You wouldn't get anything to return, so you would know that the service is down and not running.

Hope that helps someone! I know it's not really a direct solution to the problem I had originally asked, but it was a workaround, indirect solution.

Body:
I have a local service running on my computer and trying to get other computers to be able to read the status of my service (whether it's running, stopped, etc.) However, I am unable to as I get an InvalidOperationException error, saying that I am unable to open Service Control Manager. Locally, I am able to, but on another remote computer I am unable to. The ServiceController (cs) object just returns an object with properties that all have the InvalidOperationException error.

I've tried closing down all the firewalls on the other computers, tried running Visual Studio on Administrator privileges, but nothing seems to be working. I've noticed that others suggested hard coding your admin credentials and using WindowsIdentity and Impersonation but that wouldn't work for my project (as it wouldn't be a viable solution at my workplace - wouldn't make sense with the business logic as don't want to give clients any in-house credentials).

Here's my snippet of code:

    public bool CheckServiceStatus()
    {
        try
        {
            string machineName = pubSubConfig.MachineName;
            string serviceName = pubSubConfig.ServiceName;

            System.ServiceProcess.ServiceController cs = new System.ServiceProcess.ServiceController(serviceName, machineName);

            if (cs != null && cs.ServiceName == serviceName && cs.Status == System.ServiceProcess.ServiceControllerStatus.Running)
            {
                return true;
            }
        }
        catch(Exception ex)
        {
            Trace.TraceError("Unable to check service status: /r/n {0}", ex.Message);
        }
        return false;
    }

The error is this:

System.InvalidOperationException: Cannot open Service Control Manager on computer '___'.
This operation might require other privileges. ---> System.ComponentModel.Win32Exception: Access is denied

Does anyone know any workarounds as to how I can get other computers running my C# program to be able to read the ServiceController object?

Thanks!


问:
CakePHP - Ignore form Input Field with Name Attribute
I have a CakePHP form with radio buttons that enhance the frontend by toggling form sections on and off. To make the radio buttons work, I need a name attribute that binds them together.

However, my problem is that CakePHP POSTs any input field with a name attribute, so the radio button above causes errors when submitting the form because I don't have a toggle-0 field in my model.

Is there a way to prevent CakePHP from posting the radio button values? Can I achieve this in the frontend or backend?

This seems like a very simple thing to do (Like in C# MVC) but I can't seem to find any information on the Cake Cookbook.

Relevant Radio Button:

```<code><input id="toggle-on-0" class="selection-toggle selection-toggle-left" name="toggle-0" value="false" type="radio">
<label for="toggle-on-0" class="selection-btn">On</label>
<input id="toggle-off-0" class="selection-toggle selection-toggle-right" name="toggle-0" value="true" type="radio">
<label for="toggle-off-0" class="selection-btn">Off</label>
</code>```

Let me know if I can clarify the question or if you need the code for my add() method.

答:
It's not a CakePHP issue. By using both the value and name attribute you have made your radio control successful. As mentioned in the HTML specification, radio input will now be a part of form data, and will be sent to the action on form submission.

Solutions:

1: Your only solution on the server side is to remove radio input data from request object if it's present.

2: Remove the name attribute and change your frontend logic.

3: Send AJAX request with only required POST data.

Body:
I have a CakePHP form with radio buttons that enhance the frontend by toggling form sections on and off. To make the radio buttons work, I need a name attribute that binds them together.

However, my problem is that CakePHP POSTs any input field with a name attribute, so the radio button above causes errors when submitting the form because I don't have a toggle-0 field in my model.

Is there a way to prevent CakePHP from posting the radio button values? Can I achieve this in the frontend or backend?

This seems like a very simple thing to do (Like in C# MVC) but I can't seem to find any information on the Cake Cookbook.

Relevant Radio Button:

<input id="toggle-on-0" class="selection-toggle selection-toggle-left" name="toggle-0" value="false" type="radio">
On
<input id="toggle-off-0" class="selection-toggle selection-toggle-right" name="toggle-0" value="true" type="radio">
Off

Let me know if I can clarify the question or if you need the code for my add() method.


问:
Division in 8086 Assembly in MASM
I am writing this assembly program in 8086, but it is not working properly. The quotient and remainder prints out as some random symbols even though I use single digit numbers. Can someone please point out the errors/mistakes in the program? Thank you.</p>

```<code>.model small
.stack 50h

.data
Divisor db ?
Dividend db ?
Quotient db ?
Remainder db ?

.code
main_method   proc
              mov    ax, @data
              mov    ds, ax

              mov    ah, 01
              int    21h
              sub    al, 48
              mov    Divisor, al

              mov    ah, 01
              int    21h
              sub    al, 48
              mov    Dividend, al
              mov    bl, 00
              mov    al, 00
              mov    bl, Divisor
              mov    al, Dividend
              div    bl

              mov    Quotient, al
              mov    Remainder, ah

              mov    dl, Quotient
              add    dl, 48
              mov    ah, 02
              int    21h

              mov    dl, Remainder
              add    dl, 48
              mov    ah, 02
              int    21h
              mov    ah, 4ch
              int    21h
main_method   endp
              end    main_method
</code>```

答:
Basically DIV function divide AX and then put quotient in AL and remainder in AH.
AX consists of AH and AL. So if you only want to divide AL then you have to make sure that AH is 0 . You can do below method to make something zero.

```<code>MOV AH, 0
</code>```

OR

```<code>AND AH, 0
</code>```

OR

```<code>XOR AH, AH
</code>```

Title: Division in 8086 Assembly in MASM

Body:
I am writing this assembly program in 8086, but it is not working properly. The quotient and remainder prints out as some random symbols even though I use single digit numbers. Can someone please point out the errors/mistakes in the program? Thank you.

.model small
.stack 50h

.data
Divisor db ?
Dividend db ?
Quotient db ?
Remainder db ?

.code
main_method   proc
              mov    ax, @data
              mov    ds, ax

              mov    ah, 01
              int    21h
              sub    al, 48
              mov    Divisor, al

              mov    ah, 01
              int    21h
              sub    al, 48
              mov    Dividend, al
              mov    bl, 00
              mov    al, 00
              mov    bl, Divisor
              mov    al, Dividend
              div    bl

              mov    Quotient, al
              mov    Remainder, ah

              mov    dl, Quotient
              add    dl, 48
              mov    ah, 02
              int    21h

              mov    dl, Remainder
              add    dl, 48
              mov    ah, 02
              int    21h
              mov    ah, 4ch
              int    21h
main_method   endp
              end    main_method

Body:
Basically DIV function divide AX and then put quotient in AL and remainder in AH.
AX consists of AH and AL. So if you only want to divide AL then you have to make sure that AH is 0 . You can do below method to make something zero.

MOV AH, 0

OR

AND AH, 0

OR

XOR AH, AH


问:
Delaying stub answer in Javascript
In my production code I have a function which is blocking program for 10 ms (because of use execSync). In my test I used testdouble.js library to stub it:

```<code>td.when(getSignalStrength()).thenReturn.apply(null, array);
</code>```

However stub is responding immediately and in reality function getCurrentSignalStrength is responding after 10 ms. I would like to delay the answer of stub so test would be more similar to reality. I read documentation of testdouble.js:
https://github.com/testdouble/testdouble.js/blob/master/docs/5-stubbing-results.md#delay but unfortunately it seems that delay option is not available for thenReturn method. So how to delay stub answer?

答:
There is no way to cause testdouble.js to block the thread of execution. Like the documentation says, even defer and delay are frowned upon.

This sounds like an example of an overly defensive specification; the "answer" in this case is to consider whether you really need to block and delay for 10ms. What does this indicate in your design?

Title: Delaying stub answer in Javascript

Body:
In my production code I have a function which is blocking program for 10 ms (because of use execSync). In my test I used testdouble.js library to stub it:

td.when(getSignalStrength()).thenReturn.apply(null, array);

However stub is responding immediately and in reality function getCurrentSignalStrength is responding after 10 ms. I would like to delay the answer of stub so test would be more similar to reality. I read documentation of testdouble.js:
https://github.com/testdouble/testdouble.js/blob/master/docs/5-stubbing-results.md#delay but unfortunately it seems that delay option is not available for thenReturn method. So how to delay stub answer?


问:
Print the row only if the string does not exist in a specific column taking account each group of strings in other column by UNIX
So, I have the following tabulated file with thousand rows:

```<code>NP_000007.1     ACADM   1457    rs1061337       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000057.1     C8B     1078    rs1013579       117
NP_000057.1     C8B     932     rs856847        345
NP_000057.1     C8B     932     rs856831        not_match
NP_000057.1     C8B     932     rs856841        429
NP_000076.2     CLCNKB  48      rs5251          334
</code>```

I would like to delete those rows for each group of strings grouped in first column if at least appears not_match pattern one time in fifth column. Thus, only the rows grouped by the same string in first column that corresponding to only numbers in fifth column are printed.

The desired output would be:

```<code>NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334
</code>```

I think to do it in some steps separating the rows with "not_match" pattern and the numbers in fifth column and then see if there are coincidences in first column by a hash and discard these coincidences. However I would like to do in one step in the same file. How could I get it in Unix environment? Thanks in advance

答:
awk to the rescue!

a two pass algorithm will be the simplest

```<code>$ awk 'NR==FNR {                       # in the first round
         if($NF=="not_match") a[$1];   # record the keys to be deleted
         next}                         #
       !($1 in a)' file{,}             # in the second round skip them
</code>```

note that file{,} is shorthand for file file

```<code>NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334
</code>```

Body:
So, I have the following tabulated file with thousand rows:

NP_000007.1     ACADM   1457    rs1061337       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000057.1     C8B     1078    rs1013579       117
NP_000057.1     C8B     932     rs856847        345
NP_000057.1     C8B     932     rs856831        not_match
NP_000057.1     C8B     932     rs856841        429
NP_000076.2     CLCNKB  48      rs5251          334

I would like to delete those rows for each group of strings grouped in first column if at least appears not_match pattern one time in fifth column. Thus, only the rows grouped by the same string in first column that corresponding to only numbers in fifth column are printed.

The desired output would be:

NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334

I think to do it in some steps separating the rows with "not_match" pattern and the numbers in fifth column and then see if there are coincidences in first column by a hash and discard these coincidences. However I would like to do in one step in the same file. How could I get it in Unix environment? Thanks in advance

Body:
awk to the rescue!

a two pass algorithm will be the simplest

$ awk 'NR==FNR {                       # in the first round
         if($NF=="not_match") a[$1];   # record the keys to be deleted
         next}                         #
       !($1 in a)' file{,}             # in the second round skip them

note that file{,} is shorthand for file file

NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334


问:
Detection Idiom and SFINAE via Inheritance
I can use std::experimental::is_detected to check whether chips1_t can be instantiated with float* (which it can't) as shown in the static_assert below:

```<code>#include <experimental/type_traits>
#include <type_traits>

template <typename, typename = void>
  struct chips1;

template <typename T>
struct chips1<T*,std::enable_if_t<std::is_same<T,int>::value>> {
  using type = int;
};

template <typename T> using chips1_t = typename chips1<T>::type;

static_assert(!std::experimental::is_detected<chips1_t,float*>::value,"");
</code>```

If I then try a check using chips2_t, a similar static_assert, shown below, will produce a compilation error; regarding the missing type member. Can anyone tell me why?

```<code>struct Base {};

template <typename>
  struct chips2;

template <typename T>
struct chips2<T*> : std::enable_if_t<std::is_same<T,int>::value,Base> {
  using type = int;
};

template <typename T> using chips2_t = typename chips2<T>::type;

static_assert(!std::experimental::is_detected<chips2_t,float*>::value,"");
</code>```

答:
In the second case, the base class is not part of the template type, so it's not considered during SFINAE (It's a dependent base class)

Instantiating

```<code>template <typename T>
struct chips2<T*>
</code>```

Succeeds, and then compilation fails because it derives from std::enable_if_t<std::is_same<T,int>::value,Base> which becomes an ill-formed expression.

You cannot specialize templates by their base class*.

For example, you couldn't have two competing specializations like:

```<code>template <typename T>
struct chips2<T*> : std::enable_if_t<std::is_same<T,int>::value,Base> {
  using type = int;
};

template <typename T>
struct chips2<T*> : std::enable_if_t<!std::is_same<T,int>::value,Base> {
  using type = float;
};
</code>```

They would be considered identical from a specialization standpoint (i.e., they are identical from a naming standpoint, so the compiler will consider the second one to be a redeclaration of the first one). The only part that matters is everything up to the colon :

In the first case, your enable_if is directly part of the template specialization, so SFINAE works properly.

Another note

In the second one, you've effectively made it impossible to instantiate chips2 with anything other than int*, see the following example:

```<code>struct Base {};

template <typename>
struct chips2
{};

template <typename T>
struct chips2<T*>
   : std::enable_if_t<std::is_same<T,int>::value, Base>
{};

int main(){
    chips2<float*> c;
}
</code>```

You might be inclined to think that SFINAE will choose the base class template for c, but in reality it chooses the specialization chips2<T*> because of what I said above, and compilation fails.

*Relevant standardese at [temp.spec]

the name of the class that is explicitly specialized shall be a simple-template-id.

Where a simple-template-id is of the form:

   template-name < template-argument-listopt >

e.g. chips2<T*>. Note that there is no option to also include the class it derives from

Body:
I can use std::experimental::is_detected to check whether chips1_t can be instantiated with float* (which it can't) as shown in the static_assert below:

#include <experimental/type_traits>
#include <type_traits>

template <typename, typename = void>
  struct chips1;

template <typename T>
struct chips1<T*,std::enable_if_t<std::is_same<T,int>::value>> {
  using type = int;
};

template <typename T> using chips1_t = typename chips1<T>::type;

static_assert(!std::experimental::is_detected<chips1_t,float*>::value,"");

If I then try a check using chips2_t, a similar static_assert, shown below, will produce a compilation error; regarding the missing type member. Can anyone tell me why?

struct Base {};

template <typename>
  struct chips2;

template <typename T>
struct chips2<T*> : std::enable_if_t<std::is_same<T,int>::value,Base> {
  using type = int;
};

template <typename T> using chips2_t = typename chips2<T>::type;

static_assert(!std::experimental::is_detected<chips2_t,float*>::value,"");

Body:
In the second case, the base class is not part of the template type, so it's not considered during SFINAE (It's a dependent base class)

Instantiating

template <typename T>
struct chips2<T*>

Succeeds, and then compilation fails because it derives from std::enable_if_t<std::is_same<T,int>::value,Base> which becomes an ill-formed expression.

You cannot specialize templates by their base class*.

For example, you couldn't have two competing specializations like:

template <typename T>
struct chips2<T*> : std::enable_if_t<std::is_same<T,int>::value,Base> {
  using type = int;
};

template <typename T>
struct chips2<T*> : std::enable_if_t<!std::is_same<T,int>::value,Base> {
  using type = float;
};

They would be considered identical from a specialization standpoint (i.e., they are identical from a naming standpoint, so the compiler will consider the second one to be a redeclaration of the first one). The only part that matters is everything up to the colon :

In the first case, your enable_if is directly part of the template specialization, so SFINAE works properly.

Another note

In the second one, you've effectively made it impossible to instantiate chips2 with anything other than int*, see the following example:

struct Base {};

template <typename>
struct chips2
{};

template <typename T>
struct chips2<T*>
   : std::enable_if_t<std::is_same<T,int>::value, Base>
{};

int main(){
    chips2<float*> c;
}

You might be inclined to think that SFINAE will choose the base class template for c, but in reality it chooses the specialization chips2<T*> because of what I said above, and compilation fails.

*Relevant standardese at [temp.spec]

the name of the class that is explicitly specialized shall be a simple-template-id.

Where a simple-template-id is of the form:

   template-name < template-argument-listopt >

e.g. chips2<T*>. Note that there is no option to also include the class it derives from


问:
How can I ensure that my HttpClient 4.1 does not leak sockets?
My server uses data from an internal web service to construct its response, on a per request basis.  I'm using Apache HttpClient 4.1 to make the requests.  Each initial request will result in about 30 requests to the web service.  Of these, 4 - 8 will end up with sockets stuck in CLOSE_WAIT, which never get released.  Eventually these stuck sockets exceed my ulimit and my process runs out of file descriptors.

I don't want to just raise my ulimit (1024), because that will just mask the problem.

The reason I've moved to HttpClient is that java.net.HttpUrlConnection was behaving the same way.

I have tried moving to a SingleClientConnManager per request, and calling client.getConnectionManager().shutdown() on it, but sockets still end up stuck.

Should I be trying to solve this so that I end up with 0 open sockets while there are no running requests, or should I be concentrating on request persistence and pooling?

For clarity I'm including some details which may be relevant:

OS: Ubuntu 10.10

JRE: 1.6.0_22

Language: Scala 2.8

Sample code:

```<code>val cleaner = Executors.newScheduledThreadPool(1)
private val client = {
    val ssl_ctx = SSLContext.getInstance("TLS")
    val managers = Array[TrustManager](TrustingTrustManager)
    ssl_ctx.init(null, managers, new java.security.SecureRandom())
    val sslSf = new org.apache.http.conn.ssl.SSLSocketFactory(ssl_ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
    val schemeRegistry = new SchemeRegistry()
    schemeRegistry.register(new Scheme("https", 443, sslSf))
    val connection = new ThreadSafeClientConnManager(schemeRegistry)
    object clean extends Runnable{
        override def run = {
            connection.closeExpiredConnections
            connection.closeIdleConnections(30, SECONDS)
        }
    }
    cleaner.scheduleAtFixedRate(clean,10,10,SECONDS)
    val httpClient = new DefaultHttpClient(connection)
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username,password))
    httpClient
}
val get = new HttpGet(uri)
val entity = client.execute(get).getEntity
val stream = entity.getContent
val justForTheExample = IOUtils.toString(stream)
stream.close()
</code>```

Test: netstat -a | grep {myInternalWebServiceName} | grep CLOSE_WAIT

(Lists sockets for my process that are in CLOSE_WAIT state)

Post comment discussion:

This code now demonstrates correct usage.

答:
I've marked oleg's answer as correct, as it highlights an important usage point about HttpClient's connection pooling.

To answer my specific original question, though, which was "Should I be trying to solve for 0 unused sockets or trying to maximize pooling?"

Now that the pooling solution is in place and working correctly the application throughput has increased by about 150%.  I attribute this to not having to renegotiate SSL and multiple handshakes, instead reusing persistent connections in accordance with HTTP 1.1.

It is definitely worth working to utilize pooling as intended, rather than trying to hack around with calling ThreadSafeClientConnManager.shutdown() after each request etcetera.  If, on the other hand, you were calling arbitrary hosts and not reusing routes the way I am you might easily find that it becomes necessary to do that sort of hackery, as the JVM might surprise you with the long life of CLOSE_WAIT designated sockets if you're not garbage collecting very often.

ContentLicense: CC BY-SA 2.5

Body:
My server uses data from an internal web service to construct its response, on a per request basis.  I'm using Apache HttpClient 4.1 to make the requests.  Each initial request will result in about 30 requests to the web service.  Of these, 4 - 8 will end up with sockets stuck in CLOSE_WAIT, which never get released.  Eventually these stuck sockets exceed my ulimit and my process runs out of file descriptors.

I don't want to just raise my ulimit (1024), because that will just mask the problem.

The reason I've moved to HttpClient is that java.net.HttpUrlConnection was behaving the same way.

I have tried moving to a SingleClientConnManager per request, and calling client.getConnectionManager().shutdown() on it, but sockets still end up stuck.

Should I be trying to solve this so that I end up with 0 open sockets while there are no running requests, or should I be concentrating on request persistence and pooling?

For clarity I'm including some details which may be relevant:

OS: Ubuntu 10.10

JRE: 1.6.0_22

Language: Scala 2.8

Sample code:

val cleaner = Executors.newScheduledThreadPool(1)
private val client = {
    val ssl_ctx = SSLContext.getInstance("TLS")
    val managers = Array[TrustManager](TrustingTrustManager)
    ssl_ctx.init(null, managers, new java.security.SecureRandom())
    val sslSf = new org.apache.http.conn.ssl.SSLSocketFactory(ssl_ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
    val schemeRegistry = new SchemeRegistry()
    schemeRegistry.register(new Scheme("https", 443, sslSf))
    val connection = new ThreadSafeClientConnManager(schemeRegistry)
    object clean extends Runnable{
        override def run = {
            connection.closeExpiredConnections
            connection.closeIdleConnections(30, SECONDS)
        }
    }
    cleaner.scheduleAtFixedRate(clean,10,10,SECONDS)
    val httpClient = new DefaultHttpClient(connection)
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username,password))
    httpClient
}
val get = new HttpGet(uri)
val entity = client.execute(get).getEntity
val stream = entity.getContent
val justForTheExample = IOUtils.toString(stream)
stream.close()

Test: netstat -a | grep {myInternalWebServiceName} | grep CLOSE_WAIT

(Lists sockets for my process that are in CLOSE_WAIT state)

Post comment discussion:

This code now demonstrates correct usage.


问:
webdriverio: running a test with iedriver
I've setup webdriverio to run with FF and Chrome and all works fine.

I'm trying to run the same tests with http://webdriver.io/guide/services/iedriver.html.

It runs the first url command, but fails on the second run. E.g.:

```<code>browser.url('https://facebook.com'); //navigates to facebook
browser.url('https://google.com'); //fails on this line
</code>```

Which throws:

Failed to navigate to http://google.com. This usually means that a
  call to the COM method IWebBrowser2::Navigate2() failed. Build info:
  version: '3.6.0', revision: '6fbf3ec767', time:
  '2017-09-27T16:15:40.131Z' os.name: 'Windows 10', os.arch: 'amd64', os.version:
  '10.0', java.version: '1.8.0_151' Driver info: driver.version: unknown
  running internet explorer

Any idea why and how to make this work?

EDIT:
I've read IE11 Selenium WebDriverException: Failed to navigate. (org.openqa.selenium.WebDriverException ...IWebBrowser2::Navigate2() failed which didn't work for me

答:
try</p>

```<code>browser
.url('https://facebook.com') //navigates to facebook
.pause(5000)
.url('https://google.com') //fails on this line
</code>```

Body:
I've setup webdriverio to run with FF and Chrome and all works fine.

I'm trying to run the same tests with http://webdriver.io/guide/services/iedriver.html.

It runs the first url command, but fails on the second run. E.g.:

browser.url('https://facebook.com'); //navigates to facebook
browser.url('https://google.com'); //fails on this line

Which throws:

Failed to navigate to http://google.com. This usually means that a
  call to the COM method IWebBrowser2::Navigate2() failed. Build info:
  version: '3.6.0', revision: '6fbf3ec767', time:
  '2017-09-27T16:15:40.131Z' os.name: 'Windows 10', os.arch: 'amd64', os.version:
  '10.0', java.version: '1.8.0_151' Driver info: driver.version: unknown
  running internet explorer

Any idea why and how to make this work?

EDIT:
I've read IE11 Selenium WebDriverException: Failed to navigate. (org.openqa.selenium.WebDriverException ...IWebBrowser2::Navigate2() failed which didn't work for me

Body:
try

browser
.url('https://facebook.com') //navigates to facebook
.pause(5000)
.url('https://google.com') //fails on this line


问:
Scala object import in runtime
So the question is, is it possible to import Scala object object in runtime as a usual scala class e.g.:

```<code>trait A
class B extends A
Class.forName("B").newInstance().asInstanceOf[A]
</code>```

But in case if class B becomes object B it won't work.
Are there any other options for Scala Object?

答:
If B is an object the following code works:

```<code>trait A
object B extends A

val `class` = Class.forName("B$")
val constructor = `class`.getDeclaredConstructors.apply(0)
constructor.setAccessible(true)
constructor.newInstance().asInstanceOf[A]
</code>```

But this is literal translation of your code from class to object. Creating new instance of B$ violates the contract that there is the only instance of an object in Scala (although some frameworks, especially Java frameworks, can break it too). So it's better to refer the instance cached in MODULE$

```<code>`class`.getField("MODULE$")
  .get(null) // the field is static, so there's no need in instance
  .asInstanceOf[A]
</code>```

Title: Scala object import in runtime

Body:
So the question is, is it possible to import Scala object object in runtime as a usual scala class e.g.:

trait A
class B extends A
Class.forName("B").newInstance().asInstanceOf[A]

But in case if class B becomes object B it won't work.
Are there any other options for Scala Object?

Body:
If B is an object the following code works:

trait A
object B extends A

val `class` = Class.forName("B$")
val constructor = `class`.getDeclaredConstructors.apply(0)
constructor.setAccessible(true)
constructor.newInstance().asInstanceOf[A]

But this is literal translation of your code from class to object. Creating new instance of B$ violates the contract that there is the only instance of an object in Scala (although some frameworks, especially Java frameworks, can break it too). So it's better to refer the instance cached in MODULE$

`class`.getField("MODULE$")
  .get(null) // the field is static, so there's no need in instance
  .asInstanceOf[A]

ContentLicense: CC BY-SA 4.0


问:
data binding is not working in angular 4
This is probably too basic but I haven't been able to figure it out.

I'm working with angular 4. I have a folder within my "app" folder called competitions.

Here I have my competitions-detail.component.ts file like this:

```<code>import { Component }  from '@angular/core'

@Component({
  moduleId: module.id,
  selector: 'competitions-detail',
  templateUrl: 'competitions-detail.component.html',
  styleUrls: [ 'competitions-detail.component.css' ]
})

export class CompetitionsDetailComponent {
    title: 'Competencias';
}
</code>```

Then I have my template file:

```<code><md-toolbar color="primary">
  <md-icon>data_usage</md-icon>
  <span><strong>LA M10</strong></span>
  <span class="spacer"></span>
  <span><strong>COMPETENCIAS</strong></span>
</md-toolbar>

<h1>COMPETENCIAS</h1>
<h1>{{title}}</h1>
<h2>COMPETENCIAS</h2>
<h2>{{title}}</h2>
</code>```

And this is the Result

As you can see, the template is working fine, if I hardcode the values they are displayed, I even have some material design components there but for some reason, the simple data binding {{ }} is not displaying the title value.

What am I missing?

答:
The variable assignment It should be = instead of :</p>

```<code>export class CompetitionsDetailComponent{
    title = "Competencias";
}
</code>```

Body:
This is probably too basic but I haven't been able to figure it out.

I'm working with angular 4. I have a folder within my "app" folder called competitions.

Here I have my competitions-detail.component.ts file like this:

import { Component }  from '@angular/core'

@Component({
  moduleId: module.id,
  selector: 'competitions-detail',
  templateUrl: 'competitions-detail.component.html',
  styleUrls: [ 'competitions-detail.component.css' ]
})

export class CompetitionsDetailComponent {
    title: 'Competencias';
}

Then I have my template file:

<md-toolbar color="primary">
  <md-icon>data_usage</md-icon>
  LA M10

  COMPETENCIAS
</md-toolbar>

COMPETENCIAS

{{title}}

COMPETENCIAS

{{title}}

And this is the Result

As you can see, the template is working fine, if I hardcode the values they are displayed, I even have some material design components there but for some reason, the simple data binding {{ }} is not displaying the title value.

What am I missing?

Body:
The variable assignment It should be = instead of :

export class CompetitionsDetailComponent{
    title = "Competencias";
}


问:
How to Selectively choose rows in a key in map reduce
I have the following csv files with 5 columns and many rows. But I'm showing only first 6 rows.

```<code>Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450
</code>```

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

```<code>01/01/17 1290
02/01/17 790
</code>```

Output I'm getting

```<code>01/01/17 1530
02/01/17 1240
</code>```

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

Below is my code

```<code>public class GroupMR {

    public static class GroupMapper extends Mapper<LongWritable, Text, DateYear, IntWritable> {

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] keyvalue = line.split(",");
            monyeartext.set(new Text(keyvalue[0]));

            //populat.set(Integer.parseInt(keyvalue[5]));
            termText.set(keyvalue[1]);
            try {
                numpass.set(Integer.parseInt(keyvalue[4]));
            }catch (NumberFormatException e){
                System.out.println("not a number");
            }
            DateYear monyear = new DateYear(monyeartext, termText);
            context.write(monyear, numpass);

        }
    }
</code>```

答:
String[] keyvalue = line.split(",");</p>

```<code>Please add a filter after this line

if(!(keyvalue[2].equals("Pasta") ||keyvalue[2].equals("Pizza")) ){
  // If the food item is not pizza or pasta then  return
  return;
}
</code>```

Body:
I have the following csv files with 5 columns and many rows. But I'm showing only first 6 rows.

Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

01/01/17 1290
02/01/17 790

Output I'm getting

01/01/17 1530
02/01/17 1240

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

Below is my code

public class GroupMR {

    public static class GroupMapper extends Mapper<LongWritable, Text, DateYear, IntWritable> {

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] keyvalue = line.split(",");
            monyeartext.set(new Text(keyvalue[0]));

            //populat.set(Integer.parseInt(keyvalue[5]));
            termText.set(keyvalue[1]);
            try {
                numpass.set(Integer.parseInt(keyvalue[4]));
            }catch (NumberFormatException e){
                System.out.println("not a number");
            }
            DateYear monyear = new DateYear(monyeartext, termText);
            context.write(monyear, numpass);

        }
    }

Body:
String[] keyvalue = line.split(",");

Please add a filter after this line

if(!(keyvalue[2].equals("Pasta") ||keyvalue[2].equals("Pizza")) ){
  // If the food item is not pizza or pasta then  return
  return;
}


问:
How to select text in a textbox?
I have a userform with a textbox. I want to select the text within (highlight) after the keyDown event.

There are some restrictions to what the end user can enter. In case of wrong entry, a message would pop up, and the text in the textbox inviting the user to enter something should be selected.

I use the following code:

```<code>Me.txtbox_add_folder.SetFocus
Me.txtbox_add_folder.SelStart = 0
Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)
</code>```

The setFocus doesn't work. It seems that it's because setFocus triggers a series of other events see this discussion.

The solution proposed in a different discussion is to include a DoCmd.CancelEvent or Cancel = True, so that the focus doesn't go to another control, but these commands don't work on Excel.

答:
This technique is a little hacky, but it has worked for me before. It puts the cursor in the textbox and performs a Ctrl+A command (select all), which would highlight the text in that textbox.</p>

```<code>Me.txtbox_add_folder.SetFocus
SendKeys "^A"
</code>```

Title: How to select text in a textbox?

Body:
I have a userform with a textbox. I want to select the text within (highlight) after the keyDown event.

There are some restrictions to what the end user can enter. In case of wrong entry, a message would pop up, and the text in the textbox inviting the user to enter something should be selected.

I use the following code:

Me.txtbox_add_folder.SetFocus
Me.txtbox_add_folder.SelStart = 0
Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)

The setFocus doesn't work. It seems that it's because setFocus triggers a series of other events see this discussion.

The solution proposed in a different discussion is to include a DoCmd.CancelEvent or Cancel = True, so that the focus doesn't go to another control, but these commands don't work on Excel.

Body:
This technique is a little hacky, but it has worked for me before. It puts the cursor in the textbox and performs a Ctrl+A command (select all), which would highlight the text in that textbox.

Me.txtbox_add_folder.SetFocus
SendKeys "^A"


问:
JQuery Mobile - dynamically changing css with Javascript
I am having a problem trying to change the css of a button in JQuery Mobile.  I am not using the default page header ie. within the header I have nested a div with a logo etc. so the header height is about double the default.

The problem is with the back button. It defaults to the top left whereas I would like it to be centered vertically.  To this end, I inserted the script below into the page header just below the script include for JQuery Mobile.

```<code><script type="text/javascript">
    $(document).ready(function(){
        $(".ui-btn").css("margin","20px");
    }
</script>
</code>```

The HTML looks like this:

```<code><div data-role="page" id="main" data-theme="b">
<div id="myheader" data-role="header"><div id="header"><div id="logo"><img src="assets/logo.gif" alt="Acme" /></div></div></div>
</code>```

I can't seem to interact with the ui css in any way.  I've also tried:

```<code>$("#myheader a.ui-btn").css("margin","20px");
</code>```

and

```<code>$(".ui-btn-left").css("margin","20px");
</code>```

And also not nesting it within '$(document).ready(function(){' but nothing seems to be working.

I'd like to change the colours as well, but I'll move on to that once I've worked this out!  Any help or pointers would be hugely appreciated.

Thanks

Greg

答:
Are you sure that's the complete HTML, and Javascript isn't generating any other markup?

You're selecting an element with a class of .ui-btn or ui-btn-left, but those elements aren't present in the markup you've provided.

Would recommend checking it out in Firebug, as that will show you any HTML generated by Javascript.

------ EDIT AFTER INFO PROVIDED -------

Ok, I think what you're running into is your use of margin to control the position of an inline element.  Unless the the  or the s are specifically set as block elements by the CSS, margin may not affect them the way you'd expect.

I'd recommend trying to first set your target as a block element, and apply the CSS with an external stylesheet or inside some
```

Sounds to me like the problem is not necessarily that you can't use CSS interact with the UI HTML, but rather that it's not behaving the way you'd expect.

Body:
I am having a problem trying to change the css of a button in JQuery Mobile.  I am not using the default page header ie. within the header I have nested a div with a logo etc. so the header height is about double the default.

The problem is with the back button. It defaults to the top left whereas I would like it to be centered vertically.  To this end, I inserted the script below into the page header just below the script include for JQuery Mobile.

The HTML looks like this:

I can't seem to interact with the ui css in any way.  I've also tried:

$("#myheader a.ui-btn").css("margin","20px");

and

$(".ui-btn-left").css("margin","20px");

And also not nesting it within '$(document).ready(function(){' but nothing seems to be working.

I'd like to change the colours as well, but I'll move on to that once I've worked this out!  Any help or pointers would be hugely appreciated.

Thanks

Greg

Body:
Are you sure that's the complete HTML, and Javascript isn't generating any other markup?

You're selecting an element with a class of .ui-btn or ui-btn-left, but those elements aren't present in the markup you've provided.

Would recommend checking it out in Firebug, as that will show you any HTML generated by Javascript.

------ EDIT AFTER INFO PROVIDED -------

Ok, I think what you're running into is your use of margin to control the position of an inline element.  Unless the the <a> or the <span>s are specifically set as block elements by the CSS, margin may not affect them the way you'd expect.

I'd recommend trying to first set your target as a block element, and apply the CSS with an external stylesheet or inside some <style> tags on the page, rather than with jQuery.

Try something like this instead of that little JS snippet you referenced, and see where it gets you:

<style>
    #myheader a.ui-btn {display: block; margin: 20px;}
</style>

Sounds to me like the problem is not necessarily that you can't use CSS interact with the UI HTML, but rather that it's not behaving the way you'd expect.


问:
Java character encoding to HTML ISO-8859-1
I have a byte[] containing the value -110 (and other negative values). When I convert it to string I need it to display a ’ (right single quote). Currently, I am getting a question mark (?)

The ’ aligns to the special ASCII character #146 mentioned in this page but I am now stuck as to how I can input -110 or 146 (-110+256) and be a ’ value. I have also trued Any advice would be greatly appreciated.

```<code>byte[] b = {-110,84};
System.out.println(new String(b, Charset.forName("Windows-1252"))); //Displays ?T . The desired output should be ’T
System.out.println(new String(b, Charset.forName("UTF-8"))); //Displays ?T . The desired output should be ’T
System.out.println(new String(b, Charset.forName("ISO-8859-1"))); //Displays ?T . The desired output should be ’T
</code>```

答:
Thanks for the responses as John Skeet points out in his reply, the Java program needed to recognize the input data Windows-1252 and the Windows command line wasn't set to the code page either.

Setting the command line codepage to Windows-1252 was done by running

```<code>chcp 1252
</code>```

Starting the Java program to use Windows-1252 as the default was done by adding the following parameter

```<code>-Dfile.encoding="Windows-1252"
</code>```

Body:
I have a byte[] containing the value -110 (and other negative values). When I convert it to string I need it to display a ’ (right single quote). Currently, I am getting a question mark (?)

The ’ aligns to the special ASCII character #146 mentioned in this page but I am now stuck as to how I can input -110 or 146 (-110+256) and be a ’ value. I have also trued Any advice would be greatly appreciated.

byte[] b = {-110,84};
System.out.println(new String(b, Charset.forName("Windows-1252"))); //Displays ?T . The desired output should be ’T
System.out.println(new String(b, Charset.forName("UTF-8"))); //Displays ?T . The desired output should be ’T
System.out.println(new String(b, Charset.forName("ISO-8859-1"))); //Displays ?T . The desired output should be ’T

Body:
Thanks for the responses as John Skeet points out in his reply, the Java program needed to recognize the input data Windows-1252 and the Windows command line wasn't set to the code page either.

Setting the command line codepage to Windows-1252 was done by running

chcp 1252

Starting the Java program to use Windows-1252 as the default was done by adding the following parameter

-Dfile.encoding="Windows-1252"


问:
Get an object's position in another object's coordinate system
Is there a way in MEL or Python in Maya to get one object's position in the coordinate system of another object? I have a camera in a scene that may be rotated in any direction and am trying to measure the distance in its local Z axis to the vertices of various objects in the scene. This obviously needs to be fast, since it will likely be run thousands of times across the scene.

In Maxscript the command would be something like

```<code>" in coordsys $camera "
</code>```

but I have yet to find something like this in Maya. If there's no direct command to do this, does anyone have a way to calculate it using matrix math?

答:
There is no one liner similar to the MXS idiom -- and no easy way to do it in mel.  However in Python you can do this fairly easily.

First you need to get the matrix for the coordinate system you want as an MMatrix, which is part of the OpenMaya api.  Then get the position you want to check as an MPoint, which is another api class.   Here's the cheap way to get them (there are faster methods but they're much wordier):

```<code>from maya.api.OpenMaya import MVector, MMatrix, MPoint
import maya.cmds as cmds

def world_matrix(obj):
    """'
    convenience method to get the world matrix of <obj> as a matrix object
    """
    return MMatrix( cmds.xform(obj, q=True, matrix=True, ws=True))

def world_pos(obj):
    """'
    convenience method to get the world position of <obj> as an MPoint
    """
    return MPoint( cmds.xform(obj, q=True, t=True, ws=True))
</code>```

Once you have the matrix and the point, the relative position is simply point times the inverse of the matrix:

```<code>relative_position = world_pos('pSphere1') * world_matrix('pCube1').inverse()
print relative_position
# (0.756766, -0.0498943, 3.38499, 1)
</code>```

The result will be an MPoint, which has 4 numbers (x, y, z and w); the 4th will always be 1 so you can just ignore it, although the math needs it to account for scales and shears.

Body:
Is there a way in MEL or Python in Maya to get one object's position in the coordinate system of another object? I have a camera in a scene that may be rotated in any direction and am trying to measure the distance in its local Z axis to the vertices of various objects in the scene. This obviously needs to be fast, since it will likely be run thousands of times across the scene.

In Maxscript the command would be something like

" in coordsys $camera "

but I have yet to find something like this in Maya. If there's no direct command to do this, does anyone have a way to calculate it using matrix math?

Body:
There is no one liner similar to the MXS idiom -- and no easy way to do it in mel.  However in Python you can do this fairly easily.

First you need to get the matrix for the coordinate system you want as an MMatrix, which is part of the OpenMaya api.  Then get the position you want to check as an MPoint, which is another api class.   Here's the cheap way to get them (there are faster methods but they're much wordier):

from maya.api.OpenMaya import MVector, MMatrix, MPoint
import maya.cmds as cmds

def world_matrix(obj):
    """'
    convenience method to get the world matrix of <obj> as a matrix object
    """
    return MMatrix( cmds.xform(obj, q=True, matrix=True, ws=True))

def world_pos(obj):
    """'
    convenience method to get the world position of <obj> as an MPoint
    """
    return MPoint( cmds.xform(obj, q=True, t=True, ws=True))

Once you have the matrix and the point, the relative position is simply point times the inverse of the matrix:

relative_position = world_pos('pSphere1') * world_matrix('pCube1').inverse()
print relative_position
# (0.756766, -0.0498943, 3.38499, 1)

The result will be an MPoint, which has 4 numbers (x, y, z and w); the 4th will always be 1 so you can just ignore it, although the math needs it to account for scales and shears.


问:
NuGet Packages are missing
I searched this problem but none of the solutions worked. I have Visual Studio Professional 2015 installed and I am using TFS. My NuGet version is 3.1.6. This problem is happening only in my C# Web API/MVC project.

I am getting the below error:

This project references NuGet package(s) that are missing on this
  computer. Use NuGet Package Restore to download them.  For more
  information, see http://go.microsoft.com/fwlink/?LinkID=322105. The
  missing file is
  ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props

I do not have .nuget folder in my solutions.

I have a packages folder in the solution and when I delete it, it seems like NuGet does rebuild the dependencies but the project still has the above error.

I tried removing the project from TFS and it didn't fix it.

Along with the above error, all the references in the project have yellow warning signs and say they are missing.

When I checked the NuGet Package Manager for the project, everything that is "missing" has a green tick next to it, including Microsoft.Net.Compilers.

I tried adding a new Web API/MVC project and it faced a similar problem where most references such as Owin were "missing" with the yellow warning sign.

答:
The issue for me was that NuGet couldn't automatically get/update the packages because the full file path would be too large. Fixed by moving my solution to a folder in my Documents instead of a deeply nested folder.

Then can right-click on solution and select "Restore NuGet Packages" (which probably isn't necessary if you just build it and let it do it for you), and then select "Manage NuGet Packages for Solution" to get all the packages updated to the latest version.

This was for a solution of a sample ASP MVC application downloaded from Microsoft's web site.

Title: NuGet Packages are missing


问:
Oculus Platform Initialize
When I try to initialize the platform:

Oculus.Platform.Core.Initialize();

I get an error:

UnityException: Oculus Platform failed to initialize.

What could be the reason?

Device: GearVR and S8+;
Env: Unity v2017.1.1f1, Oculus Utilities v1.19.0, OVRPlugin v1.19.0, SDK v1.1.9.0.

答:
In my case, the problem was with Oculus Runtime.

To find the problem need to use OculusLogGatherer. This util can gather all logs and perform auto analysis. If u see in auto analysis something like this:

[Service_2017-11-15_14.59.51.txt] 15/11 14:59:54.088 {!ERROR!} [OAF
  ERROR] ......\package\PackageManager.cpp(187) : Package does not
  exist: oculus-runtime (1971015) [Service_2017-11-15_14.59.51.txt]
  15/11 14:59:54.103 {!ERROR!} [OAF ERROR]
  ......\package\PackageManager.cpp(187) : Package does not exist:
  oculus-runtime (1971015) [Service_2017-11-15_14.59.51.txt] 15/11
  15:00:09.078 {!ERROR!} [MobileConfigWrapper] Could not find
  mobileconfig metadata at C:\Program
  Files\Oculus\Support\oculus-runtime\mobileconfig\MobileConfigMetadata.json

This means that you need to install\reinstall a Oculus Runtime.

Title: Oculus Platform Initialize


问:
rake db:migrate - PG:: InvalidSchamaName ERROR: no schema has been selected to create in
I am attempting to run a rake:db migrate on a postgres database for my rails application. rake:db drop (the db already existed I am fixing a bug that requires I recreate the db) runs fine rake:db create runs fine but when I run rake:db migrate I get the following error

ERROR --: PG::InvalidSchemaName: ERROR: no schema has been selected to create in.

My database.yml file looks fine (it was working so I'm not sure what happened?)

```<code>development:
adapter: postgressql
encoding: utf8
username: [myusername]
password: [mypassword]
host: [myhost]
port: 5432
database: myapp_dev
schema_search_path: "myapp_dev"
pool: 5
timeout: 5000
</code>```

Any idea what is going on?

答:
Rails does not automatically create schemas AFAIK, if you stick to the public schema that fact can be ignored and things just work.

To use a different schema you will have to include a migration to do so, a raw SQL one like this will do:

```<code>class CreateMyAppSchema < ActiveRecord::Migration
  def up
    execute "CREATE SCHEMA myapp_dev;"
  end

  def down
    execute "DROP SCHEMA myapp_dev;"
  end
end
</code>```

In addition to the schema in the schema search path existing, the user needs to have the USAGE privilege on the myapp_dev schema

```<code>GRANT USAGE on schema myapp_dev to the_user;
</code>```

Body:
I am attempting to run a rake:db migrate on a postgres database for my rails application. rake:db drop (the db already existed I am fixing a bug that requires I recreate the db) runs fine rake:db create runs fine but when I run rake:db migrate I get the following error

ERROR --: PG::InvalidSchemaName: ERROR: no schema has been selected to create in.

My database.yml file looks fine (it was working so I'm not sure what happened?)

development:
adapter: postgressql
encoding: utf8
username: [myusername]
password: [mypassword]
host: [myhost]
port: 5432
database: myapp_dev
schema_search_path: "myapp_dev"
pool: 5
timeout: 5000

Any idea what is going on?

Body:
Rails does not automatically create schemas AFAIK, if you stick to the public schema that fact can be ignored and things just work.

To use a different schema you will have to include a migration to do so, a raw SQL one like this will do:

class CreateMyAppSchema < ActiveRecord::Migration
  def up
    execute "CREATE SCHEMA myapp_dev;"
  end

  def down
    execute "DROP SCHEMA myapp_dev;"
  end
end

In addition to the schema in the schema search path existing, the user needs to have the USAGE privilege on the myapp_dev schema

GRANT USAGE on schema myapp_dev to the_user;


问:
creating JSON format
I want to create JSON object like below,

```<code>{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};
</code>```

and I have two arrays like below,

```<code>["Greg", "Mike] and ["1", "2"]
</code>```

What is the best way to combine these arrays to populate the JSON object I described above by using JS?

答:
You could use a temporary object with the key names for the given arrays and assign values to the object at same index and return the array.

var names = ["Greg", "Mike"],
    values = ["1", "2"],
    temp = { name: names, value: values },
    object = Object.keys(temp).reduce(function (r, k) {
        temp[k].forEach(function (v, i) {
            r[i] = r[i] || {};
            r[i][k] = v;
        });
        return r;
    }, []);

console.log(object);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: creating JSON format

Body:
I want to create JSON object like below,

{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};

and I have two arrays like below,

["Greg", "Mike] and ["1", "2"]

What is the best way to combine these arrays to populate the JSON object I described above by using JS?

Body:
You could use a temporary object with the key names for the given arrays and assign values to the object at same index and return the array.

var names = ["Greg", "Mike"],
    values = ["1", "2"],
    temp = { name: names, value: values },
    object = Object.keys(temp).reduce(function (r, k) {
        temp[k].forEach(function (v, i) {
            r[i] = r[i] || {};
            r[i][k] = v;
        });
        return r;
    }, []);

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
RoundRobin functional approach - why does my function have side effects?

Objective

I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.

This function, is supposed to received an array like the following:

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

And produce the following output:

[ 1, 3, 2, 4 ]

Code

To achieve this, I decided to implement round robin recursively like the following:

```<code>const roundRobin = (arr, results) => {
    if (arr.length === 0) return results;

    const newResults = arr.reduce((acc, current) => {

        if (current.length > 0) {
            acc.results.push(current.shift());
            acc.arr.push(current);
        }
        return acc;

    }, { arr: [], results });

    return roundRobin(newResults.arr, newResults.results);
};
</code>```

Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:

```<code>const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );
</code>```

Problem

In my code I am using reduce in my arr parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!

Questions:

If I am using reduce, which is pure, how am I mutating my parameters?

Is there another pure/functional way of implementing roundRobin?

答:
If I am using reduce, which is pure, how am I mutating my parameters?

Function parameters can't really be mutated; a strange thought – but I'm sure you meant the arguments supplied to your function are being mutated. And yeah, that's with .shift as others pointed out

And for what it's worth, .reduce isn't pure unless the user-supplied lambda is pure

Is there another pure/functional way of implementing roundRobin?

Yep

const isEmpty = xs =>
  xs.length === 0

const head = ( [ x , ...xs ] ) =>
  x

const tail = ( [ x , ...xs ] ) =>
  xs

const append = ( xs , x ) =>
  xs.concat ( [ x ] )

const roundRobin = ( [ x , ...xs ] , acc = [] ) =>
  x === undefined
    ? acc
    : isEmpty ( x )
      ? roundRobin ( xs , acc )
      : roundRobin ( append ( xs , tail ( x ) )
                   , append ( acc , head ( x ) )
                   )

const data =
  [ [ 1 , 4 , 7 , 9 ]
  , [ 2 , 5 ]
  , [ 3 , 6 , 8 , 10 , 11 , 12 ]
  ]

console.log ( roundRobin ( data ) )
// => [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ]

console.log ( roundRobin ( [ [ 1 , 2 , 3 ] ] ) )
// => [ 1 , 2 , 3 ]

console.log ( roundRobin ( [] ) )
// => []```

Body:
Objective

I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.

This function, is supposed to received an array like the following:

[
    [ 1, 2 ],
    [ 3, 4 ]
]

And produce the following output:

[ 1, 3, 2, 4 ]

Code

To achieve this, I decided to implement round robin recursively like the following:

const roundRobin = (arr, results) => {
    if (arr.length === 0) return results;

    const newResults = arr.reduce((acc, current) => {

        if (current.length > 0) {
            acc.results.push(current.shift());
            acc.arr.push(current);
        }
        return acc;

    }, { arr: [], results });

    return roundRobin(newResults.arr, newResults.results);
};

Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:

const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );

Problem

In my code I am using reduce in my arr parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!

Questions:

If I am using reduce, which is pure, how am I mutating my parameters?

Is there another pure/functional way of implementing roundRobin?


问:
how to get point set (x,y) in a desired area in r

The figure is the plot of x,y set in a excel file, total 8760 pair of x and y. I want to remove the noise data pair in red circle area and output a new excel file with remain data pair. How could I do it in R?

答:
Using @G5W's example:

Make up data:

```<code>set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)
</code>```

Fit a quantile regression to the 90th percentile:

```<code>library(quantreg)
library(splines)
qq <- rq(y~ns(x,20),tau=0.9,data=XY)
</code>```

Compute and draw the predicted curve:

```<code>xvec <- seq(0,16,length.out=101)
pp <- predict(qq,newdata=data.frame(x=xvec))
plot(y~x,data=XY)
lines(xvec,pp,col=2,lwd=2)
</code>```

Keep only points below the predicted line:

```<code>XY2 <- subset(XY,y<predict(qq,newdata=data.frame(x)))

plot(y~x,data=XY2)
lines(xvec,pp,col=2,lwd=2)
</code>```

You can make the line less wiggly by lowering the number of knots, e.g. y~ns(x,10)

Body:
Using @G5W's example:

Make up data:

set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)

Fit a quantile regression to the 90th percentile:

library(quantreg)
library(splines)
qq <- rq(y~ns(x,20),tau=0.9,data=XY)

Compute and draw the predicted curve:

xvec <- seq(0,16,length.out=101)
pp <- predict(qq,newdata=data.frame(x=xvec))
plot(y~x,data=XY)
lines(xvec,pp,col=2,lwd=2)

Keep only points below the predicted line:

XY2 <- subset(XY,y<predict(qq,newdata=data.frame(x)))

plot(y~x,data=XY2)
lines(xvec,pp,col=2,lwd=2)

You can make the line less wiggly by lowering the number of knots, e.g. y~ns(x,10)


问:
Handlebars: Calling a helper within a call to another helper?
So I have 2 helpers, #hex works correctly when used separately, and #rgb also works correctly when a color has been passed directly.  However, ideally, I'd like to use my #hex helper within the call to the #rgb helper but I'm not having much luck.  Here's what I have so far.

Helper within helper - Doesn't work as expected:

```<code>{{#rgb {{#hex color}}{{/hex}} -0.25}}
</code>```

Example of what is expected of the above:

```<code>{{#rgb #abc123 -0.25}}
</code>```

Is this achievable within handlebars or would it be easier if I wrote a new helper that included both my #rgb helper and #hex helper?

答:
You can do this with parentheses rather than curly brackets:

```<code>{{helper1 (helper2 var1) var2}}
</code>```

Example:

// dummy helpers
Handlebars.registerHelper('rgb', function(color, opacity) {
  return color + ' ' + opacity;
});
Handlebars.registerHelper('hex', function(color) {
  return color + 'hexified';
});

// now in template
var template = '{{rgb (hex color) -0.25}}';
Handlebars.compile(template)({color: 'green'});
//Outputs "greenhexified -0.25"
```

Subexpressions docs

Body:
So I have 2 helpers, #hex works correctly when used separately, and #rgb also works correctly when a color has been passed directly.  However, ideally, I'd like to use my #hex helper within the call to the #rgb helper but I'm not having much luck.  Here's what I have so far.

Helper within helper - Doesn't work as expected:

{{#rgb {{#hex color}}{{/hex}} -0.25}}

Example of what is expected of the above:

{{#rgb #abc123 -0.25}}

Is this achievable within handlebars or would it be easier if I wrote a new helper that included both my #rgb helper and #hex helper?

Body:
You can do this with parentheses rather than curly brackets:

{{helper1 (helper2 var1) var2}}

Example:

// dummy helpers
Handlebars.registerHelper('rgb', function(color, opacity) {
  return color + ' ' + opacity;
});
Handlebars.registerHelper('hex', function(color) {
  return color + 'hexified';
});

// now in template
var template = '{{rgb (hex color) -0.25}}';
Handlebars.compile(template)({color: 'green'});
//Outputs "greenhexified -0.25"

Subexpressions docs


问:
Translucent with Navigation Bar in swift
I customized my navigation bar to clear. So I set the backgroundImage as UIImage() and isTranslucent = true. So the problem I got here is: That is what I set in my xib. Now TopConstraints is: 10px
With topConstraint = 10. When I run in simulator iPhone 5s: this is what i got. The screen is perfect. Although I remember that, if I set isTranslucent = true -> I must set topConstraint is higher more than navigation bar height, ex: topConstraint = 50.. But with this code, when I tried to run in real device: iPhone 5s. and this is what I got:
The navigation bar is cover the view. My simulator is run in iOS 11.0, and real device is run in iOS 9.2. Anyone have the same situation? Thanks so much

BTW: I need to set my navigation bar is clear because our background color is gradient color from top-left to bottom-right

答:
Remove backgroundImage as UIImage() and try this:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.backgroundColor = UIColor.clear
}
</code>```

And keep the topConstraint = 10

Body:
Remove backgroundImage as UIImage() and try this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.backgroundColor = UIColor.clear
}

And keep the topConstraint = 10


问:
Is there a way to move money between customers directly in Stripe?
Is it possible to move money between Stripe customers through ACH without having to use the merchant, myself, as an intermediary? </p>

答:
To facilitate payments through Stripe between users of product, you'd need to have them create Connect accounts. You can read about the process of making payouts in the stripe docs. It is currently impossible to transfer money between Customers.

It may be worth going through Stripe's list of prohibited businesses as "Money Transmitters" generally aren't allowed. Where here that is defined as transferring money without the sale of a good or service. If you want to know whether you'd run afoul of this, I recommend writing into Stripe's support.


问:
Getting asked twice to insert integer
I have some homework to do for the University, and since I'm a beginner I don't know how to code yet. So, there are 10 tests with the grade of each being between 0 and 10. I have to make sure that I don't get any negative number or a number greater than 10. while running the code I have to put 2 numbers in order to proceed to the next one, when, I clearly want just the one saved to A[i]. I hope you understand even though I can't even explain the problem. :)</p>

```<code>#include<stdio.h>

int main()
{
    int A[10];
    int i, j;
    for ( i = 1; i<11; i++)
    {
        printf("Enter %d grade \n", i);
        scanf("%d", &j);
        if (j<=10 && j>=0)
         A[i] = j;
        else
         printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
    }
}
</code>```

答: arrays start at index 0 in C so your for loop should go be for(i=0;i<10;i++)

Title: Getting asked twice to insert integer

Body:
I have some homework to do for the University, and since I'm a beginner I don't know how to code yet. So, there are 10 tests with the grade of each being between 0 and 10. I have to make sure that I don't get any negative number or a number greater than 10. while running the code I have to put 2 numbers in order to proceed to the next one, when, I clearly want just the one saved to A[i]. I hope you understand even though I can't even explain the problem. :)

#include<stdio.h>

int main()
{
    int A[10];
    int i, j;
    for ( i = 1; i<11; i++)
    {
        printf("Enter %d grade \n", i);
        scanf("%d", &j);
        if (j<=10 && j>=0)
         A[i] = j;
        else
         printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
    }
}


问:
Unit testing Rxjava observables that have a delay
I want to be able to unit test an Observable that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this?

I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.

Example:

```<code>val myObservable: PublishSubject<Boolean> = PublishSubject.create<Boolean>()
fun myObservable(): Observable<Boolean> = myObservable.delay(3, TimeUnit.SECONDS)

@Test
fun testMyObservable() {
    val testObservable = myObservable().test()
    myObservable.onNext(true)

    // val lock = CountDownLatch(1)
    // lock.await(3100, TimeUnit.MILLISECONDS)
    testObservable.assertValue(true)
}
</code>```

答:
I was able to come up with a complete solution thanks to @aaron-he's answer.

It uses a combination of TestScheduler to advance the time and also RxJavaPlugins to override the default scheduler with the testScheduler. This allowed testing the myObservable() function without modification or needing to pass in a Scheduler.

```<code>@Before
fun setUp() = RxJavaPlugins.reset()

@After
fun tearDown() = RxJavaPlugins.reset()

@Test
fun testMyObservable() {
    val testScheduler = TestScheduler()
    RxJavaPlugins.setComputationSchedulerHandler { testScheduler }

    val testObservable = myObservable().test()
    myObservable.onNext(true)

    testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    testObservable.assertEmpty()
    testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    testObservable.assertValue(true)
}
</code>```

Body:
I want to be able to unit test an Observable that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this?

I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.

Example:

val myObservable: PublishSubject<Boolean> = PublishSubject.create<Boolean>()
fun myObservable(): Observable<Boolean> = myObservable.delay(3, TimeUnit.SECONDS)

@Test
fun testMyObservable() {
    val testObservable = myObservable().test()
    myObservable.onNext(true)

    // val lock = CountDownLatch(1)
    // lock.await(3100, TimeUnit.MILLISECONDS)
    testObservable.assertValue(true)
}

Body:
I was able to come up with a complete solution thanks to @aaron-he's answer.

It uses a combination of TestScheduler to advance the time and also RxJavaPlugins to override the default scheduler with the testScheduler. This allowed testing the myObservable() function without modification or needing to pass in a Scheduler.

@Before
fun setUp() = RxJavaPlugins.reset()

@After
fun tearDown() = RxJavaPlugins.reset()

@Test
fun testMyObservable() {
    val testScheduler = TestScheduler()
    RxJavaPlugins.setComputationSchedulerHandler { testScheduler }

    val testObservable = myObservable().test()
    myObservable.onNext(true)

    testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    testObservable.assertEmpty()
    testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    testObservable.assertValue(true)
}


问:
Maven plugin for versioning and minifying javascript

Single Page Javascript Application

I have built a sophisticated ajax-driven single page webapp that uses a RESTful backend web service serving JSON. The javascript is split into many different files, each file representing some sort of feature or component.

While the service has been in alpha testing, I've just be serving all these files separately without minification. But now that I'd like to launch a beta version, I really need to combine files, minify them, and version them. I want to add this to my build process, using Maven.

Javascript File Types

I'm using the following "types" of javascript files, of which #3 and #4 are my concerns:

External files, such a jquery and jquery-ui served from the Google CDN. Rarely change these versions, can be handled manually.

Jquery plugins that I'm hosting myself, such as fullcalendar or ui-layout. Again, I rarely update these to new versions and can handle it manually.

Application-wide javascript code. Custom javascript that is spread across many files and can change occasionally. All of these files need to be loaded for the app to work.

Feature-specific javascript code. Custom javascript that is loaded on demand when a specific feature is requested. This code can change quite frequently and is not loaded at startup.

Build Objectives

I'd like to do the following during my build process:

Concatenate all type 3 javascript files together, minify them, and save as a single file with a version number. For instance: app-2.0.6.min.js, where 2.0.6 is the maven project version.

All type 4 files should be individually minified and saved as separate files with version numbers in the name. For instance: feature-abc-56ab32de29.min.js, where 56ab32de29 is the version number of that specific file.

Update HTML files with

答:
I've successfully incorporated RequireJS optimization (uses Google Closure compiler + does concatenation) in a Maven environment (for single page JS app). See my question and the follow up answer for details: RequireJS Compilation in Maven project with external JS dependencies

You could probably expand on that to version and archive the minified JS artifacts.


问:
RxJS marble test fails when using my own observable instead of creating one with the createHotObservable method
I am trying to create a simple test with RxJS marbles.

I am using mocha and chai.

I am instantiating a new test scheduler and I do not want to use the "testScheduler.createHotObservable method" because I want to use my own Observable, the "Observable.of(4)"

```<code> const testScheduler = new TestScheduler(assert.deepEqual.bind(assert));

      const expected = "a";
      const expectedStateMap = {
        a: 4
      };

      testScheduler.expectObservable(Observable.of(4)).toBe(expected, expectedStateMap);

      testScheduler.flush();
</code>```

This is the error:

```<code> AssertionError: expected [ Array(2) ] to deeply equal [ Array(1) ]
      + expected - actual

           "notification": {
             "error": [undefined]
             "hasValue": true
             "kind": "N"
      -      "value": 4
      +      "value": "4"
           }
         }
      -  {
      -    "frame": 0
      -    "notification": {
      -      "error": [undefined]
      -      "hasValue": false
      -      "kind": "C"
      -      "value": [undefined]
      -    }
      -  }
       ]

      at TestScheduler.flush (node_modules/rxjs/src/testing/TestScheduler.ts:135:12)
</code>```

Any ideas what is wrong?

答:
Yes, it doesn't work. What hot, cold observable creation method does is, creating observable based on given marble and setup internally inside of testscheduler. When testscheduler executes via flush, it iterates all observable and flush. If custom observable is provided, testscheduler doesn't know about existence of those observable and not flush those.

It is just limitation of current testscheduler implementation - unless monkey patch testscheduler to accept custom observable it may not work as expected.

Body:
I am trying to create a simple test with RxJS marbles.

I am using mocha and chai.

I am instantiating a new test scheduler and I do not want to use the "testScheduler.createHotObservable method" because I want to use my own Observable, the "Observable.of(4)"

 const testScheduler = new TestScheduler(assert.deepEqual.bind(assert));

      const expected = "a";
      const expectedStateMap = {
        a: 4
      };

      testScheduler.expectObservable(Observable.of(4)).toBe(expected, expectedStateMap);

      testScheduler.flush();

This is the error:

 AssertionError: expected [ Array(2) ] to deeply equal [ Array(1) ]
      + expected - actual

           "notification": {
             "error": [undefined]
             "hasValue": true
             "kind": "N"
      -      "value": 4
      +      "value": "4"
           }
         }
      -  {
      -    "frame": 0
      -    "notification": {
      -      "error": [undefined]
      -      "hasValue": false
      -      "kind": "C"
      -      "value": [undefined]
      -    }
      -  }
       ]

      at TestScheduler.flush (node_modules/rxjs/src/testing/TestScheduler.ts:135:12)

Any ideas what is wrong?


问:
How do I parse unknown encoding file?
I am trying to parse a file with extension with vmd (Vocaloid Motion Data 0002). I do not know what encoding it uses. I have attempted using UTF-8, UTF-16, CS_ASCII and Windows-31j (Shift JIS), but none of them worked (but based on what I know, most of UTF-8 should resolve since the byte is 2 for most of characters).

```<code>String testFile = rawFilePath+"/test.vmd";
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter(outputPath+"/newFile.txt");
bw = new BufferedWriter(fw);
BufferedReader fBr = new BufferedReader(new InputStreamReader(
    new FileInputStream(testFile), "UTF-8"));  //US-ASCII windows-31j
int count=0;
String line;
while ((line = fBr.readLine()) != null) {
    System.out.println(line);
    bw.write(line);
    bw.write("\r\n");
    count++;
    if(count > 3) { //print small portion of a larger file for testing
        break;
    }
    ...
}
</code>```

Both print and the output file writes something like this:

```<code>???~?N ??????????P ?Z???^?[    ??kkkkkkkk
</code>```

I was wondering if this is an encoding issue, or some other issue?  How do I parse readable data from this?

答:
Vocaloid Motion Data is binary data (as mentioned in the link you provided), so you can't just convert it to text and hope for the best. That means, you can't use readers but must use InputStreams. There is an InputStream called DataInputStream that can read ints and floats if they are encoded in VMD in the same way Java expects them to be. You can try it out, if reasonable values come up, you're golden, otherwise you have to read in the single bytes and calculate with the values to create the corresponding result yourself (e.g. if the data is least significant byte first ordering, etc.)

So code that reads in VMD could look like this (in lack of a real file, this should just be seen as illustration. There are things missing like checking that we actually read the number of bytes into the arrays or if we reached the end of the stream prematurely, etc.

```<code>try (FileInputStream fis = new FileInputStream(new File("rawFilePath", "test.vmd"))) {
    DataInputStream dis = new DataInputStream(fis);
    byte[] nameBytes = new byte[15];
    dis.read(nameBytes);
    int index = 0;
    for (int i = 0; i < nameBytes.length; i++) {
        if (nameBytes[i] == 0) {
            index = i;
            break;
        }
    }
    String name = new String(nameBytes, 0, index, "8859_1");
    // Java ints are signed, so to keep an unsigned int we need long
    long frameNumber = dis.readInt() & 0xffffffff;
    float boneXPosCoordinate = dis.readFloat();
    float boneYPosCoordinate = dis.readFloat();
    float boneZPosCoordinate = dis.readFloat();
    float boneXRotCoordinate = dis.readFloat();
    float boneYRotCoordinate = dis.readFloat();
    float boneZRotCoordinate = dis.readFloat();
    float boneWRotCoordinate = dis.readFloat();
    byte[] interpolationData = new byte[64];
    dis.read(interpolationData);
}
</code>```

Title: How do I parse unknown encoding file?

Body:
I am trying to parse a file with extension with vmd (Vocaloid Motion Data 0002). I do not know what encoding it uses. I have attempted using UTF-8, UTF-16, CS_ASCII and Windows-31j (Shift JIS), but none of them worked (but based on what I know, most of UTF-8 should resolve since the byte is 2 for most of characters).

String testFile = rawFilePath+"/test.vmd";
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter(outputPath+"/newFile.txt");
bw = new BufferedWriter(fw);
BufferedReader fBr = new BufferedReader(new InputStreamReader(
    new FileInputStream(testFile), "UTF-8"));  //US-ASCII windows-31j
int count=0;
String line;
while ((line = fBr.readLine()) != null) {
    System.out.println(line);
    bw.write(line);
    bw.write("\r\n");
    count++;
    if(count > 3) { //print small portion of a larger file for testing
        break;
    }
    ...
}

Both print and the output file writes something like this:

???~?N ??????????P ?Z???^?[    ??kkkkkkkk

I was wondering if this is an encoding issue, or some other issue?  How do I parse readable data from this?

Body:
Vocaloid Motion Data is binary data (as mentioned in the link you provided), so you can't just convert it to text and hope for the best. That means, you can't use readers but must use InputStreams. There is an InputStream called DataInputStream that can read ints and floats if they are encoded in VMD in the same way Java expects them to be. You can try it out, if reasonable values come up, you're golden, otherwise you have to read in the single bytes and calculate with the values to create the corresponding result yourself (e.g. if the data is least significant byte first ordering, etc.)

So code that reads in VMD could look like this (in lack of a real file, this should just be seen as illustration. There are things missing like checking that we actually read the number of bytes into the arrays or if we reached the end of the stream prematurely, etc.

try (FileInputStream fis = new FileInputStream(new File("rawFilePath", "test.vmd"))) {
    DataInputStream dis = new DataInputStream(fis);
    byte[] nameBytes = new byte[15];
    dis.read(nameBytes);
    int index = 0;
    for (int i = 0; i < nameBytes.length; i++) {
        if (nameBytes[i] == 0) {
            index = i;
            break;
        }
    }
    String name = new String(nameBytes, 0, index, "8859_1");
    // Java ints are signed, so to keep an unsigned int we need long
    long frameNumber = dis.readInt() & 0xffffffff;
    float boneXPosCoordinate = dis.readFloat();
    float boneYPosCoordinate = dis.readFloat();
    float boneZPosCoordinate = dis.readFloat();
    float boneXRotCoordinate = dis.readFloat();
    float boneYRotCoordinate = dis.readFloat();
    float boneZRotCoordinate = dis.readFloat();
    float boneWRotCoordinate = dis.readFloat();
    byte[] interpolationData = new byte[64];
    dis.read(interpolationData);
}