问:
making a code that can fill in automatically a list with restrictions
such as the content must be only of ones and zeros with a length of 7 variables and has to be different each time. I am a rookie at python ,at coding in general i know there is a way to do it but my knowledge is limited i really hadn't tried by my own but it because I dont have any clue at all

```<code>def variable_creator:
    auto_variable_list = [None]*7
    content = ['0','1']
    for auto_variable_list in content:
        "auto_variable_list return 7 length with content variables"
</code>```

The output that I expect is

```<code>list1=[0000000]
list2=[1000000]
list3=[0100000]
...
list128=[1111111]
</code>```

not necessarily in that particular order but don't violate this statement for every list needs to be different content for all the 127 list

答:
If you want all combinations of [0, 1] for a length of 7 then you can take the cartesian product of [0, 1] repeated 7 times, e.g.:

```<code>In []:
import itertools as it
list(it.product([0, 1], repeat=7))

Out[]:
[(0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 1),
 (0, 0, 0, 0, 0, 1, 0),
 (0, 0, 0, 0, 0, 1, 1),
 (0, 0, 0, 0, 1, 0, 0),
 ...
</code>```

You don't need to create independent variables for each item as you can just index them in the list:

```<code>In []:
vars = list(it.product([0, 1], repeat=7))
vars[0]

Out[]:
(0, 0, 0, 0, 0, 0, 0)
</code>```

If you do really need them named, then a dict would be the appropriate structure:

```<code>In []:
vars = {'List{}'.format(i): v for i, v in enumerate(it.product([0, 1], repeat=7), 1)}
vars['List128']

Out[]:
(1, 1, 1, 1, 1, 1, 1)
</code>```

Because you are just wanting a binary form of the number the alternative is just to convert the number to a binary string, e.g.:

```<code>In []:
[tuple(map(int, format(i, '07b'))) for i in range(128)]

Out[]:
[(0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 1),
 (0, 0, 0, 0, 0, 1, 0),
 (0, 0, 0, 0, 0, 1, 1),
 (0, 0, 0, 0, 1, 0, 0),
 ...
</code>```

Body:
such as the content must be only of ones and zeros with a length of 7 variables and has to be different each time. I am a rookie at python ,at coding in general i know there is a way to do it but my knowledge is limited i really hadn't tried by my own but it because I dont have any clue at all

def variable_creator:
    auto_variable_list = [None]*7
    content = ['0','1']
    for auto_variable_list in content:
        "auto_variable_list return 7 length with content variables"

The output that I expect is

list1=[0000000]
list2=[1000000]
list3=[0100000]
...
list128=[1111111]

not necessarily in that particular order but don't violate this statement for every list needs to be different content for all the 127 list

Body:
If you want all combinations of [0, 1] for a length of 7 then you can take the cartesian product of [0, 1] repeated 7 times, e.g.:

In []:
import itertools as it
list(it.product([0, 1], repeat=7))

Out[]:
[(0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 1),
 (0, 0, 0, 0, 0, 1, 0),
 (0, 0, 0, 0, 0, 1, 1),
 (0, 0, 0, 0, 1, 0, 0),
 ...

You don't need to create independent variables for each item as you can just index them in the list:

In []:
vars = list(it.product([0, 1], repeat=7))
vars[0]

Out[]:
(0, 0, 0, 0, 0, 0, 0)

If you do really need them named, then a dict would be the appropriate structure:

In []:
vars = {'List{}'.format(i): v for i, v in enumerate(it.product([0, 1], repeat=7), 1)}
vars['List128']

Out[]:
(1, 1, 1, 1, 1, 1, 1)

Because you are just wanting a binary form of the number the alternative is just to convert the number to a binary string, e.g.:

In []:
[tuple(map(int, format(i, '07b'))) for i in range(128)]

Out[]:
[(0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 1),
 (0, 0, 0, 0, 0, 1, 0),
 (0, 0, 0, 0, 0, 1, 1),
 (0, 0, 0, 0, 1, 0, 0),
 ...


来源: stackexchange

问:
Using job scheduler to repeat a job at specific time and then at specific intervals
Aim: Build an app that reminds me to punch in at the machine. It will start at 8 am, repeat at 10 minute intervals. Every time, it will use TexttoSpeech to remind me to punch in.

The basic service and the activity is in place. How can JobScheduler be run at a specific hour and minute, and then run a job every 10 minutes till a specific time?

```<code>public class Util {
    public static void scheduleJob(Context context) {
        ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    }
}

public class MyStartServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Util.scheduleJob(context);
    }
}

public class TestJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Intent service = new Intent(getApplicationContext(), TestVoice.class);
        getApplicationContext().startService(service);
        Util.scheduleJob(getApplicationContext()); // reschedule the job
        return true;
    }
    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}

public class TestVoice extends AppCompatActivity {
    TextToSpeech tts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED){
                        Log.e("error", "This Language is not supported");
                    }
                    else{
                        ConvertTextToSpeech("Have you punched in?");
                    }
                }
                else
                    Log.e("error", "Initilization Failed!");
            }
        });
    }
    private void ConvertTextToSpeech(String text) {
        // TODO Auto-generated method stub

        if(text==null||"".equals(text))
        {
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    }
}
</code>```

答:
How can JobScheduler be run at a specific hour and minute, and then run a job every 10 minutes till a specific time?

It can't.

JobScheduler is intrinsically inexact. You provide general guidance for when jobs should run, and the jobs run when they run.

Particularly on Android 6.0+, there is nothing that will meet your requirements, with the exception of setAlarmClock() on AlarmManager. However, using this has UI repercussions, as it is designed for alarm clock apps. Using it for your desired purpose may also interfere with any actual alarm clock app on the device (in case this is a BYOD scenario, instead of a company-issued device). Also, setAlarmClock() is a one-shot event; you would need to call setAlarmClock() again as part of processing the previous event, to schedule when you want to get control again.

ContentLicense: CC BY-SA 3.0

Body:
Aim: Build an app that reminds me to punch in at the machine. It will start at 8 am, repeat at 10 minute intervals. Every time, it will use TexttoSpeech to remind me to punch in.

The basic service and the activity is in place. How can JobScheduler be run at a specific hour and minute, and then run a job every 10 minutes till a specific time?

public class Util {
    public static void scheduleJob(Context context) {
        ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    }
}

public class MyStartServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Util.scheduleJob(context);
    }
}

public class TestJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Intent service = new Intent(getApplicationContext(), TestVoice.class);
        getApplicationContext().startService(service);
        Util.scheduleJob(getApplicationContext()); // reschedule the job
        return true;
    }
    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}

public class TestVoice extends AppCompatActivity {
    TextToSpeech tts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED){
                        Log.e("error", "This Language is not supported");
                    }
                    else{
                        ConvertTextToSpeech("Have you punched in?");
                    }
                }
                else
                    Log.e("error", "Initilization Failed!");
            }
        });
    }
    private void ConvertTextToSpeech(String text) {
        // TODO Auto-generated method stub

        if(text==null||"".equals(text))
        {
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    }
}


问:
Wordpress Images path are not working?
I have images working on one server, but they are not working on other server, I don't know what happened..

The images in style.css path is set like this below on both servers. i have rechecked.

```<code>.category{ background:url(../images/category-icon.png); background-size:100%;}
.tabs a:hover .category{ background:url(../images/category_dark-icon.png); background-size:100%;}
</code>```

But on server 1, it works and url becomes like this. It works.

```<code>http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/images/category-icon.png
</code>```

but on server 2, it is like this. This is not working.

```<code>http://demo.server2.com/projects/gamingcafe/wp-content/themes/images/category-icon.png
</code>```

My directory style is like this on both servers..

```<code>http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/css/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/images/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/js/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/less/
</code>```

same style on server2.

答:
It most likely is related to the location in which the style.css file resides.

On server1, is the style.css file in the root of your theme directory, or is it in a sub-directory?

Title: Wordpress Images path are not working?

Body:
I have images working on one server, but they are not working on other server, I don't know what happened..

The images in style.css path is set like this below on both servers. i have rechecked.

.category{ background:url(../images/category-icon.png); background-size:100%;}
.tabs a:hover .category{ background:url(../images/category_dark-icon.png); background-size:100%;}

But on server 1, it works and url becomes like this. It works.

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/images/category-icon.png

but on server 2, it is like this. This is not working.

http://demo.server2.com/projects/gamingcafe/wp-content/themes/images/category-icon.png

My directory style is like this on both servers..

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/css/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/images/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/js/

http://demo.server1.com/projects/gamingcafe/wp-content/themes/gamingcafe/less/

same style on server2.


问:
Java console error message while using test harness
I was trying to do the java tutorial on regexes and it had a test harness. I copied the code and tried to run it.

```<code>import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {
    public static void main(String[] args) {
        Console console = System.console();

        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }

        while (true) {
            Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
            Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
            boolean found = false;

            while (matcher.find()) {
                console.format("I found the text" +
                " \"%s\" starting at " +
                "index %d and ending at index %d.%n",
                matcher.group(),
                matcher.start(),
                matcher.end());
                found = true;
            }

            if (!found) {
                console.format("No match found.%n");
            }
        }
    }
}
</code>```

I get the following error message on my console

Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
  No console.

It's importing "console" and displaying the error on my console. So I am not sure why it is not creating a console.

The page can be found at: JAVA test Harness

答:
Here you have the code using the Scanner adapted for a Java compilator
(eclipse for me):</p>

```<code>import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;

/*
 * Test for regular expressions - Test Harness
 * List of commands and more info:
 * https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html
*/
public class RegexTestHarness {

    public static void main(String[] args){

            Scanner in = new Scanner(System.in);

            System.out.printf("%nEnter your regex: ");
            Pattern pattern =
            Pattern.compile(in.nextLine());

            System.out.printf("Enter input string to search: ");
            Matcher matcher =
            pattern.matcher(in.nextLine());

            boolean found = false;
            while (matcher.find()) {
                System.out.printf("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());
                found = true;
            }
            if(!found){
                System.out.printf("No match found.%n");
            }
            in.close();
        }

}
</code>```

Body:
I was trying to do the java tutorial on regexes and it had a test harness. I copied the code and tried to run it.

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {
    public static void main(String[] args) {
        Console console = System.console();

        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }

        while (true) {
            Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
            Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
            boolean found = false;

            while (matcher.find()) {
                console.format("I found the text" +
                " \"%s\" starting at " +
                "index %d and ending at index %d.%n",
                matcher.group(),
                matcher.start(),
                matcher.end());
                found = true;
            }

            if (!found) {
                console.format("No match found.%n");
            }
        }
    }
}

I get the following error message on my console

Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
  No console.

It's importing "console" and displaying the error on my console. So I am not sure why it is not creating a console.

The page can be found at: JAVA test Harness

Body:
Here you have the code using the Scanner adapted for a Java compilator
(eclipse for me):

import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;

/*
 * Test for regular expressions - Test Harness
 * List of commands and more info:
 * https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html
*/
public class RegexTestHarness {

    public static void main(String[] args){

            Scanner in = new Scanner(System.in);

            System.out.printf("%nEnter your regex: ");
            Pattern pattern =
            Pattern.compile(in.nextLine());

            System.out.printf("Enter input string to search: ");
            Matcher matcher =
            pattern.matcher(in.nextLine());

            boolean found = false;
            while (matcher.find()) {
                System.out.printf("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());
                found = true;
            }
            if(!found){
                System.out.printf("No match found.%n");
            }
            in.close();
        }

}


问:
How to create a summary using dictionaries based on an excel with empty cells using python? (vlookup with python)
I have an Excel spreadsheet. In column A I have an ID, column B I have the description.

The same ID and same text repeats x times, but the final row of that ID has no description. And then the ID changes.

Here is a screenshot of the file:

I want with Python to read downwards. When it finds a new ID, append it to a dictionary with its description, and then go to the next ID with its description.

It´s like the vlookup formula, but with Python.

答: You can load the data into pandas dataframe using read_excel, and then use fillna with method='ffill' on description column, after which you save the table. A three-liner, basically.


问:
How do I access environment variables in Vala?
How do I access environment variables in Vala? (as above)  it seems simple, but I can't find how g_getenv() is mapped into Vala.</p>

答:
The answer lies in the bindings file.  Vala uses bindings (in .vapi files) for binding its constructs to the C language.  In this case you can grep through glib-2.0.vapi (on my system that is in /usr/share/vala-0.10/vapi), and you'll see that it is bound as:

```<code>unowned string? GLib.Environment.get_variable(string name)
</code>```

It can be quite useful to have the location of the core VAPI files handy, because if you know the C name of a function you can just grep for it.

Body:
The answer lies in the bindings file.  Vala uses bindings (in .vapi files) for binding its constructs to the C language.  In this case you can grep through glib-2.0.vapi (on my system that is in /usr/share/vala-0.10/vapi), and you'll see that it is bound as:

unowned string? GLib.Environment.get_variable(string name)

It can be quite useful to have the location of the core VAPI files handy, because if you know the C name of a function you can just grep for it.

ContentLicense: CC BY-SA 2.5


问:
Intel HAXM installation error in VMWare
My own processor supports virtualisation:

I think i have activated it also in my bios settings.

And it is the info page of my processor of the vmware virtual machine i use (9.0.2 build-1031769)

Still, when i try to install Hardware Accelerated Execution Manager in order to start my android virtual devices, i take the following error:

What should i do?

答: I simply had to check 'virtualize intel vt-x/ept or amd-v/rvi' in my machine settings.

Title: Intel HAXM installation error in VMWare


问:
How to tell if a mobile page was designed specifically for mobile?
Is there a way to tell if a mobile page you've downloaded is just a desktop page modified with media queries, or is a separate page designed specifically for mobile? I'd like to go through a list of the "20 Best Mobile Pages" and see what percent were designed specially for mobile. </p>

答:
Google has a test specifically for this problem, it has API using REST, it can be used with Go,Java, Javascript, PHP, Python and Ruby:

https://developers.google.com/webmaster-tools/search-console-api/

I hope this helps.


问:
rmarkdown inline code vs. code chunk
I'm working with an rmarkdown document in Rstudio, where I'm noticing some differences in the behavior of inline R code from R code in a code chunk. For instance, if I use the function lubridate::now() in a code chunk, I see that the time zone is appended to the output when I knit the Rmd document. However, when I use the same R code, i.e., lubridate::now(), as inline code and knit the document, I see that the time zone is not included in the output. Can you help me to understand this difference?

Thanks.

答:
For inline code the 'decoration' is removed so that you can use a computed value in a sentence.
The chunks let you do a lot of processing, with or without displaying the outcome. If the code and the response are visible in the document, you can copy and paste it directly into the console and compare the outcomes. </p>

Title: rmarkdown inline code vs. code chunk


问:
Autofac InstancePerRequest scope in Azure Function
I am trying to have a dependency registered to share an instance per run of Eventhub triggered Azure Function (create new instance each time Azure function runs).

I tried register like below:

```<code>builder.RegisterType<TrialClass>().As<ITrialClass>().InstancePerRequest();
</code>```

But it fails saying

No scope with a tag matching 'AutofacWebRequest' is visible from the
  scope in which the instance was requested

Is there a way to handle this case ?

.

答:
Two issues here:

DI not truly supported in Azure Functions today, making registration and injection difficult.

Event Hubs triggered functions do not execute within the context of a web request, so to built in per request lifetime supported by Autofac would not work

If you have Autofac in a semi working state today, you can try @mjwills' suggestion and define a lifetime scope for a given invocation (this will not be as trivial as using the per request functionality, but doable).

We do have work happening in the WebJobs SDK and the Functions Host/Runtime to enhance the DI story. Some of the work is related or dependent on the .NET core migration you can track here.

Body:
I am trying to have a dependency registered to share an instance per run of Eventhub triggered Azure Function (create new instance each time Azure function runs).

I tried register like below:

builder.RegisterType<TrialClass>().As<ITrialClass>().InstancePerRequest();

But it fails saying

No scope with a tag matching 'AutofacWebRequest' is visible from the
  scope in which the instance was requested

Is there a way to handle this case ?

.


问:
Wordpress loading the_content() with the title
I have a blog page, and then an individual post page for each blog post.

On my Blog page, it shows all the posts with their titles:

```<code><div class="entry-content">
    <?php
        the_content();

        wp_link_pages( array(
        'before' => '<div class="page-links">' . __( 'Pages:', 'twentyseventeen' ),
        'after'  => '</div>',
        ) );
    ?>
</div>
</code>```

But on the individual blog post page, it only shows the image and the blog text, not the title:

```<code><div class="entry-content">
<?php
    /* translators: %s: Name of current post */
    the_content();

    wp_link_pages( array(
        'before'      => '<div class="page-links">' . __( 'Pages:', 'twentyseventeen' ),
        'after'       => '</div>',
        'link_before' => '<span class="page-number">',
        'link_after'  => '</span>',
    ) );

?>
</div>
</code>```

How come both call the_content(), but it returns differently? I need to also have the title of the post show on the individual blog post page.

答:
I think you need to add the_title() on your post page.

From the documentation: https://codex.wordpress.org/Function_Reference/the_title

Body:
I have a blog page, and then an individual post page for each blog post.

On my Blog page, it shows all the posts with their titles:

    <?php
        the_content();

        wp_link_pages( array(
        'before' => '
' . __( 'Pages:', 'twentyseventeen' ),
        'after'  => '
',
        ) );
    ?>

But on the individual blog post page, it only shows the image and the blog text, not the title:

<?php
    /* translators: %s: Name of current post */
    the_content();

    wp_link_pages( array(
        'before'      => '
' . __( 'Pages:', 'twentyseventeen' ),
        'after'       => '
',
        'link_before' => '',
        'link_after'  => '',
    ) );

?>

How come both call the_content(), but it returns differently? I need to also have the title of the post show on the individual blog post page.


问:
User Defined Filtering of HTML table built with XML/XSL
I am new to web development, and have found myself stuck on how to approach allowing website visitors to filter and sort an HTML table of publications that has been generated by XML/XSL.  Due to server constraints, I cannot use .php or ASP.NET - the data must remain a flat-file.

Here is the basic structure of the XML file:

```<code><xml>
  <records>
    <record>
       <contributors>
          <author>Author 1</author>
          <author>Author 2</author>
          <author>Author 3</author>
       </contributors>
       <title>Publication Title</title>
       <type>Publication Type</type>
       <keywords>Multiple Keywords</keywords>
       <year>1995</year>
       <abstract>Abstract Text Here</abstract>
   </record>
  </records>
</xml>
</code>```

And, my XSL:

```<code><table id="cvPubs">
  <thead>
      <tr>
        <th>Authors</th>
        <th>Title</th>
        <th>Type of Publication</th>
        <th>keywords</th>
        <th>Year</th>
        <th>Abstract</th>
      </tr>
  </thead>
  <tbody>
    <xsl:for-each select="descendant::record">
      <tr>
        <td><xsl:value-of select="keywords" /></td>
        <td><xsl:value-of select="contributors/*[position()]"  /></td>
        <td><xsl:value-of select="titles/title" /></td>
        <td><xsl:value-of select="abstract" /></td>
        <td><xsl:value-of select="titles/tertiary-title" /></td>
        <td><xsl:value-of select="year" /></td>
      </tr>
    </xsl:for-each>
  </tbody>
</table>
</code>```

I would like to add dropdown lists to the keyword field, and a user-defined text field to the contributors and abstract fields.

The XSL file outputs the table perfectly, I just don't know what the best approach is to building the filter and sort functionalities.  I've tried a few JavaScript and jQuery scripts for table sorting/filtering , but I can't get them to work properly. I don't get any errors, but I don't get the added functionality.

Any guidance would be greatly appreciated. Thanks for reading!

答:
I think you are going to get into a bit of a pickle if you keep going down the road of XSLT.

Yep, its been working fine as a transformation with a single table output that is relatively static, however now you want to add all the bells and whistles your XSLT is going to get increasingly complex and less useful than an all-purpose language since it is only meant for transformations.

I would recommend that, since you are stuck without server side code, you use the full capabilities of a native javascript library to handle the sorting on the client as well as the other functionality you are going to need on this page.

Ext JS comes to mind, but there are other examples such as Dojo or YUI that would serve you well too.

The component you are looking for is generally called a "Grid".

In Ext JS you can implement a GridPanel. Or if your data has more than 500 records in it use a Buffered GridPanel which is a similar implementation that only renders DOM for the rows that are being displayed.

Hope this is useful.

Body:
I am new to web development, and have found myself stuck on how to approach allowing website visitors to filter and sort an HTML table of publications that has been generated by XML/XSL.  Due to server constraints, I cannot use .php or ASP.NET - the data must remain a flat-file.

Here is the basic structure of the XML file:

<xml>
  <records>
    <record>
       <contributors>
          <author>Author 1</author>
          <author>Author 2</author>
          <author>Author 3</author>
       </contributors>
       <title>Publication Title</title>
       <type>Publication Type</type>
       <keywords>Multiple Keywords</keywords>
       <year>1995</year>
       <abstract>Abstract Text Here</abstract>
   </record>
  </records>
</xml>

And, my XSL:

        Authors
        Title
        Type of Publication
        keywords
        Year
        Abstract

    <xsl:for-each select="descendant::record">

        <xsl:value-of select="keywords" />
        <xsl:value-of select="contributors/*[position()]"  />
        <xsl:value-of select="titles/title" />
        <xsl:value-of select="abstract" />
        <xsl:value-of select="titles/tertiary-title" />
        <xsl:value-of select="year" />

    </xsl:for-each>

I would like to add dropdown lists to the keyword field, and a user-defined text field to the contributors and abstract fields.

The XSL file outputs the table perfectly, I just don't know what the best approach is to building the filter and sort functionalities.  I've tried a few JavaScript and jQuery scripts for table sorting/filtering , but I can't get them to work properly. I don't get any errors, but I don't get the added functionality.

Any guidance would be greatly appreciated. Thanks for reading!


问:
How to change ActionBar menu background color (android 4 & 5)
I've got one trouble while changing android design. I need to change action bar menu background color to black. I know, there are lots of answers for this question. I tried many of them. But nothing worked for me.

Oh, and i forgot to say, that i am not a very skilled android developer. Here's my styles file (v21)

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><style name="AppTheme" parent="@style/Theme.AppCompat.Light">
    <item name="colorPrimary">@color/mainColor</item>
    <item name="colorPrimaryDark">@color/secondaryColor</item>
    <item name="colorAccent">@color/goldColor</item>
    <item name="colorControlNormal">@color/mainColor</item>
    <item name="colorControlActivated">@color/secondaryColor</item>
    <item name="colorControlHighlight">@color/secondaryColor</item>
    <item name="android:navigationBarColor">@color/blackColor</item>
    <item name="colorSwitchThumbNormal">@color/secondaryTextColor</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:textColorPrimary">@color/goldColor</item>
    <item name="android:windowBackground">@color/blackColor</item>
    <item name="android:itemTextAppearance">@color/normalTextColor</item>
    <item name="android:buttonStyle">@style/ButtonStyle</item>
    <item name="android:actionMenuTextColor">@color/blackColor</item>
    <item name="actionMenuTextColor">@color/blackColor</item>
    <item name="android:actionBarPopupTheme">@style/Theme.Red.Widget</item>
    <item name="android:popupTheme">@color/blackColor</item>
</style>

<style name="Theme.Red.Widget" parent="@style/Theme.AppCompat">
    <item name="popupMenuStyle">@style/PopupMenu.Red</item>
    <item name="dropDownListViewStyle">@style/DropDownListView.Red</item>
</style>

<style name="PopupMenu.Red" parent="@style/Widget.AppCompat.PopupMenu">
    <item name="android:popupBackground">@color/blackColor</item>
</style>

<style name="DropDownListView.Red" parent="@style/Widget.AppCompat.ListView.DropDown">
    <item name="android:listSelector">@color/blackColor</item>
</style>

<color name="mainColor">#373737</color>
<color name="secondaryColor">#252525</color>
<color name="goldColor">#cea939</color>
<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>
<style name="ButtonStyle" parent="android:Widget.Button">
    <item name="android:background">@drawable/custom_btn</item>
</style>
</code>```

And here is my code for lower android releases.

```<code><resources>

<style name="AppTheme" parent="@style/Theme.AppCompat.Light">
    <item name="colorPrimary">@color/mainColor</item>
    <item name="colorPrimaryDark">#856f2d</item>
    <item name="colorAccent">@color/mainColor</item>
    <item name="colorControlNormal">@color/mainColor</item>
    <item name="colorControlActivated">#856f2d</item>
    <item name="colorControlHighlight">#856f2d</item>
    <item name="colorSwitchThumbNormal">@color/mainColor</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:textColorPrimary">@color/blackColor</item>
    <item name="android:textColorSecondary">@color/blackColor</item>
    <item name="android:textColorTertiary">@color/blackColor</item>
    <item name="android:windowBackground">@color/backgroundColor</item>
    <item name="android:itemTextAppearance">@color/normalTextColor</item>

    <item name="android:editTextBackground">@drawable/apptheme_edit_text_holo_light</item>
    <item name="android:textColorHighlight">#99cea939</item>
    <item name="android:textSelectHandleLeft">@drawable/apptheme_text_select_handle_left</item>
    <item name="android:textSelectHandleRight">@drawable/apptheme_text_select_handle_right</item>
    <item name="android:textSelectHandle">@drawable/apptheme_text_select_handle_middle</item>
    <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewAppTheme</item>
    <item name="android:listChoiceIndicatorMultiple">@drawable/apptheme_btn_check_holo_light</item>
    <item name="android:listChoiceIndicatorSingle">@drawable/apptheme_btn_radio_holo_light</item>
    <item name="android:buttonStyle">@style/ButtonAppTheme</item>
    <item name="android:imageButtonStyle">@style/ImageButtonAppTheme</item>
    <item name="android:dropDownSpinnerStyle">@style/SpinnerAppTheme</item>
    <item name="android:progressBarStyleHorizontal">@style/ProgressBarAppTheme</item>
    <item name="android:seekBarStyle">@style/SeekBarAppTheme</item>
    <item name="android:ratingBarStyle">@style/RatingBarAppTheme</item>
    <item name="android:ratingBarStyleIndicator">@style/RatingBarBigAppTheme</item>
    <item name="android:ratingBarStyleSmall">@style/RatingBarSmallAppTheme</item>
    <item name="android:buttonStyleToggle">@style/ToggleAppTheme</item>
    <item name="android:listChoiceBackgroundIndicator">@drawable/apptheme_list_selector_holo_light</item>
    <item name="android:activatedBackgroundIndicator">@drawable/apptheme_activated_background_holo_light</item>
    <item name="android:fastScrollThumbDrawable">@drawable/apptheme_fastscroll_thumb_holo</item>

</style>

<style name="SettingsToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorPrimary">@color/goldColor</item>
    <item name="actionMenuTextColor">@color/abc_primary_text_material_light</item>
    <item name="android:textColorSecondary">@color/goldColor</item>
</style>

<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>
<style name="AutoCompleteTextViewAppTheme" parent="android:Widget.Holo.Light.AutoCompleteTextView">
    <item name="android:dropDownSelector">@drawable/apptheme_list_selector_holo_light</item>
    <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
</style>
<style name="ButtonAppTheme" parent="android:Widget.Holo.Light.Button">
    <item name="android:background">@drawable/apptheme_btn_default_holo_light</item>
</style>
<style name="ImageButtonAppTheme" parent="android:Widget.Holo.Light.ImageButton">
    <item name="android:background">@drawable/apptheme_btn_default_holo_light</item>
</style>
<style name="SpinnerAppTheme" parent="android:Widget.Holo.Light.Spinner">
    <item name="android:background">@drawable/apptheme_spinner_background_holo_light</item>
    <item name="android:dropDownSelector">@drawable/apptheme_list_selector_holo_light</item>
</style>
<style name="TabAppTheme">
    <item name="android:gravity">center_horizontal</item>
    <item name="android:paddingLeft">16dip</item>
    <item name="android:paddingRight">16dip</item>
    <item name="android:background">@drawable/apptheme_tab_indicator_holo</item>
    <item name="android:layout_width">0dip</item>
    <item name="android:layout_weight">1</item>
    <item name="android:minWidth">80dip</item>
</style>
<style name="TabTextAppTheme">
    <item name="android:textColor">#000000</item>
    <item name="android:textSize">12sp</item>
    <item name="android:textStyle">bold</item>
    <!-- v14 <item name="android:textAllCaps">true</item> -->
    <item name="android:ellipsize">marquee</item>
    <item name="android:maxLines">2</item>
    <item name="android:maxWidth">180dip</item>
</style>
<style name="ProgressBarAppTheme" parent="android:Widget.Holo.Light.ProgressBar.Horizontal">
    <item name="android:progressDrawable">@drawable/apptheme_progress_horizontal_holo_light</item>
    <item name="android:indeterminateDrawable">@drawable/apptheme_progress_indeterminate_horizontal_holo_light</item>
</style>
<style name="SeekBarAppTheme" parent="android:Widget.Holo.Light.SeekBar">
    <item name="android:progressDrawable">@drawable/apptheme_scrubber_progress_horizontal_holo_light</item>
    <item name="android:indeterminateDrawable">@drawable/apptheme_scrubber_progress_horizontal_holo_light</item>
    <item name="android:thumb">@drawable/apptheme_scrubber_control_selector_holo_light</item>
</style>
<style name="RatingBarAppTheme" parent="android:Widget.Holo.Light.RatingBar">
    <item name="android:progressDrawable">@drawable/apptheme_ratingbar_full_holo_light</item>
    <item name="android:indeterminateDrawable">@drawable/apptheme_ratingbar_full_holo_light</item>
</style>
<style name="RatingBarBigAppTheme" parent="android:Widget.Holo.Light.RatingBar.Indicator">
    <item name="android:progressDrawable">@drawable/apptheme_ratingbar_holo_light</item>
    <item name="android:indeterminateDrawable">@drawable/apptheme_ratingbar_holo_light</item>
</style>
<style name="RatingBarSmallAppTheme" parent="android:Widget.Holo.Light.RatingBar.Small">
    <item name="android:progressDrawable">@drawable/apptheme_ratingbar_small_holo_light</item>
    <item name="android:indeterminateDrawable">@drawable/apptheme_ratingbar_small_holo_light</item>
</style>
<style name="ToggleAppTheme" parent="android:Widget.Holo.Light.Button.Toggle">
    <item name="android:background">@drawable/apptheme_btn_toggle_holo_light</item>
</style>
</code>```

I would be very thankful to you for any help.

答:
You can simply add the line like this:</p>

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <!-- To change the background of options menu-->
    <item name="android:itemBackground">*Your_color*</item>

</style>
</code>```

Body:
I've got one trouble while changing android design. I need to change action bar menu background color to black. I know, there are lots of answers for this question. I tried many of them. But nothing worked for me.

Oh, and i forgot to say, that i am not a very skilled android developer. Here's my styles file (v21)

<?xml version="1.0" encoding="utf-8"?>

<color name="mainColor">#373737</color>
<color name="secondaryColor">#252525</color>
<color name="goldColor">#cea939</color>

And here is my code for lower android releases.

<resources>

I would be very thankful to you for any help.

Body:
You can simply add the line like this:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <!-- To change the background of options menu-->
    <item name="android:itemBackground">*Your_color*</item>

</style>


问:
WPF / Console Hybrid Application
I writing an application what can either be run on the command line, or with a WPF UI.

```<code>[STAThread]
static void Main(string[] args)
{
    // Does magic parse args and sets IsCommandLine to true if flag is present
    ParseArgs(args);

    if(IsCommandLine)
    {
        // Write a bunch of things to the console
    }
    else
    {
        var app = new App();
        app.Run(new Window());
    }
}
</code>```

I set the project's Output type to Console Application, I get a console window that popups if I try to execute it by double-clicking the exe. I don't want to show the console window to the user if the flag is not set (passed in via command args).

However, if I set the project's Output type to Windows Application, the double-click behaviour is fine, but when I run it in the console, I get no console output (Console.Writeline)

答:
Create a WPF app and add the following code to your App class:</p>

```<code>public partial class App
{
    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args.Length > 0)
        {
            List<string> lowercaseArgs = e.Args.ToList().ConvertAll(x => x.ToLower());
            if (AttachConsole(ATTACH_PARENT_PROCESS))
            {
                // your console app code

                Console.Write("\rPress any key to continue...");
                Console.ReadKey();
                FreeConsole();
            }
            Shutdown();
        }
        else
        {
            base.OnStartup(e);
        }
    }

    private const int ATTACH_PARENT_PROCESS = -1;

    [DllImport("kernel32", SetLastError = true)]
    private static extern bool AttachConsole(int dwProcessId);

    [DllImport("kernel32.dll")]
    private static extern bool FreeConsole();
}
</code>```

Title: WPF / Console Hybrid Application

Body:
I writing an application what can either be run on the command line, or with a WPF UI.

[STAThread]
static void Main(string[] args)
{
    // Does magic parse args and sets IsCommandLine to true if flag is present
    ParseArgs(args);

    if(IsCommandLine)
    {
        // Write a bunch of things to the console
    }
    else
    {
        var app = new App();
        app.Run(new Window());
    }
}

I set the project's Output type to Console Application, I get a console window that popups if I try to execute it by double-clicking the exe. I don't want to show the console window to the user if the flag is not set (passed in via command args).

However, if I set the project's Output type to Windows Application, the double-click behaviour is fine, but when I run it in the console, I get no console output (Console.Writeline)

Body:
Create a WPF app and add the following code to your App class:

public partial class App
{
    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args.Length > 0)
        {
            List<string> lowercaseArgs = e.Args.ToList().ConvertAll(x => x.ToLower());
            if (AttachConsole(ATTACH_PARENT_PROCESS))
            {
                // your console app code

                Console.Write("\rPress any key to continue...");
                Console.ReadKey();
                FreeConsole();
            }
            Shutdown();
        }
        else
        {
            base.OnStartup(e);
        }
    }

    private const int ATTACH_PARENT_PROCESS = -1;

    [DllImport("kernel32", SetLastError = true)]
    private static extern bool AttachConsole(int dwProcessId);

    [DllImport("kernel32.dll")]
    private static extern bool FreeConsole();
}


问:
Best way to test a web application for multiple versions of browser using Selenium automation?
I have been doing a research for quite a sometime but unable to find a good solution - therefore thought of asking on StackOverflow.

I have automated the testing using Selenium Webdriver for different browser but lately I had seen there were some issues which came for Chrome's older version - now, the question I had was if there is any way through which I could run the script for different versions of browsers e.g. test should run on Chrome 48 - Chrome 59 (covering majors versions only).

The two solution I got from my research was -

1.
Overriding the chrome binary location like the below link:
https://stackoverflow.com/a/16562068/6738995

I then started my research on how to download the binaries for Chrome and I found the official repo also - http://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

2. Use Selenium Webdriver on cloud solution provider like BrowserStack or SauceLabs etc who provides multi-version-browser support

Now, I want to exhaust all the options related to the 1st approach i.e. if there is no proper/easy way to implement the solution then I would have go for the 2nd approach.

The reason I am reluctant to go for 2nd approach is that I might loose control(I am speculating that there might be some restrictions on using that platform, I might be wrong and could only find out the try after tring that) and also there will be learning curve associated with this and I would also have to spend time & resources in order to stabilize with the chosen technology.

Thanks in advance.

答: If resource isn't a concern/constraint for you, then you can use a Virtual Machine, like VMWare and simulate separate test environments with different web browsers. However, if you are looking for the best solution, then you have to use Cloud solutions like SauceLabs or BrowserStack.


问:
JSON object parse issue on react
```<code>json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
   json = JSON.stringify(json);
   model = new Model(json);
</code>```

it dosen't recognise the json object when it have quotes on

```<code> var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
</code>```

it works when removes quotes

```<code>   json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'};
</code>```

I have tried JSON.parse(json); it dosen't work, would anyone please suggest solution, please?

答:
Because you are trying to stringify a string no the object remove " " and it would become object and then try JSON.stringify and JSON.parse is not working because the data is not in proper JSON string format. For example:

var object = '{"e":"a"}';
Then use JSON.parse(object);
Which will convert your string in object.

Title: JSON object parse issue on react

Body:
json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
   json = JSON.stringify(json);
   model = new Model(json);

it dosen't recognise the json object when it have quotes on

 var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";

it works when removes quotes

   json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'};

I have tried JSON.parse(json); it dosen't work, would anyone please suggest solution, please?


问:
Change tab view with button
super new to coding. I followed a tutorial on creating tabs and fragments. My app right now has 3 tabs on the toolbar, and when clicked they change to their respective layout. I'd like to now add a button that will take me to those layouts instead of using the toolbar, so I can move it around and place it where I want.

This is what I have in my MainActivity

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

     //Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Main2Activity(), "TAB1");
    adapter.addFragment(new Main3Activity(), "TAB2");
    adapter.addFragment(new Main4Activity(), "TAB3");
    viewPager.setAdapter(adapter);
}
</code>```

So then I added this code for the button. In my XML, I placed the button above the container id so that I can always see it. Ideally, I'd have 3 buttons, each one putting into the container id Main2Activity, Main3Activity, and Main4Activity. Here is just 1 button as I try to figure out how to get the view to change.

```<code>public void onClickBtn1(View v){
    FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

    ft.replace(R.id.container, new Main2Activity());
    ft.commit();
}
</code>```

This is also my SectionsPageAdapter page if it helps.

```<code>public class SectionsPageAdapter extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

public SectionsPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}
}
</code>```

Thanks in advance!

答:
Call ViewPager#setCurrentItem in your on click to go to the index of the item in the viewpager's adapter's list/array:

```<code>public void onClickBtn1(View v){
    int gotoIndex = 0;
    mViewPager.setCurrentItem(gotoIndex, /*smoothscrolling*/ true);
}
</code>```

Title: Change tab view with button

Body:
super new to coding. I followed a tutorial on creating tabs and fragments. My app right now has 3 tabs on the toolbar, and when clicked they change to their respective layout. I'd like to now add a button that will take me to those layouts instead of using the toolbar, so I can move it around and place it where I want.

This is what I have in my MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

     //Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Main2Activity(), "TAB1");
    adapter.addFragment(new Main3Activity(), "TAB2");
    adapter.addFragment(new Main4Activity(), "TAB3");
    viewPager.setAdapter(adapter);
}

So then I added this code for the button. In my XML, I placed the button above the container id so that I can always see it. Ideally, I'd have 3 buttons, each one putting into the container id Main2Activity, Main3Activity, and Main4Activity. Here is just 1 button as I try to figure out how to get the view to change.

public void onClickBtn1(View v){
    FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

    ft.replace(R.id.container, new Main2Activity());
    ft.commit();
}

This is also my SectionsPageAdapter page if it helps.

public class SectionsPageAdapter extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

public SectionsPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}
}

Thanks in advance!

Body:
Call ViewPager#setCurrentItem in your on click to go to the index of the item in the viewpager's adapter's list/array:

public void onClickBtn1(View v){
    int gotoIndex = 0;
    mViewPager.setCurrentItem(gotoIndex, /*smoothscrolling*/ true);
}


问:
Can I start a windows form from a console program
I'd like to start a new windows form from a console program. Is this possible?</p>

答:
Use "start"

C:> start yourprogram.exe

Body:
Use "start"

C:> start yourprogram.exe


问:
How to group by multiple values in same column in Oracle DB
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

```<code>Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1
</code>```

I would like to group the customers based the same set of accesses. For eg:

```<code>USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2
</code>```

Currently, I have table created for some important users for this purpose as follows:

```<code>Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1
</code>```

And the below query comparing both tables.

```<code>select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)
</code>```

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.

答:
Agree with @jeff6times7 that you should reconsider your data model to make access group-driven, but in the meantime... you could generate a list of access privileges for each user using listagg():

```<code>select username, listagg(useraccess, ',') within group (order by useraccess) as groupaccess
from accesstab
group by username;

USERNAME GROUPACCESS
-------- --------------------
Cust1    BA1,BB2
Cust2    BA1,BB2
Cust3    BA1,CB1
</code>```

and generate the groups from the distinct aggregates:

```<code>select 'Group' || rownum as groupname, groupaccess
from (
  select distinct listagg(useraccess, ',') within group (order by useraccess) as groupaccess
  from accesstab
  group by username
  order by groupaccess
);

GROUPNAME GROUPACCESS
--------- --------------------
Group1    BA1,BB2
Group2    BA1,CB1
</code>```

and them join them together, e.g. with two CTEs:

```<code>with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
),
group_cte (groupname, groupaccess) as (
  select 'Group' || rownum, groupaccess
  from (
    select distinct listagg(useraccess, ',') within group (order by useraccess) as groupaccess
    from accesstab
    group by username
    order by groupaccess
  )
)
select u.username, g.groupname
from user_cte u
join group_cte g on g.groupaccess = u.groupaccess
order by u.username;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2
</code>```

Or you can use the first CTE to build the second so you only hit the actual table once:

```<code>with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
),
group_cte (groupname, groupaccess) as (
  select distinct 'Group' || dense_rank () over (order by groupaccess), groupaccess
  from user_cte
)
select u.username, g.groupname
from user_cte u
join group_cte g on g.groupaccess = u.groupaccess
order by u.username;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2
</code>```

or even without the second CTE:

```<code>with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
)
select distinct username,
  'Group' || dense_rank() over (order by groupaccess) as groupname
from user_cte;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2
</code>```

(... which is pretty much xQbert's approach)

You can also, if it's useful, include the aggregated groupaccess in the output to list the privileges in each group, but that doesn't seem to be required.

Of course, as soon as a user is added (or updated) with a different combination of accesses, a group will be generated (or removed!), and the numbering of existing groups may change - which may be confusing, but not an issue for you. If it is an issue then you're stuck with maintaining your intermediate table.

Body:
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1

I would like to group the customers based the same set of accesses. For eg:

USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2

Currently, I have table created for some important users for this purpose as follows:

Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1

And the below query comparing both tables.

select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.

Body:
Agree with @jeff6times7 that you should reconsider your data model to make access group-driven, but in the meantime... you could generate a list of access privileges for each user using listagg():

select username, listagg(useraccess, ',') within group (order by useraccess) as groupaccess
from accesstab
group by username;

USERNAME GROUPACCESS
-------- --------------------
Cust1    BA1,BB2
Cust2    BA1,BB2
Cust3    BA1,CB1

and generate the groups from the distinct aggregates:

select 'Group' || rownum as groupname, groupaccess
from (
  select distinct listagg(useraccess, ',') within group (order by useraccess) as groupaccess
  from accesstab
  group by username
  order by groupaccess
);

GROUPNAME GROUPACCESS
--------- --------------------
Group1    BA1,BB2
Group2    BA1,CB1

and them join them together, e.g. with two CTEs:

with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
),
group_cte (groupname, groupaccess) as (
  select 'Group' || rownum, groupaccess
  from (
    select distinct listagg(useraccess, ',') within group (order by useraccess) as groupaccess
    from accesstab
    group by username
    order by groupaccess
  )
)
select u.username, g.groupname
from user_cte u
join group_cte g on g.groupaccess = u.groupaccess
order by u.username;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2

Or you can use the first CTE to build the second so you only hit the actual table once:

with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
),
group_cte (groupname, groupaccess) as (
  select distinct 'Group' || dense_rank () over (order by groupaccess), groupaccess
  from user_cte
)
select u.username, g.groupname
from user_cte u
join group_cte g on g.groupaccess = u.groupaccess
order by u.username;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2

or even without the second CTE:

with user_cte (username, groupaccess) as (
  select username, listagg(useraccess, ',') within group (order by useraccess)
  from accesstab
  group by username
)
select distinct username,
  'Group' || dense_rank() over (order by groupaccess) as groupname
from user_cte;

USERNAME GROUPNAME
-------- ---------
Cust1    Group1
Cust2    Group1
Cust3    Group2

(... which is pretty much xQbert's approach)

You can also, if it's useful, include the aggregated groupaccess in the output to list the privileges in each group, but that doesn't seem to be required.

Of course, as soon as a user is added (or updated) with a different combination of accesses, a group will be generated (or removed!), and the numbering of existing groups may change - which may be confusing, but not an issue for you. If it is an issue then you're stuck with maintaining your intermediate table.


问:
What is format from url in AJAX to send POST method with RESPONSE ENTITY
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:

localhost:8080/name-project/insert?id=1&name=bobby

is the above url is correct? because I failed with this url. the parameter is id and name.

mycontroller:

```<code>@PostMapping(value={"/insertuser"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(@RequestBody UserEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabelUser(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}
</code>```

my daoimpl:

```<code>@Transactional
public String insertUser(UserEntity user) {
    return (String) this.sessionFactory.getCurrentSession().save(user);
}
</code>```

the code running in swagger (plugin maven) but not run in postman with above url.

Thanks.
Bobby

答: I'm not sure, but it seems that you try to pass data via get params (id=1&name=bobby), but using POST http method implies to pass data inside body of http request (in get params, as you did, data is passed in GET method) . So you have to serialize your user data on client side and add this serialized data to request body and sent it to localhost:8080/name-project/insert.</p>

Body:
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:

localhost:8080/name-project/insert?id=1&name=bobby

is the above url is correct? because I failed with this url. the parameter is id and name.

mycontroller:

@PostMapping(value={"/insertuser"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(@RequestBody UserEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabelUser(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}

my daoimpl:

@Transactional
public String insertUser(UserEntity user) {
    return (String) this.sessionFactory.getCurrentSession().save(user);
}

the code running in swagger (plugin maven) but not run in postman with above url.

Thanks.
Bobby


问:
Repeated looping of if/else statements in a function
I'm having trouble with repeated loops through if/else statements in an onclick function. It's a game where you have to say whether a word is valid or not and you keep going until you get one wrong.

What is happening though is the code goes through a branch of the if/else the same number of times as the questions you've done. So the first question once, second question twice and so on. So on the fifth question you'll get 5 alert boxes, and your score will increment by 5 instead of 1.

It is quite a long bit of code in total, which works otherwise (I've not done the hi-score bit yet) otherwise. I've put a shortened bit of it below where I think the problem must be.

The full thing is on http://www.absp.org.uk/test/study3lw.shtml

```<code>function quiz(){

...

    $('#true').on('click', function(){
        ...
        if (valid === true){          // ie got it right
            score++;
            alert(score);
            ...
        } else {                      // got it wrong
            ...
            score = 0;
            $('#word').append("*");
            alert("Game Over!");
        }
    });

    $('#false').on('click', function(){
        ...
        if (valid === false){         // ie got it right
            score++;
            alert(score);
            ...
        } else {                      // got it wrong
            score = 0;
            alert("Game Over!");
            ...
        }
    });

}

$('#start').on('click', function (){  // calls the above for each question
    ...
    quiz();
});
</code>```

答:
It looks like you're creating a new click event for each question, so by the fifth question, you have five event listeners for your buttons. I believe jQuery has .one() that will de-register the event after it's fired. Try using .one() instead of .on()

http://api.jquery.com/one/

Body:
I'm having trouble with repeated loops through if/else statements in an onclick function. It's a game where you have to say whether a word is valid or not and you keep going until you get one wrong.

What is happening though is the code goes through a branch of the if/else the same number of times as the questions you've done. So the first question once, second question twice and so on. So on the fifth question you'll get 5 alert boxes, and your score will increment by 5 instead of 1.

It is quite a long bit of code in total, which works otherwise (I've not done the hi-score bit yet) otherwise. I've put a shortened bit of it below where I think the problem must be.

The full thing is on http://www.absp.org.uk/test/study3lw.shtml

function quiz(){

...

    $('#true').on('click', function(){
        ...
        if (valid === true){          // ie got it right
            score++;
            alert(score);
            ...
        } else {                      // got it wrong
            ...
            score = 0;
            $('#word').append("*");
            alert("Game Over!");
        }
    });

    $('#false').on('click', function(){
        ...
        if (valid === false){         // ie got it right
            score++;
            alert(score);
            ...
        } else {                      // got it wrong
            score = 0;
            alert("Game Over!");
            ...
        }
    });

}

$('#start').on('click', function (){  // calls the above for each question
    ...
    quiz();
});


问:
How can I use the UIPinchGestureRecognizer with the entire view to zoom the entire screen? Swift 3, IOS
I can't seem to connect my action (pinch gesture) to my view, instead it connects to the viewcontroller. This is everything i have coded in the view controller to test out the code:

```<code>import UIKit

class AlertController: UIAlertController {

@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
    self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
    sender.scale = 1
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    view.backgroundColor = UIColor.blackColor()
}

override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()
}

}
</code>```

All i want to do is zoom into the form i fill out in my app (text boxes - buttons and labels, checkboxes - buttons and labels, background image - image view). I want to be able to zoom into everything at once. Im failing miserably. Please help! :)

答:
first make recognizer:

```<code>let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchHandler))
</code>```

then create handler function:

```<code>func pinchHandler(recognizer : UIPinchGestureRecognizer) {

    print ("PINCHING NOW")

    if let view = self.view {
        view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
        recognizer.scale = 1
    }
}
</code>```

inside viewDidLoad add recognizer:

```<code>pinchGestureRecognizer.addTarget(self, action: #selector(pinchHandler))
view.addGestureRecognizer(pinchGestureRecognizer)
</code>```

Body:
I can't seem to connect my action (pinch gesture) to my view, instead it connects to the viewcontroller. This is everything i have coded in the view controller to test out the code:

import UIKit

class AlertController: UIAlertController {

@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
    self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
    sender.scale = 1
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    view.backgroundColor = UIColor.blackColor()
}

override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()
}

}

All i want to do is zoom into the form i fill out in my app (text boxes - buttons and labels, checkboxes - buttons and labels, background image - image view). I want to be able to zoom into everything at once. Im failing miserably. Please help! :)

Body:
first make recognizer:

let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchHandler))

then create handler function:

func pinchHandler(recognizer : UIPinchGestureRecognizer) {

    print ("PINCHING NOW")

    if let view = self.view {
        view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
        recognizer.scale = 1
    }
}

inside viewDidLoad add recognizer:

pinchGestureRecognizer.addTarget(self, action: #selector(pinchHandler))
view.addGestureRecognizer(pinchGestureRecognizer)


问:
What is the best way to update two tables at the same time in SQL?
I have two tables. one is "Data" and another one is "AnalyzedData"

Two tables are for, first table "Data" is used to store basic data and another table to store details about analyzed data.

In "Data" table we have 3 columns - "DataID","DataName","AnalyzedDataID" (foreign key to "AnalyzedData")
in AnalyzedData table we have 3 columns. "AnalyzedDataID","AnalyzedataName"

Initially we have data in DataID and DataName colums. Later, after analyzing the data, We are inserting data into AnalyzedData table. So we need to update the AnalyzedDataID in Data table after inserting data into AnalyzedData table.

What's the best way to do this?

答:
One way is to start a transaction in your stored procedure. If any of the insert/updates fails, you rollback the transaction; otherwise, you COMMIT the transaction. So the recipe is:

```<code>1. Take the parameters you need in the stored proc
2. Start a transaction
3. Insert/Update each table independently
4. If no error, Commit the TRANSACTION; otherwise, ROLLBACK
</code>```

Some useful links:

Intro to Transactions

Best way to work with Transactions

Body:
One way is to start a transaction in your stored procedure. If any of the insert/updates fails, you rollback the transaction; otherwise, you COMMIT the transaction. So the recipe is:

1. Take the parameters you need in the stored proc
2. Start a transaction
3. Insert/Update each table independently
4. If no error, Commit the TRANSACTION; otherwise, ROLLBACK

Some useful links:

Intro to Transactions

Best way to work with Transactions


问:
smart way to do calculation near int overflow
Is there any smart way to fix this issue?

```<code>uint32_t a = 16637510;
uint32_t b = 45627362;
uint32_t c = 0;
c = a * 100000 / b //overflows
c = (a * 100/b)*1000 //gives 36000
</code>```

I need to get result c = 36463 or better 36464. And fast, non float operations are required. CPU is stm32f4

Update:

Accepted answer is converting 100000 to 100000ULL (64 bit) but as @PeterJ suggested (and deleted his answer) using stm32f4 FPU is faster then 64 dividing operations

```<code>Timer t;
int i;
t.start();
for(i = 1; i <= 100000; ++i) c = a * 100000ULL / b;
t.stop();
printf("64\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
t.start();
for(i = 1; i <= 100000; ++i) c = (uint32_t)((float)a * 100000.0f / (float)b);
t.stop();
printf("float\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
</code>```

64 takes 0.086669 seconds, du is 57333

  float  takes 0.017779 seconds, du is 57333

答:
How about this?

```<code>c = a * 100000ULL / b; // gives 36463
</code>```

See https://godbolt.org/g/aemCyw for the assembly that gcc generates for this operation and the original c = a * 100000 / b that overflows. Notice that __aeabi_uldivmod is used instead of __aeabi_uidiv.

Body:
Is there any smart way to fix this issue?

uint32_t a = 16637510;
uint32_t b = 45627362;
uint32_t c = 0;
c = a * 100000 / b //overflows
c = (a * 100/b)*1000 //gives 36000

I need to get result c = 36463 or better 36464. And fast, non float operations are required. CPU is stm32f4

Update:

Accepted answer is converting 100000 to 100000ULL (64 bit) but as @PeterJ suggested (and deleted his answer) using stm32f4 FPU is faster then 64 dividing operations

Timer t;
int i;
t.start();
for(i = 1; i <= 100000; ++i) c = a * 100000ULL / b;
t.stop();
printf("64\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
t.start();
for(i = 1; i <= 100000; ++i) c = (uint32_t)((float)a * 100000.0f / (float)b);
t.stop();
printf("float\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();

64 takes 0.086669 seconds, du is 57333

  float  takes 0.017779 seconds, du is 57333

Body:
How about this?

c = a * 100000ULL / b; // gives 36463

See https://godbolt.org/g/aemCyw for the assembly that gcc generates for this operation and the original c = a * 100000 / b that overflows. Notice that __aeabi_uldivmod is used instead of __aeabi_uidiv.


问:
How does -InputObject parameter of the Sort-Object cmdlet work?
PowerShell 4.0

I read about Sort-Object cmdlet here (TechNet page). I don't understand how to use -InputObject parameter. That page hasn't examples for it. Also I didn't find this info in Internet. I would be very grateful for the examples of its using, or for the links to Internet pages with that info.

I have tried to use it how I understand its purpose (according documentation):

```<code>$items = ('a','b','c','d')
$result = sort -InputObject $items -Descending
</code>```

But the result variable has the same value like it has items instead of its descended version.

Thank you.

答:
The process block of a function automatically deals with a collection over a pipe, but not if it's passed as a command line argument.  Some cmdlets put in an extra foreach loop to process -inputobject collections or lists, but most don't.

However, any parameter that can take input from a pipe, can also take a script block from the command line.  So that may come in handy some time.  You'll see examples like this in the help.

```<code>PS C:\> echo a,b,c,d | sort -InputObject { $_.ToUpper() } -Descending
D
C
B
A
</code>```

Body:
PowerShell 4.0

I read about Sort-Object cmdlet here (TechNet page). I don't understand how to use -InputObject parameter. That page hasn't examples for it. Also I didn't find this info in Internet. I would be very grateful for the examples of its using, or for the links to Internet pages with that info.

I have tried to use it how I understand its purpose (according documentation):

$items = ('a','b','c','d')
$result = sort -InputObject $items -Descending

But the result variable has the same value like it has items instead of its descended version.

Thank you.

Body:
The process block of a function automatically deals with a collection over a pipe, but not if it's passed as a command line argument.  Some cmdlets put in an extra foreach loop to process -inputobject collections or lists, but most don't.

However, any parameter that can take input from a pipe, can also take a script block from the command line.  So that may come in handy some time.  You'll see examples like this in the help.

PS C:\> echo a,b,c,d | sort -InputObject { $_.ToUpper() } -Descending
D
C
B
A


问:
Publishing jasmine test results using CI on TFS
I have created some tests using jasmine and chai for my nodejs application. I am looking at publishing the test results in TFS using CI build. Could somebody give me direction on how to go about it.

Example of the test that I have written

```<code>import chai from 'chai';
import sinon from 'sinon';
import  financialMapper from "../map/mappers/party-financials.mapper";
import * as _ from 'lodash';

var assert = chai.assert;
var expect = chai.expect;

let financials = { key: 160233,
  data:
   [ { companyId: 160233,
       dataItemName: 'Cash and Cash Equivalents, Beginning of Period',
       dataItemId: 2055,
       dataItemvalueUSD: 207217000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Preferred Dividend and Other Adjustments',
       dataItemId: 97,
       dataItemvalueUSD: 405000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Basic Earnings Per Share - Total',
       dataItemId: 3523,
       dataItemvalueUSD: 0.43728,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Net Property Plant And Equipment',
       dataItemId: 1004,
       periodTypeId: 4,
       dataItemvalueUSD: 123269000,
       fiscalYear: 2016,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Accounts Receivable, Total',
       dataItemId: 1021,
       dataItemvalueUSD: 892289000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Net Income - (IS)',
       dataItemId: 15,
       dataItemvalueUSD: 65517000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Accounts Payable, Total',
       dataItemId: 1018,
       dataItemvalueUSD: 246670000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Interest Expense',
       dataItemId: 208,
       dataItemvalueUSD: -17878000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 }]}

describe('party financials mapper test suit:', function () {

    it('should return an array of financials items', function () {
        let doc = financialMapper.map(financials).value[0]
        assert.isArray(doc);
    });
  it('should return financials with period id equal to 4', function () {
    let doc = financialMapper.map(financials).value[0]
    assert.equal(doc[0].historical[0].periodTypeId,4);
  });

    it('should return financials item with name equal to : <Interest Expense>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.isTrue(doc.name==='Interest Expense');
    });
    it('should return financials item with data item id equal to: <208>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.equal(doc.dataItemId,208);
    });

    it('should return financials item with current value equal to :<-17878000>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.equal(doc.current,-17878000);
    });

});
</code>```

答: I've used this package before. The example shows how to set it up for protractor but you can do the same thing with karma or whatever test runner you are using. Just set it up as a reporter so that it creates the xml file and then add the build step to publish the results. </p>

Body:
I have created some tests using jasmine and chai for my nodejs application. I am looking at publishing the test results in TFS using CI build. Could somebody give me direction on how to go about it.

Example of the test that I have written

import chai from 'chai';
import sinon from 'sinon';
import  financialMapper from "../map/mappers/party-financials.mapper";
import * as _ from 'lodash';

var assert = chai.assert;
var expect = chai.expect;

let financials = { key: 160233,
  data:
   [ { companyId: 160233,
       dataItemName: 'Cash and Cash Equivalents, Beginning of Period',
       dataItemId: 2055,
       dataItemvalueUSD: 207217000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Preferred Dividend and Other Adjustments',
       dataItemId: 97,
       dataItemvalueUSD: 405000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Basic Earnings Per Share - Total',
       dataItemId: 3523,
       dataItemvalueUSD: 0.43728,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Net Property Plant And Equipment',
       dataItemId: 1004,
       periodTypeId: 4,
       dataItemvalueUSD: 123269000,
       fiscalYear: 2016,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Accounts Receivable, Total',
       dataItemId: 1021,
       dataItemvalueUSD: 892289000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Net Income - (IS)',
       dataItemId: 15,
       dataItemvalueUSD: 65517000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Accounts Payable, Total',
       dataItemId: 1018,
       dataItemvalueUSD: 246670000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 },
     { companyId: 160233,
       dataItemName: 'Interest Expense',
       dataItemId: 208,
       dataItemvalueUSD: -17878000,
       fiscalYear: 2016,
       periodTypeId: 4,
       fiscalQuarter: 4 }]}

describe('party financials mapper test suit:', function () {

    it('should return an array of financials items', function () {
        let doc = financialMapper.map(financials).value[0]
        assert.isArray(doc);
    });
  it('should return financials with period id equal to 4', function () {
    let doc = financialMapper.map(financials).value[0]
    assert.equal(doc[0].historical[0].periodTypeId,4);
  });

    it('should return financials item with name equal to : <Interest Expense>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.isTrue(doc.name==='Interest Expense');
    });
    it('should return financials item with data item id equal to: <208>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.equal(doc.dataItemId,208);
    });

    it('should return financials item with current value equal to :<-17878000>', function () {
        let docs= financialMapper.map(financials).value[0]

        let doc = _.find(docs, (item)=>{
            return item.name==='Interest Expense'
        })
        assert.equal(doc.current,-17878000);
    });

});


问:
How to serve files from express 4.0 public folder as formatted html and not files, based on extension? E.g. format JSON, show images
Hey so anytime I place something in the "public" dir of my express directory, it automatically has a link on my webpage that I like. For example, going to https://website.com/image.jpg will allow me to download an image, and https://website.com/object.json will allow me to download a JSON file, without me having to do anything aside from place these files in my public folder. This is super convenient since I have another script that could be making a bunch of different things that I won't want to specify by name on my server every time I change something.

What I would like to do is modify this serve command so that when I want to retrieve an image, instead of automatically downloading it, it displays it in the browser. This should be as simple as adding an   around anything in the public folder that has the .png file ending. Likewise, I would like to stringify any JSON file so that it comes out in a readable format (JSON.stringify(object,null,2));

Basically, I would like to be able to just put something in my public folder and automatically be able to access it in a desirable way based on its file extension. In these two cases the "desirable" way is not downloading the file, but displaying it in-browser in a human-friendly format.

答:
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.

```<code>app.use(express.static(path.join('.', 'public')));
</code>```

Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.

```<code>var fs = require('fs');
app.use(function(req, res, next){
    fileName = req.url.substring('https://website.com/'.length);
    if(fs.existsSync('public/'+fileName){
        if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
            res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})
</code>```

As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'

Body:
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.

app.use(express.static(path.join('.', 'public')));

Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.

var fs = require('fs');
app.use(function(req, res, next){
    fileName = req.url.substring('https://website.com/'.length);
    if(fs.existsSync('public/'+fileName){
        if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
            res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})

As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'


问:
How to choose OpenCL implementation with CMake?
I have a Windows OpenCL application that uses some of the AMD extensions. Additionally, my application has some optional CUDA components. When building the visual studio solution with CMake, the FindOpenCL module picks the Nvidia OpenCL implementation instead of AMD's. Is there an easy way to make CMake use the AMD version?

I tried commenting the Nvidia sections in the FindOpenCL module code, but that did not work. Is there some registry setting I can modify? I installed CUDA after installing AMD's SDK. Would the installation order make a difference?

答:
In the end, what worked was to remove the NVIDIA environment variables from the PATHS suggestions in the find_library and find_path commands and adding the NO_DEFAULT_PATH. The issue was that, even though I removed the suggestions, CMake was adding the default path which included NVIDIA's OpenCL implementation. Both commands ended up like shown below:

```<code>find_path(OpenCL_INCLUDE_DIR
  NAMES
    CL/cl.h OpenCL/cl.h
    NO_DEFAULT_PATH
  PATHS
    ENV "PROGRAMFILES(X86)"
    ENV AMDAPPSDKROOT
    ENV ATISTREAMSDKROOT
  PATH_SUFFIXES
    include
    OpenCL/common/inc
    "AMD APP/include")

 find_library(OpenCL_LIBRARY
      NAMES OpenCL
      NO_DEFAULT_PATH
      PATHS
        ENV "PROGRAMFILES(X86)"
        ENV AMDAPPSDKROOT
        ENV ATISTREAMSDKROOT
      PATH_SUFFIXES
        "AMD APP/lib/x86_64"
        lib/x86_64
        lib/x64
        OpenCL/common/lib/x64)
</code>```

Body:
In the end, what worked was to remove the NVIDIA environment variables from the PATHS suggestions in the find_library and find_path commands and adding the NO_DEFAULT_PATH. The issue was that, even though I removed the suggestions, CMake was adding the default path which included NVIDIA's OpenCL implementation. Both commands ended up like shown below:

find_path(OpenCL_INCLUDE_DIR
  NAMES
    CL/cl.h OpenCL/cl.h
    NO_DEFAULT_PATH
  PATHS
    ENV "PROGRAMFILES(X86)"
    ENV AMDAPPSDKROOT
    ENV ATISTREAMSDKROOT
  PATH_SUFFIXES
    include
    OpenCL/common/inc
    "AMD APP/include")

 find_library(OpenCL_LIBRARY
      NAMES OpenCL
      NO_DEFAULT_PATH
      PATHS
        ENV "PROGRAMFILES(X86)"
        ENV AMDAPPSDKROOT
        ENV ATISTREAMSDKROOT
      PATH_SUFFIXES
        "AMD APP/lib/x86_64"
        lib/x86_64
        lib/x64
        OpenCL/common/lib/x64)


问:
MSSQL Stored procedure conversion to MySQL
Site is already built in .Net where it is using SQL server stored procedure. Now we are converting into PHP for that we are also altering stored procedure in MySQL.

In one of stored procedure there is some code to multiple insert and update which is achieved in SQL stored procedure as follows:

```<code>MERGE
    INTO products T
    USING SELECT STATEMENT
WHEN MATCHED
    THEN UPDATE STATEMENT
WHEN NOT MATCHED
        THEN INSERT STATEMENT
</code>```

I need an alternative to this approach in MySQL stored procedure syntax. Please guide me through how can I achieve this.

答:
You should be able to replace this with on duplicate key update.

For this, you will need a unique key on the columns that specify "matched".

Note:  This will (definitely) not replace all merge code.  However, your example seems like it is implementing exactly this logic.  Otherwise, you can use if with update and insert statements to pretty much do the same thing.

Body:
Site is already built in .Net where it is using SQL server stored procedure. Now we are converting into PHP for that we are also altering stored procedure in MySQL.

In one of stored procedure there is some code to multiple insert and update which is achieved in SQL stored procedure as follows:

MERGE
    INTO products T
    USING SELECT STATEMENT
WHEN MATCHED
    THEN UPDATE STATEMENT
WHEN NOT MATCHED
        THEN INSERT STATEMENT

I need an alternative to this approach in MySQL stored procedure syntax. Please guide me through how can I achieve this.