问:
Json connection to Angular Js .success() is not a function Error
```<code>$http.get('data/stock.json').success(function(data){
    $scope.stock = data;
})
</code>```

and i also tried this

```<code>$http.get('data/stock.json').then(function(data){
    $scope.stock = data;
})
</code>```

my Data is in stock.json file no problem in HTML which is working and i m working on angular 1.6 version

答:
In Angular 1.6, The $http legacy promise methods success and error have been deprecated. So you have to use the standard then method instead. So change your code like this:</p>

```<code>$http.get('data/stock.json').then(function(data){
    $scope.stock = data.data;
})
</code>```

Body:
$http.get('data/stock.json').success(function(data){
    $scope.stock = data;
})

and i also tried this

$http.get('data/stock.json').then(function(data){
    $scope.stock = data;
})

my Data is in stock.json file no problem in HTML which is working and i m working on angular 1.6 version

Body:
In Angular 1.6, The $http legacy promise methods success and error have been deprecated. So you have to use the standard then method instead. So change your code like this:

$http.get('data/stock.json').then(function(data){
    $scope.stock = data.data;
})


来源: stackexchange

问:
Program for working with large CSV Files
Are there any good programs for dealing with reading large CSV files?  Some of the datafiles I deal with are in the 1 GB range. They have too many lines for Excel to even deal with. Using Access can be a little slow, as you have to actually import them into a database to work with them directly.  Is there a program that can open large CSV files and give you a simple spreadsheet layout to help you easily and quickly scan through the data?</p>

答:
If you can fit the data into memory and you like python then I recommend checking out the UniTable portion of Augustus.  (Disclaimer: Augustus is open source (GPLv2) but I work for the company that writes it.)

It's not very well documented but this should help you get going.

```<code>from augustus.kernel.unitable import *
a = UniTable().from_csv_file('filename')
b = a.subtbl(a['key'] == some_value) #creates a subtable
</code>```

It won't directly give you an excel like interface but with a little bit of work you can get many statistics out quickly.

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

Body:
If you can fit the data into memory and you like python then I recommend checking out the UniTable portion of Augustus.  (Disclaimer: Augustus is open source (GPLv2) but I work for the company that writes it.)

It's not very well documented but this should help you get going.

from augustus.kernel.unitable import *
a = UniTable().from_csv_file('filename')
b = a.subtbl(a['key'] == some_value) #creates a subtable

It won't directly give you an excel like interface but with a little bit of work you can get many statistics out quickly.

OwnerDisplayName: David


问:
Hand Coded GUI Versus Qt Designer GUI
I'm spending these holidays learning to write Qt applications. I was reading about Qt Designer just a few hours ago, which made me wonder : what do people writing real world applications in Qt use to design their GUIs? In fact, how do people design GUIs in general?

I, for one, found that writing the code by hand was conceptually simpler than using Qt Designer, although for complex GUIs Designer might make sense. Large GUIs might be possible using Designer, but with time they might become very difficult to manage as complexity increases (this is just my opinion). I also downloaded the AmaroK source code to take a peek at what those guys were doing, and found many calls to addWidget() and friends, but none of those XML files created by Designer (aside: AmaroK has to be my favorite application ever on any platform).

What, then, is the "right" way to create a GUI? Designer or code? Let us, for this discussion, consider the following types of GUIs :

Simple dialogs that just need to take input, show some result and exit. Let's assume an application that takes a YouTube URL and downloads the video to the user's hard disk. The sort of applications a newbie is likely to start out with.

Intermediate level GUIs like, say, a sticky notes editor with a few toolbar/menu items. Let's take xPad for example (http://getxpad.com/). I'd say most applications falling in the category of "utilities".

Very complex GUIs, like AmaroK or OpenOffice. You know 'em when you see 'em because they make your eyes bleed.

答:
I'd add that one of the reasons for using graphical designer was the lack of layout managers in Win32, for instance. Only absolute positioning was possible, and doing that by hand would have just sucked.

Since I switched from Delphi to Java for GUI apps (back in 2002), I've never used designers any more. I like layout managers much more. And yeah, you get boilerplate code, but moving objects on a UI designer may take as much time as changing the boilerplate. Plus, I would be stuck with a slow IDE; that's for the Java/C# case, OK, while for Qt (especially Qt4) it doesn't apply. For Qt3, I wonder why one should edit the generated code - wasn't it possible to add code in other files? For which reason?

About the discussed cases:
1) Hand Coded GUI is likely faster to write, at least if you know your libraries. If you're a newbie and you don't know them, you may save time and learn less with a designer, since you don't need to learn the APIs you use. But "learn less" is the key factor, so in both cases I'd say Hand Coded GUI.

2) Menu bars are quite annoying to write code for. Also, think to details like accelerators and so on. Still, it depends on what you're used to. After some time, it may be faster to type that boilerplate than to point-and-click into designer to fix all those properties, but just if you can really type like into a typewriter (like those admins for which typing Unix commands is faster than using any GUI).

3) I'd extend the answer for case #2 to this one. Note that, for Win32 platforms, it may be possible that using designers which generate Win32 resources might be faster to load (no idea about that).

However, I'd like to mention a potential problem with using Qt Designer there. Real world case: it took some seconds (say 10) to load a complex Java dialog (the Preferences dialog box for a programmer's text editor) with a lot of options. The correct fix would have been to load each of the tabs only when the programmer wanted to see them (I realized that after), by adding a separate method to each preference set to build its GUI.

If you design all the tabs and the tab switcher together with a designer, can you do that as easily? I guess there might be a similar example where a hand coded GUI gives you more flexibility, and in such a big app, you're likely to need that, even if just for optimization purposes.

OwnerDisplayName: General Maximus

Title: Hand Coded GUI Versus Qt Designer GUI

OwnerDisplayName: Blaisorblade


问:
Passing function as parameter in c# works but not in vb.net?
So I have the following line of code in c# to register AutoMapper with SimpleInjector:

container.Register(() => config.CreateMapper(container.GetInstance));

For context, config.CreateMapper() looks like this:

public IMapper CreateMapper(Func<Type, object> serviceCtor);

While container.GetInstance looks like this:

public object GetInstance(Type serviceType);

The first line of code I posted works in C# because config.CreateMapper takes in a function that takes a type of Type and returns a type of object. Exactly what container.GetInstance does.

When I try to do this same line in VB, as:

container.Register(Function() config.CreateMapper(container.GetInstance))

It gives an error Type arguments for 'Public Function Container.GetInstance(Of TService)()' cannot be inferred from the usage. Try specifying type arguments explicitly. It is giving this error because container.GetInstance has an overload that looks like this:

public TService GetInstance<TService>() where TService : class;

Why does the VB try to use the wrong overload of GetInstance and how can I force it to use the correct one?

答:
Use the AddressOf keyword before the function parameter to define this as Parameter as function pointer.

AddressOf ist the same as @ keyword in C#. The keyword is implicit used in your c# sample.

ContentLicense: CC BY-SA 3.0


问:
C++ OpenCV mouseCallback on inheritance class
Consider the Base class, and the two Child classes:

```<code>class Base
{
public:
    ~Base() = default;

    virtual void mouseCallback() = 0; // this is overriden by the Childs!

    void mouseCallback2() { std::cout << "mouseCallback2 OK" << std::endl; }//Not overriden
};

class Child1 : public Base
{
public:
    ~Child1() = default;

    void mouseCallback() override;
};

class Child2 : public Base
{
public:
    ~Child2() = default;

    void mouseCallback() override;
};
</code>```

Where the implementation is:

```<code>void Child1::mouseCallback()
{
    std::cout << "Child 1 OK" << std::endl;
}

void Child2::mouseCallback()
{
    std::cout << "Child 2 OK" << std::endl;
}
</code>```

I have my CameraVision class:

```<code>class CameraVision
{
public:
   // ...
   void init();
   static void callback(int event, int x, int y, int flags, void* userdata);
private:
   Base* mBase; // A pointer to the Base class!
}
</code>```

Which contains the init() method as follows:

```<code>void CameraVision::init()
{
    mBase = new Child1();

    // Here I set the callback
    cv::setMouseCallback("Title", callback, &mBase);
}
</code>```

So that when the mouse has an event I have this, the overriden method crashes my application.

```<code>void CameraVision::callback(int event, int x, int y, int flags, void* userdata)
{
    if (event == cv::EVENT_LBUTTONDOWN)
    {
        Base* tof = static_cast<Base*>(userdata);

        tof->mouseCallback2(); // THIS WORKS!

        // But this is what I need
        tof->mouseCallback(); // ERROR!!!!!!
    }

}
</code>```

Why I can't use the mouseCallback() using inheritance of Child1?

I'm getting an error:

```<code>Exception thrown at 0x000000013F391938 in Demo.exe: 0xC0000005: Access violation executing location 0x000000013F391938
</code>```

I was expecting the output:

```<code>mouseCallback2 OK
Child 1 OK
</code>```

答:
mBase is type Base*, then you don't need to use &, simply
cv::setMouseCallback("Title", callback, mBase);

&mBase will give you a pointer to a pointer, so your static_cast doesn't give you back the original mBase pointer, but its address. Not sure how the first callback worked, both should result in UB.

Body:
Consider the Base class, and the two Child classes:

class Base
{
public:
    ~Base() = default;

    virtual void mouseCallback() = 0; // this is overriden by the Childs!

    void mouseCallback2() { std::cout << "mouseCallback2 OK" << std::endl; }//Not overriden
};

class Child1 : public Base
{
public:
    ~Child1() = default;

    void mouseCallback() override;
};

class Child2 : public Base
{
public:
    ~Child2() = default;

    void mouseCallback() override;
};

Where the implementation is:

void Child1::mouseCallback()
{
    std::cout << "Child 1 OK" << std::endl;
}

void Child2::mouseCallback()
{
    std::cout << "Child 2 OK" << std::endl;
}

I have my CameraVision class:

class CameraVision
{
public:
   // ...
   void init();
   static void callback(int event, int x, int y, int flags, void* userdata);
private:
   Base* mBase; // A pointer to the Base class!
}

Which contains the init() method as follows:

void CameraVision::init()
{
    mBase = new Child1();

    // Here I set the callback
    cv::setMouseCallback("Title", callback, &mBase);
}

So that when the mouse has an event I have this, the overriden method crashes my application.

void CameraVision::callback(int event, int x, int y, int flags, void* userdata)
{
    if (event == cv::EVENT_LBUTTONDOWN)
    {
        Base* tof = static_cast<Base*>(userdata);

        tof->mouseCallback2(); // THIS WORKS!

        // But this is what I need
        tof->mouseCallback(); // ERROR!!!!!!
    }

}

Why I can't use the mouseCallback() using inheritance of Child1?

I'm getting an error:

Exception thrown at 0x000000013F391938 in Demo.exe: 0xC0000005: Access violation executing location 0x000000013F391938

I was expecting the output:

mouseCallback2 OK
Child 1 OK


问:
Analyze a tensorflow graph or a .pb file on Tensorboard
I have been following github repository for "Tensorflow on Android".

I was able to build the code using bazel and then import the Android project to Android Studio, as mentioned here.

As you can see here, after building the APK, using Android Studio, the Model files/Graphs are included in the tensorflow/examples/android/assets

By default, tensorflow_inception_graph.pb and imagenet_comp_graph_label_strings.txt are included, from inception5 file which is downloaded while the APK is built.

What's the issue?

I have a retrained graph (InceptionV3 model, mentioned in tensorflow/examples/image_retraining/retrain.py), which I was able to place in the assets folder in android directory and generate a working APK.

Inference time while I was using the default graph or .pb file was ~500ms and with my retrained.pb or graph it is ~1400ms.(tested on OnePlus3T device)

Please help me understand

How to analyze the default tensorflow_inception_graph.pb on Tensorboard

答:
Last May they have introduced a helper script called import_pb_to_tensorboard to do just that.

```<code>usage: import_pb_to_tensorboard.py [-h] [--model_dir MODEL_DIR]
                                   [--log_dir LOG_DIR]

optional arguments:
  -h, --help            show this help message and exit
  --model_dir MODEL_DIR
                        The location of the protobuf ('pb') model to
                        visualize.
  --log_dir LOG_DIR     The location for the Tensorboard log to begin
                        visualization from.
</code>```

Note that currently, the version in master seems to have received more love than the one present in the latest 1.2.1 distribution of tensorflow, so I would suggest to use this one.

Body:
Last May they have introduced a helper script called import_pb_to_tensorboard to do just that.

usage: import_pb_to_tensorboard.py [-h] [--model_dir MODEL_DIR]
                                   [--log_dir LOG_DIR]

optional arguments:
  -h, --help            show this help message and exit
  --model_dir MODEL_DIR
                        The location of the protobuf ('pb') model to
                        visualize.
  --log_dir LOG_DIR     The location for the Tensorboard log to begin
                        visualization from.

Note that currently, the version in master seems to have received more love than the one present in the latest 1.2.1 distribution of tensorflow, so I would suggest to use this one.


问:
PHP check for a duplicate files in a DIR and write them in a txt
I need to find a duplicate files and write them in a txt file. I almost got it but I can't resolve 4 things.

Every new value must be written in a new line.

An array must be [fileName]=>"fileHash" (Watch p.3)

Write in a txt fileName (a key), not a fileHash.

Why is the first 2 values of $files are . and .. ? They are equal to an empty string.

```<code>//get a files array
$files = scandir(__DIR__);

//key=value
$result = array_combine($files, $files);

//get an array of filee hashes
$hashArr = [];
foreach ($result as $file) {
    $file = md5_file($file);
    array_push($hashArr, $file);
}

//search for duplicates
$arr_unique = array_unique($hashArr);
$arr_duplicates = array_diff_assoc($hashArr, $arr_unique);

//write duplicates in a file
$result = "values.txt";
file_put_contents($result,$arr_duplicates);
</code>```

In "values.txt" I have

a9f238ec88777a129c1b6ad4ceeef77c57c90c48a63620442e5bddb2764585cb

I tried to make something like this

```<code>$fp = fopen('values.txt', 'a+');
fwrite($fp, $arr_duplicates."\r\n");
fclose($fp);
//or
file_put_contents($result,$arr_duplicates . "\r");
</code>```

but it writes "Array" in my TXT instead of values.
Any help will be appreciated.

答:
```<code>//get a files array
$files = scandir(__DIR__);

//key=value no need
// $result = array_combine($files, $files);
unset($files[array_search('.',$files)],$files[array_search('..',$files)]);

//get an array of filee hashes
$hashArr = [];
    foreach ($files as $file) {
    $fileHash = md5_file($file);
    $hashArr[$file] = $fileHash;
//    array_push($hashArr, $file);
}

//search for duplicates
$arr_unique = array_unique($hashArr);
$arr_duplicates = array_diff_assoc($hashArr, $arr_unique);
//write duplicates in a file
$fp = fopen('values.txt', 'a+');
foreach($arr_duplicates as $fileName=>$fileHash) {
    fwrite($fp, $fileName."\r\n");
}
fclose($fp);
</code>```

Body:
I need to find a duplicate files and write them in a txt file. I almost got it but I can't resolve 4 things.

Every new value must be written in a new line.

An array must be [fileName]=>"fileHash" (Watch p.3)

Write in a txt fileName (a key), not a fileHash.

Why is the first 2 values of $files are . and .. ? They are equal to an empty string.

//get a files array
$files = scandir(__DIR__);

//key=value
$result = array_combine($files, $files);

//get an array of filee hashes
$hashArr = [];
foreach ($result as $file) {
    $file = md5_file($file);
    array_push($hashArr, $file);
}

//search for duplicates
$arr_unique = array_unique($hashArr);
$arr_duplicates = array_diff_assoc($hashArr, $arr_unique);

//write duplicates in a file
$result = "values.txt";
file_put_contents($result,$arr_duplicates);

In "values.txt" I have

a9f238ec88777a129c1b6ad4ceeef77c57c90c48a63620442e5bddb2764585cb

I tried to make something like this

$fp = fopen('values.txt', 'a+');
fwrite($fp, $arr_duplicates."\r\n");
fclose($fp);
//or
file_put_contents($result,$arr_duplicates . "\r");

but it writes "Array" in my TXT instead of values.
Any help will be appreciated.


问:
How to print the #define statement?
How can I get cerr to print 5 < 6 as opposed to statement_? I have access to Boost and Qt.

```<code>using namespace std;

#define some_func( statement_ )               \
  if( ! statement_ )                          \
  {                                           \
    throw runtime_error( "statement_" );      \
  }                                           \

int main()
{
  try
  {
    some_func( 5 < 6 );
  }
  catch(std::exception& e)
  {
    cerr << e.what();
  }
}
</code>```

答:
Oh, I found this.

and here's the final working code =):

```<code>#include <stdexcept>
#include <iostream>

#define some_func( statement_ )              \
  if( ! statement_ )                         \
  {                                          \
    throw std::runtime_error( #statement_ ); \
/* Note: #, no quotes!       ^^^^^^^^^^  */  \
  }                                          \

int main(int argc, char** argv)
{
  try
  {
    some_func( 5 < 6 );
  }
  catch(std::exception& e)
  {
    std::cerr << e.what();
  }
}
</code>```

Title: How to print the #define statement?

Body:
How can I get cerr to print 5 < 6 as opposed to statement_? I have access to Boost and Qt.

using namespace std;

#define some_func( statement_ )               \
  if( ! statement_ )                          \
  {                                           \
    throw runtime_error( "statement_" );      \
  }                                           \

int main()
{
  try
  {
    some_func( 5 < 6 );
  }
  catch(std::exception& e)
  {
    cerr << e.what();
  }
}

Body:
Oh, I found this.

and here's the final working code =):

#include <stdexcept>
#include <iostream>

#define some_func( statement_ )              \
  if( ! statement_ )                         \
  {                                          \
    throw std::runtime_error( #statement_ ); \
/* Note: #, no quotes!       ^^^^^^^^^^  */  \
  }                                          \

int main(int argc, char** argv)
{
  try
  {
    some_func( 5 < 6 );
  }
  catch(std::exception& e)
  {
    std::cerr << e.what();
  }
}


问:
Failed to execute goal org.apache.felix:maven-scr-plugin:1.20.0
I am working on an AEM project and facing the below error while building my maven project.

```<code>Failed to execute goal org.apache.felix:maven-scr-plugin:1.20.0:scr (generate-scr-scrdescriptor) on project acs.core: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: **Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)** -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.felix:maven-scr-plugin:1.20.0:scr (generate-scr-scrdescriptor) on project acs.core: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    ... 20 more
Caused by: com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory.getDefaultMethodProperties(OutputPropertiesFactory.java:345)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.setDefaults(TransformerImpl.java:1168)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.createOutputProperties(TransformerImpl.java:1129)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.<init>(TransformerImpl.java:270)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.<init>(TransformerImpl.java:261)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:764)
    at org.apache.felix.scrplugin.xml.IOUtils.parse(IOUtils.java:59)
    at org.apache.felix.scrplugin.xml.ComponentDescriptorIO.read(ComponentDescriptorIO.java:167)
    at org.apache.felix.scrplugin.helper.ClassScanner.readServiceComponentDescriptor(ClassScanner.java:527)
    at org.apache.felix.scrplugin.helper.ClassScanner.readServiceComponentDescriptor(ClassScanner.java:558)
    at org.apache.felix.scrplugin.helper.ClassScanner.getComponentDescriptors(ClassScanner.java:497)
    at org.apache.felix.scrplugin.helper.ClassScanner.getDescription(ClassScanner.java:433)
    at org.apache.felix.scrplugin.SCRDescriptorGenerator.createComponent(SCRDescriptorGenerator.java:397)
    at org.apache.felix.scrplugin.SCRDescriptorGenerator.execute(SCRDescriptorGenerator.java:161)
    at org.apache.felix.scrplugin.mojo.SCRDescriptorMojo.execute(SCRDescriptorMojo.java:237)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    ... 21 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :acs.core
</code>```

Not sure from where it's referencing the "output_xml.properties" file.

答:
org.apache.felix:maven-scr-plugin plugin,  use this plugin, it has to be declared in the project descriptor as a  element:

```<code><project>
...
<build>
...
<plugins>
  ...
  <plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-scr-plugin</artifactId>
    <version>1.20.0</version>
    <executions>
      <execution>
        <id>generate-scr-scrdescriptor</id>
        <goals>
          <goal>scr</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
  ...
</plugins>
...
</build>
...
</project>
</code>```

If you want to process the standard annotations with the maven-scr-plugin add this dependency:

```<code><project>
...
<dependencies>
...
<dependency>
     <groupId>org.apache.felix</groupId>
     <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
     <version>1.2.4</version>
     <scope>provided</scope>
</dependency>
...
</dependencies>
...
</project>
</code>```

Body:
I am working on an AEM project and facing the below error while building my maven project.

Failed to execute goal org.apache.felix:maven-scr-plugin:1.20.0:scr (generate-scr-scrdescriptor) on project acs.core: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: **Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)** -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.felix:maven-scr-plugin:1.20.0:scr (generate-scr-scrdescriptor) on project acs.core: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution generate-scr-scrdescriptor of goal org.apache.felix:maven-scr-plugin:1.20.0:scr failed: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    ... 20 more
Caused by: com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException: Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)
    at com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory.getDefaultMethodProperties(OutputPropertiesFactory.java:345)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.setDefaults(TransformerImpl.java:1168)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.createOutputProperties(TransformerImpl.java:1129)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.<init>(TransformerImpl.java:270)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.<init>(TransformerImpl.java:261)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:764)
    at org.apache.felix.scrplugin.xml.IOUtils.parse(IOUtils.java:59)
    at org.apache.felix.scrplugin.xml.ComponentDescriptorIO.read(ComponentDescriptorIO.java:167)
    at org.apache.felix.scrplugin.helper.ClassScanner.readServiceComponentDescriptor(ClassScanner.java:527)
    at org.apache.felix.scrplugin.helper.ClassScanner.readServiceComponentDescriptor(ClassScanner.java:558)
    at org.apache.felix.scrplugin.helper.ClassScanner.getComponentDescriptors(ClassScanner.java:497)
    at org.apache.felix.scrplugin.helper.ClassScanner.getDescription(ClassScanner.java:433)
    at org.apache.felix.scrplugin.SCRDescriptorGenerator.createComponent(SCRDescriptorGenerator.java:397)
    at org.apache.felix.scrplugin.SCRDescriptorGenerator.execute(SCRDescriptorGenerator.java:161)
    at org.apache.felix.scrplugin.mojo.SCRDescriptorMojo.execute(SCRDescriptorMojo.java:237)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    ... 21 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :acs.core

Not sure from where it's referencing the "output_xml.properties" file.

Body:
org.apache.felix:maven-scr-plugin plugin,  use this plugin, it has to be declared in the project descriptor as a  element:

<project>
...
<build>
...
<plugins>
  ...
  <plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-scr-plugin</artifactId>
    <version>1.20.0</version>
    <executions>
      <execution>
        <id>generate-scr-scrdescriptor</id>
        <goals>
          <goal>scr</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
  ...
</plugins>
...
</build>
...
</project>

If you want to process the standard annotations with the maven-scr-plugin add this dependency:

<project>
...
<dependencies>
...
<dependency>
     <groupId>org.apache.felix</groupId>
     <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
     <version>1.2.4</version>
     <scope>provided</scope>
</dependency>
...
</dependencies>
...
</project>


问:
Apache log4j asynchronous Loggers for Low-Latency Logging
If application server crashes and huge log is pending to be persisted into the log file, how log4j Asynchronous Logger handle to avoid missing any log? Or is there any mechanism to retrieve the log?</p>

答: In graceful shutdown no log is lost, whereas, in crash or killing process, may lose the log and I could not find any approach to return the lost logs. </p>


问:
transformClassesAndResourcesWithProguardForRelease FAILED
I am trying to Build my Android application with Gradle in console.
But getting below error about task ':app:transformClassesAndResourcesWithProguardForRelease':

build.gradle:

```<code>buildscript {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app/build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion '24.0.2'
    defaultConfig {
        applicationId "com.XXX.XXX"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "0.1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile('com.squareup.retrofit2:retrofit:2.1.0') {
        exclude module: 'okhttp'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.retrofit2:converter-moshi:2.1.0'
    compile 'moe.banana:moshi-jsonapi:2.2.0'
    compile 'com.squareup.moshi:moshi-adapters:1.3.1'
    compile 'com.google.android.gms:play-services-maps:9.6.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.firebase:firebase-core:9.6.0'
    compile 'com.google.firebase:firebase-crash:9.6.0'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

gradle-wrapper.properties

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
</code>```

./gradlew build --stacktrace

This is the exception I am receiving:

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task
':app:transformClassesAndResourcesWithProguardForRelease'.
</code>```

答:
It worked for me I also had to add following in a pro-gaurd.txt file</p>

```<code>#### -- Picasso --
 -dontwarn com.squareup.picasso.**

 #### -- OkHttp --

 -dontwarn com.squareup.okhttp.internal.**

 #### -- Apache Commons --

 -dontwarn org.apache.commons.logging.**

     -ignorewarnings
-keep class * {
public private protected *;
}
</code>```

Body:
I am trying to Build my Android application with Gradle in console.
But getting below error about task ':app:transformClassesAndResourcesWithProguardForRelease':

build.gradle:

buildscript {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion '24.0.2'
    defaultConfig {
        applicationId "com.XXX.XXX"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "0.1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile('com.squareup.retrofit2:retrofit:2.1.0') {
        exclude module: 'okhttp'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.retrofit2:converter-moshi:2.1.0'
    compile 'moe.banana:moshi-jsonapi:2.2.0'
    compile 'com.squareup.moshi:moshi-adapters:1.3.1'
    compile 'com.google.android.gms:play-services-maps:9.6.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.firebase:firebase-core:9.6.0'
    compile 'com.google.firebase:firebase-crash:9.6.0'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

./gradlew build --stacktrace

This is the exception I am receiving:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task
':app:transformClassesAndResourcesWithProguardForRelease'.

Body:
It worked for me I also had to add following in a pro-gaurd.txt file

#### -- Picasso --
 -dontwarn com.squareup.picasso.**

 #### -- OkHttp --

 -dontwarn com.squareup.okhttp.internal.**

 #### -- Apache Commons --

 -dontwarn org.apache.commons.logging.**

     -ignorewarnings
-keep class * {
public private protected *;
}

ContentLicense: CC BY-SA 4.0


答:
You need to use the stringize operator:

```<code>throw runtime_error(# statement_);
</code>```

If statement_ may be a macro, you'll want to use the double stringize trick.

Title: How to print the #define statement?

Body:
You need to use the stringize operator:

throw runtime_error(# statement_);

If statement_ may be a macro, you'll want to use the double stringize trick.


问:
Is it possible to set the max-length of a data member in WCF
Is it possible to set a requirement in WCF that a specific string datamember have a maximum length?

I'm essentially wanting to do some basic validation, and enhancing the implicit documentation that WSDL gives you.

I'm pretty sure that its possible when writing raw WSDL, but am not sure if you can do it in WCF using attributes etc.

And related, require that an array property have at least one element in it...

答:
I guess this post is old but it now exists just add the Maxlength attribute</p>

```<code>[MaxLength(MaxLength = 100)]
public string Name{ get; set; }
</code>```

Body:
I guess this post is old but it now exists just add the Maxlength attribute

[MaxLength(MaxLength = 100)]
public string Name{ get; set; }


问:
How to get available routes from the mux in go?
I have a mux and 4 different routes.

```<code>a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")
</code>```

Is there a method where we can list the defined routes and get the  methods defined on them. I was trying this way: routes := a.getRoutes() will return me a slice with all the routes, and methods := routes[1].Methods() will return the methods listed on that route. Is there a way we can achieve this?

答:
Use the Walk method:

```<code>router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    tpl, err1 := route.GetPathTemplate()
    met, err2 := route.GetMethods()
    fmt.Println(tpl, err1, met, err2)
    return nil
})
</code>```

Alternatively, you can just put all your routes into a slice of structs and just do

```<code>for _, r := range routes {
    router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
}
</code>```

on the initialisation step.

Body:
I have a mux and 4 different routes.

a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")

Is there a method where we can list the defined routes and get the  methods defined on them. I was trying this way: routes := a.getRoutes() will return me a slice with all the routes, and methods := routes[1].Methods() will return the methods listed on that route. Is there a way we can achieve this?

Body:
Use the Walk method:

router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    tpl, err1 := route.GetPathTemplate()
    met, err2 := route.GetMethods()
    fmt.Println(tpl, err1, met, err2)
    return nil
})

Alternatively, you can just put all your routes into a slice of structs and just do

for _, r := range routes {
    router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
}

on the initialisation step.


问:
Odoo installation ''error: [Errno 98] Address already in use''
I followed this installation guide for odoo and I get an error in the very end
when I run odoo-bin file it gives me this error

```<code>teo@teo-Lenovo-Yoga-3-14:/opt/odoo/odoo-10.0$ ./odoo-bin
2017-07-06 15:03:20,583 3754 INFO ? odoo: Odoo version 10.0
2017-07-06 15:03:20,583 3754 INFO ? odoo: addons paths: ['/home/teo/.local/share/Odoo/addons/10.0', u'/opt/odoo/odoo-10.0/odoo/addons', u'/opt/odoo/odoo-10.0/addons']
2017-07-06 15:03:20,583 3754 INFO ? odoo: database: default@default:default
2017-07-06 15:03:20,601 3754 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069
Exception in thread odoo.service.httpd:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 251, in http_thread
    self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 106, in __init__
    handler=RequestHandler)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 440, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 116, in server_bind
    super(ThreadedWSGIServerReloadable, self).server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use
</code>```

I think it may be related to the odoo.conf file because I specify a port but it still assumes de default port 8069

this is my odoo.conf file

```<code>[options]

; This is the password that allows database operations:

; admin_passwd = PASSWORD

db_host = False

db_port = 8470

db_user = odoo

db_password = False

addons_path = /opt/odoo/odoo-10.0/addons

;Log Settings

logfile = /var/log/odoo/odoo.log

log_level = error
</code>```

Does anyone have an idea of what's happening, for the record I tried to install odoo before but failed so I already had DB user created for e.g.

答: Your odoo config has another DB port set, but 8069 is the port used for xmlrpc requests. If you want to change that in config, you have to set xmlrpc_port = 8470.

Body:
I followed this installation guide for odoo and I get an error in the very end
when I run odoo-bin file it gives me this error

teo@teo-Lenovo-Yoga-3-14:/opt/odoo/odoo-10.0$ ./odoo-bin
2017-07-06 15:03:20,583 3754 INFO ? odoo: Odoo version 10.0
2017-07-06 15:03:20,583 3754 INFO ? odoo: addons paths: ['/home/teo/.local/share/Odoo/addons/10.0', u'/opt/odoo/odoo-10.0/odoo/addons', u'/opt/odoo/odoo-10.0/addons']
2017-07-06 15:03:20,583 3754 INFO ? odoo: database: default@default:default
2017-07-06 15:03:20,601 3754 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069
Exception in thread odoo.service.httpd:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 251, in http_thread
    self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 106, in __init__
    handler=RequestHandler)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 440, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 116, in server_bind
    super(ThreadedWSGIServerReloadable, self).server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use

I think it may be related to the odoo.conf file because I specify a port but it still assumes de default port 8069

this is my odoo.conf file

[options]

; This is the password that allows database operations:

; admin_passwd = PASSWORD

db_host = False

db_port = 8470

db_user = odoo

db_password = False

addons_path = /opt/odoo/odoo-10.0/addons

;Log Settings

logfile = /var/log/odoo/odoo.log

log_level = error

Does anyone have an idea of what's happening, for the record I tried to install odoo before but failed so I already had DB user created for e.g.


问:
Maven Error : Maven Project Configuration for Module isn't available
I keep getting this error when I try to compile my code. I have the pom.xml file in my directories but I am not sure if there is something wrong in there. I found only one link on the internet regarding this and that was not my case: Maven project configuration required for module

Error:Maven Resources Compiler: Maven project configuration required for module 'updater' isn't available. Compilation of Maven projects is supported only if external build is started from an IDE.

Here is the content of my pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nothing.updater</groupId>
    <artifactId>Updater</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--<dependencies>-->
        <!--<dependency>-->
            <!--<groupId>com.nothing.toolbox</groupId>-->
            <!--<artifactId>Toolbox</artifactId>-->
            <!--<version>1.1</version>-->
        <!--</dependency>-->

    <!--</dependencies>-->
</project>
</code>```

I am using a multi-module project.

答:
I had this problem after an Intellij Idea version upgrade.  The fix was to wait for it to finish indexing.  Then I think it downloaded some stuff it needed.

Makes me think that the other answers on this thread about the IJ version upgrade probably just needed to wait as well - by the time they finished trying a few things the problem was fixed by itself.

Body:
I keep getting this error when I try to compile my code. I have the pom.xml file in my directories but I am not sure if there is something wrong in there. I found only one link on the internet regarding this and that was not my case: Maven project configuration required for module

Error:Maven Resources Compiler: Maven project configuration required for module 'updater' isn't available. Compilation of Maven projects is supported only if external build is started from an IDE.

Here is the content of my pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nothing.updater</groupId>
    <artifactId>Updater</artifactId>
    <version>1.0-SNAPSHOT</version>

</project>

I am using a multi-module project.


问:
How to get the ID of an inserted or updated record in Sequelize upsert?
i need to get the id for the inserted/updated record when using .upsert() in sequelize.

right now .upsert() returns a boolean indicating whether the row was created or updated.

```<code>return db.VenueAddress.upsert({
            addressId:address.addressId,
            venueId: venue.venueId,
            street: address.street,
            zipCode: address.zipCode,
            venueAddressDeletedAt: null
        }).then(function(test){
            //test returned here as true or false how can i get the inserted id here so i can insert data in other tables using this new id?
        });
</code>```

答:
i know this is an old post, but in case this helps anyone</p>

```<code>const upsert = async (model: any, values: any, condition: any): Promise<any> => {
  const obj = await model.findOne({ where: condition })
  if (obj) {
    // only do update is value is different from queried object from db
    for (var key in values) {
      const val = values[key]
      if (parseFloat(obj[key]) !== val) {
        obj.isUpdatedRecord = true
        return obj.update(values)
      }
    }
    obj.isUpdatedRecord = false
    return obj

  } else {
    // insert
    const merged = { ...values, ...condition }
    return model.create(merged)
  }
}
</code>```

Body:
i need to get the id for the inserted/updated record when using .upsert() in sequelize.

right now .upsert() returns a boolean indicating whether the row was created or updated.

return db.VenueAddress.upsert({
            addressId:address.addressId,
            venueId: venue.venueId,
            street: address.street,
            zipCode: address.zipCode,
            venueAddressDeletedAt: null
        }).then(function(test){
            //test returned here as true or false how can i get the inserted id here so i can insert data in other tables using this new id?
        });

Body:
i know this is an old post, but in case this helps anyone

const upsert = async (model: any, values: any, condition: any): Promise<any> => {
  const obj = await model.findOne({ where: condition })
  if (obj) {
    // only do update is value is different from queried object from db
    for (var key in values) {
      const val = values[key]
      if (parseFloat(obj[key]) !== val) {
        obj.isUpdatedRecord = true
        return obj.update(values)
      }
    }
    obj.isUpdatedRecord = false
    return obj

  } else {
    // insert
    const merged = { ...values, ...condition }
    return model.create(merged)
  }
}


问:
Foward declaration of classes in Python
The following program can run successfully:

```<code>class Simple(object):
    def __init__(self, name):
      self.name = name

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]
</code>```

I would like to keep the definition of Simple, Composite, and __main__ in three different files, but I cannot do it because I cannot import Simple into composite.py and I cannot import Composite into simple.py.

How would you modify the class definition such that you can keep separate files?

Thank you.

PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.

答:
The problem is that you get circular imports, right?

import Simple in the __add__ method instead of at the top of the file to avoid circular dependency. It will slow down the __add__ method somewhat, but usually not significantly.

Title: Foward declaration of classes in Python

Body:
The following program can run successfully:

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

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]

I would like to keep the definition of Simple, Composite, and __main__ in three different files, but I cannot do it because I cannot import Simple into composite.py and I cannot import Composite into simple.py.

How would you modify the class definition such that you can keep separate files?

Thank you.

PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.


问:
Using xpath expression in grails on node objects
I wonder if it is possible to use xpath liky syntax on node objects in grails.

```<code><root>
   <enrichedData datatable="ROUTING">
        <customer>234</customer>
   </enrichedData>
   <enrichedData datatable="TABLE2">
        <location>aaa</location>
    </enrichedData>
</root>
</code>```

With this xml structure, it is simple to use this xpath expression:

```<code>/data/enrichedData[@datatable='ROUTING']/customer
</code>```

When I access this with nodes, I use this code

```<code>root.data.enrichedData.each {
   if(it.attributes().get("datatable"=="ROUTING")) {
     //do some stuff here
   }
</code>```

Is there another way to access a node with a specific attribute in grails?

答:
.find and .findAll work.  I added another ROUTING node to your example for clarity:

```<code><root>
  <enrichedData datatable="ROUTING">
    <customer>234</customer>
  </enrichedData>
  <enrichedData datatable="TABLE2">
    <location>aaa</location>
  </enrichedData>
  <enrichedData datatable="ROUTING">
    <customer>567</customer>
  </enrichedData>
</root>
</code>```

But this is of course not necessary.

I can then find ROUTING nodes, and operate on their customers, as such:

data.enrichedData.findAll{it.@datatable == "ROUTING"}.customer.each { println it.text() }

It's possible to add additional .finds farther down the chain, but that should give you the general idea.

Body:
I wonder if it is possible to use xpath liky syntax on node objects in grails.

<root>
   <enrichedData datatable="ROUTING">
        <customer>234</customer>
   </enrichedData>
   <enrichedData datatable="TABLE2">
        <location>aaa</location>
    </enrichedData>
</root>

With this xml structure, it is simple to use this xpath expression:

/data/enrichedData[@datatable='ROUTING']/customer

When I access this with nodes, I use this code

root.data.enrichedData.each {
   if(it.attributes().get("datatable"=="ROUTING")) {
     //do some stuff here
   }

Is there another way to access a node with a specific attribute in grails?

Body:
.find and .findAll work.  I added another ROUTING node to your example for clarity:

<root>
  <enrichedData datatable="ROUTING">
    <customer>234</customer>
  </enrichedData>
  <enrichedData datatable="TABLE2">
    <location>aaa</location>
  </enrichedData>
  <enrichedData datatable="ROUTING">
    <customer>567</customer>
  </enrichedData>
</root>

But this is of course not necessary.

I can then find ROUTING nodes, and operate on their customers, as such:

data.enrichedData.findAll{it.@datatable == "ROUTING"}.customer.each { println it.text() }

It's possible to add additional .finds farther down the chain, but that should give you the general idea.


问:
Populating a list of lists with random items
I have a list of lists with a certain range:

```<code>l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]
</code>```

And a list of words:

```<code>words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]
</code>```

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

```<code>for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice
</code>```

Any ideas? Thank you in advance!

答:
You're not storing the values back into your lists. Try:</p>

```<code>for i in range(0, len(list)):
    subl = list[i]
    for n in range(0, len(subl)):
        list[i][n] = random.choice(words)
</code>```

Body:
I have a list of lists with a certain range:

l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]

And a list of words:

words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice

Any ideas? Thank you in advance!

Body:
You're not storing the values back into your lists. Try:

for i in range(0, len(list)):
    subl = list[i]
    for n in range(0, len(subl)):
        list[i][n] = random.choice(words)


问:
How to write a file to an Azure website folder from a webjob or worker role
I need to write an XML file to an Azure website folder under site root, with data pulled from the website's Azure SQL DB. This will be done on a recurring basis.

I have written a worker role which pulls the data and writes the file, however, it writes to a folder within the worker role folder structure using the below code. I am not sure how to specify and access the web folder path.

XmlTextWriter xml = new XmlTextWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "feed.xml"), Encoding.UTF8);

Both the worker role and the website are in the same VS project, and deployed to Azure.

Since both the website and the worker role are in their respective VM instances, maybe the WR cannot access the website - I am not completely sure, and would really appreciate any guidance.

Would a webjob be better suited for this? Can it connect to an Azure DB, and write to a folder within the site root? Appreciate any code examples.

答:
You wouldn't want to write a any single location as the server running your website is rather ethereal and can be taken offline and replaced at any time.

You should consider having your job generate the file and write it to Blob Storage and having your website read and serve the same file. Set up your site to treat the path to the file as a regular non-static route (this will let you keep the path /feeds/feed.xml) and the Action can read the XML file from your blob storage and serve it as the response.


问:
Two table filter
I try to filter the Author with the class Book that has the specific category, but I can't get the exact category.

models.py

```<code>class Book(models.Model):
    category = models.CharField()
    foreignkey = models.ForeignKey(Author, related_name="auth")
class Author(models.Model):
    author_id = models.IntegerField(primary_key=True)
</code>```

views.py

```<code>book = models.Book.objects.filter(category = 'Space')
author = models.Author.objects.filter(author_id__in = book )
</code>```

答:
```<code>class Book(models.Model):
    category = models.CharField()
    author = models.ForeignKey(Author, related_name='books')

class Author(models.Model):
    name = models.CharField()

books = Book.objects.values('author_id',flat=True).filter(category='Space')
authors = Author.objects.filter(pk__in=books)
</code>```

Title: Two table filter

Body:
I try to filter the Author with the class Book that has the specific category, but I can't get the exact category.

models.py

class Book(models.Model):
    category = models.CharField()
    foreignkey = models.ForeignKey(Author, related_name="auth")
class Author(models.Model):
    author_id = models.IntegerField(primary_key=True)

views.py

book = models.Book.objects.filter(category = 'Space')
author = models.Author.objects.filter(author_id__in = book )


问:
Algorithm to time-sort N data streams
So I've got N asynchronous, timestamped data streams. Each stream has a fixed-ish rate. I want to process all of the data, but the catch is that I must process the data in order as close to the time that the data arrived as possible (it is a real-time streaming application).

So far, my implementation has been to create a fixed window of K messages which I sort by timestamp using a priority queue. I then process the entirety of this queue in order before moving on to the next window. This is okay, but its less than ideal because it creates lag proportional to the size of the buffer, and also will sometimes lead to dropped messages if a message arrives just after the end of the buffer has been processed. It looks something like this:

```<code>// Priority queue keeping track of the data in timestamp order.
ThreadSafeProrityQueue<Data> q;
// Fixed buffer size
int K = 10;
// The last successfully processed data timestamp
time_t lastTimestamp = -1;

// Called for each of the N data streams asyncronously
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
   if (q.size() > K) {
       processQueue();
   }
}

// Process all the data in the queue.
void processQueue() {
    while (!q.empty()) {
        const auto& data = q.top();
        // If the data is too old, drop it.
        if (data.timestamp < lastTimestamp) {
            LOG("Dropping message. Too old.");
            q.pop();
            continue;
        }
        // Otherwise, process it.
        processData(data);
        lastTimestamp = data.timestamp;
        q.pop();
    }
}
</code>```

Information about the data: they're guaranteed to be sorted within their own stream. Their rates are between 5 and 30 hz. They consist of images and other bits of data.

Some examples of why this is harder than it appears. Suppose I have two streams, A and B both running at 1 Hz and I get the data in the following order:

```<code>(stream, time)
(A, 2)
(B, 1.5)
(A, 3)
(B, 2.5)
(A, 4)
(B, 3.5)
(A, 5)
</code>```

See how if I processed the data in order of when I received them, B would always get dropped? that's what I wanted to avoid.Now in my algorithm, B would get dropped every 10th frame, and I would process the data with a lag of 10 frames into the past.

答:
There's always be a lag and that lag will be determined by how long you'll be willing to wait for your slowest "fixed-ish rate" stream.

Suggestion:

keep the buffer

keep an array of bool flags with the meaning:"if position ix is true, in the buffer there is at least a sample originated from stream ix"

sort/process as soon as you have all flag to true

Not full-proof (each buffer will be sorted, but from one buffer to another you may have timestamp inversion), but perhaps good enough?

Playing around with the count of "satisfied" flags to trigger the processing (at step 3) may be used to make the lag smaller, but with the risk of more inter-buffer timestamp inversions. In extreme, accepting the processing with only one satisfied flag means "push a frame as soon as you receive it, timestamp sorting be damned".

I mentioned this to support my feeling that lag/timestamp inversions balance is inherent to your problem - except for absolutely equal framerates, there will be perfect solution in which one of the sides is not sacrificed.

Since a "solution" will be an act of balancing, any solution will require gathering/using extra information to help decisions (e.g. that "array of flags"). If what I suggested sounds silly for your case (may well be, the details you chose to share aren't too many), start thinking what metrics will be relevant for your targeted level of "quality of experience" and use additional data structures to help gathering/processing/using those metrics.

Title: Algorithm to time-sort N data streams

Body:
So I've got N asynchronous, timestamped data streams. Each stream has a fixed-ish rate. I want to process all of the data, but the catch is that I must process the data in order as close to the time that the data arrived as possible (it is a real-time streaming application).

So far, my implementation has been to create a fixed window of K messages which I sort by timestamp using a priority queue. I then process the entirety of this queue in order before moving on to the next window. This is okay, but its less than ideal because it creates lag proportional to the size of the buffer, and also will sometimes lead to dropped messages if a message arrives just after the end of the buffer has been processed. It looks something like this:

// Priority queue keeping track of the data in timestamp order.
ThreadSafeProrityQueue<Data> q;
// Fixed buffer size
int K = 10;
// The last successfully processed data timestamp
time_t lastTimestamp = -1;

// Called for each of the N data streams asyncronously
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
   if (q.size() > K) {
       processQueue();
   }
}

// Process all the data in the queue.
void processQueue() {
    while (!q.empty()) {
        const auto& data = q.top();
        // If the data is too old, drop it.
        if (data.timestamp < lastTimestamp) {
            LOG("Dropping message. Too old.");
            q.pop();
            continue;
        }
        // Otherwise, process it.
        processData(data);
        lastTimestamp = data.timestamp;
        q.pop();
    }
}

Information about the data: they're guaranteed to be sorted within their own stream. Their rates are between 5 and 30 hz. They consist of images and other bits of data.

Some examples of why this is harder than it appears. Suppose I have two streams, A and B both running at 1 Hz and I get the data in the following order:

(stream, time)
(A, 2)
(B, 1.5)
(A, 3)
(B, 2.5)
(A, 4)
(B, 3.5)
(A, 5)

See how if I processed the data in order of when I received them, B would always get dropped? that's what I wanted to avoid.Now in my algorithm, B would get dropped every 10th frame, and I would process the data with a lag of 10 frames into the past.


问:
Android samasung galaxy tab emulator resolut?
I have updated my  android sdk  with samsung galax tab addon , it installed successfully . problem is that when i open galaxy tab emulator, it displayed portion of emulator ,i.e; bottom of emulator is not visible. i thnk it is problem with desktop resolution , but resolution of desktop is 1280 X 1024 .  Can any one tell me how to get the display of galaxy tab emulator </p>

答:
Those of you having trouble launching from Eclipse and not being able scale the display, use the following command line option (set via Run | Run Configurations): </p>

```<code>-scale 0.57
</code>```

Body:
Those of you having trouble launching from Eclipse and not being able scale the display, use the following command line option (set via Run | Run Configurations):

-scale 0.57


问:
Parse JSON with Swift 3 XCode 8
I have an app that allows you to enter in data and it posts it to a server running mysql I created. I then wrote the PHP file to translate mysql to JSON so that my app could list the contents in a table. However it is not working, I get errors saying "Invalid value around character 0" or "JSON text did not start with array or object". All I want to do is get the data and convert it to an index so that I can display certain data throughout my app.

php code:

```<code>//including the file dboperation
require_once '../includes/DbOperation2.php';

//creating a response array to store data
$response = array();

//creating a key in the response array to insert values
//this key will store an array iteself
$response['profile'] = array();

//creating object of class DbOperation
$db = new DbOperation();

//getting the teams using the function we created
$profile = $db->getAllUsers();

//looping through all the teams.
//creating a temporary array
$temp = array();

//inserting the team in the temporary array
$temp['id'] = $profiles['id'];
$temp['displayName']=$profiles['displayName'];
$temp['department']=$profiles['department'];
$temp['mamager']=$profiles['mamager'];
$temp['office']=$profiles['office'];
$temp['util']=$profiles['util'];

//inserting the temporary array inside response
array_push($response['profile'],$temp);
}

//displaying the array in json format
echo json_encode($response);
</code>```

Output looks like this:

```<code>{"profile":[{"id":1,"displayName":"Jacob Blacksten","department":"DF","mamager":"San","office":"NYC","util":2},{"id":2,"displayName":"John Smith","department":"SS","mamager":"Jack","office":"Boston","util":3}]}
</code>```

xcode:

```<code>   guard let url = URL(string: "http://ipAddress/MyWebService/api/getteams.php") else { return}

    let session = URLSession.shared
    session.dataTask(with: url) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch{
                print(error)
            }
        }
    }.resume()
}
</code>```

Please some one help me with the xcode. I need to first get it to parse and once parsed I would like to put them in an array and index them. I know this might be a duplicate question but I have spent days looking for this answer and I don't know coding enough to understand everything.

答:
There are many ways you can parse this. This is how I would do it.

First, create an NSObject class of the keys you will be parsing.

```<code>class DataObject: NSObject { var Name: String? var ID: String?

}
</code>```

In your ViewController class (Or wherever you have your method to retrieve data), create a global variable of type DataObject

```<code>var dataObject = [DataObject]()

func retrieveData(dataToParse: [String : Any]) {

//dataToParse will be your json variable and cast it as a dictionary of [String : Any]

let object = DataObject()
object.setValuesForKey(dataToParse)
dataObject.append(object)

}
</code>```

Now you can access your data just like an array, kinda.

```<code>let name = dataObject[0].Name
</code>```

Title: Parse JSON with Swift 3 XCode 8

Body:
I have an app that allows you to enter in data and it posts it to a server running mysql I created. I then wrote the PHP file to translate mysql to JSON so that my app could list the contents in a table. However it is not working, I get errors saying "Invalid value around character 0" or "JSON text did not start with array or object". All I want to do is get the data and convert it to an index so that I can display certain data throughout my app.

php code:

//including the file dboperation
require_once '../includes/DbOperation2.php';

//creating a response array to store data
$response = array();

//creating a key in the response array to insert values
//this key will store an array iteself
$response['profile'] = array();

//creating object of class DbOperation
$db = new DbOperation();

//getting the teams using the function we created
$profile = $db->getAllUsers();

//looping through all the teams.
//creating a temporary array
$temp = array();

//inserting the team in the temporary array
$temp['id'] = $profiles['id'];
$temp['displayName']=$profiles['displayName'];
$temp['department']=$profiles['department'];
$temp['mamager']=$profiles['mamager'];
$temp['office']=$profiles['office'];
$temp['util']=$profiles['util'];

//inserting the temporary array inside response
array_push($response['profile'],$temp);
}

//displaying the array in json format
echo json_encode($response);

Output looks like this:

{"profile":[{"id":1,"displayName":"Jacob Blacksten","department":"DF","mamager":"San","office":"NYC","util":2},{"id":2,"displayName":"John Smith","department":"SS","mamager":"Jack","office":"Boston","util":3}]}

xcode:

   guard let url = URL(string: "http://ipAddress/MyWebService/api/getteams.php") else { return}

    let session = URLSession.shared
    session.dataTask(with: url) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch{
                print(error)
            }
        }
    }.resume()
}

Please some one help me with the xcode. I need to first get it to parse and once parsed I would like to put them in an array and index them. I know this might be a duplicate question but I have spent days looking for this answer and I don't know coding enough to understand everything.

Body:
There are many ways you can parse this. This is how I would do it.

First, create an NSObject class of the keys you will be parsing.

class DataObject: NSObject { var Name: String? var ID: String?

}

In your ViewController class (Or wherever you have your method to retrieve data), create a global variable of type DataObject

var dataObject = [DataObject]()

func retrieveData(dataToParse: [String : Any]) {

//dataToParse will be your json variable and cast it as a dictionary of [String : Any]

let object = DataObject()
object.setValuesForKey(dataToParse)
dataObject.append(object)

}

Now you can access your data just like an array, kinda.

let name = dataObject[0].Name


问:
Why does my PHP PDO Select in while not working with page limit? Also issue with Array in select
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates</p>

```<code>for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}
</code>```

答:
Don't base your loop condition on the result of fetch(). Get the result and evaluate it separately.

From the docs: "The return value of this function on success depends on the fetch type." IE Not necc a great thing for a boolean evaluation. It will return false if it fails but when it succeeds it may behave in an unexpected manner.

Better - use fetchAll() and loop through the resultant array.

Last - check your result set using print_r(). Make sure you have something to loop through.

Body:
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates

for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '
zipcode: ' . $zipcodeA[$x] . '
';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}


问:
bash - find all .bashrc files and append to them
I need to find all .bashrc files and append "MYSQL_HISTFILE=/dev/null" to it, to remediate an issue. There are alot of .bashrc files, so can I do something like:</p>

```<code>find / -type f -name ".bashrc" -exec echo "export MYSQL_HISTFILE=/dev/null" >> {} \;
</code>```

答:
>> is executed by the original shell process, it can't use substitution from find. And find doesn't run its command through a shell, so it can't do output redirection itself.

You need to execute bash explicitly so you can use redirection in the command.

```<code>find / -type f -name '.bashrc' -exec bash -c 'echo export MYSQL_HISTFILE=/dev/null >> "{}"' \;
</code>```

Body:
I need to find all .bashrc files and append "MYSQL_HISTFILE=/dev/null" to it, to remediate an issue. There are alot of .bashrc files, so can I do something like:

find / -type f -name ".bashrc" -exec echo "export MYSQL_HISTFILE=/dev/null" >> {} \;

Body:
>> is executed by the original shell process, it can't use substitution from find. And find doesn't run its command through a shell, so it can't do output redirection itself.

You need to execute bash explicitly so you can use redirection in the command.

find / -type f -name '.bashrc' -exec bash -c 'echo export MYSQL_HISTFILE=/dev/null >> "{}"' \;


问:
Find value within a range in R
My data look like below. I want to select value greater/equal to 35 and less than/equal to 350. I also want to replace those values with withinrange

```<code>value
1
35
36
37
350
355
3555
35555
</code>```

答:
To select the values: value[value >= 35 & value <=350]

To replace them with withinrange: value[value >= 35 & value <=350] <- withinrange

Title: Find value within a range in R

Body:
My data look like below. I want to select value greater/equal to 35 and less than/equal to 350. I also want to replace those values with withinrange

value
1
35
36
37
350
355
3555
35555


问:
Junit instance creation each by method or class
Recently, I'm reading the book Growing Object-Oriented Software, Guided by Tests and I'm confused about the description they say of Junit behaviour.

If I understand what the authors say, Junit creates a new instance of a test class and in each test method to ensure they are isolated from each other.

To run a test, JUnit creates a new instance of the test class and
  calls the relevant test method. Creating a new test object each time
  ensures that the tests are isolated from each other, because the test
  object’s fields are replaced before each test. This means that a test
  is free to change the contents of any of the test object fields.

Then they say that in NUnit (.Net) is different, because it reuses the same test object for all test methods, so you need to reset the objects using Setups and TearDowns.

NUnit Behaves Differently from JUnit Those working in .Net should note
  that NUnit reuses the same instance of the test object for all the
  test methods, so any values that might change must either be reset in
  [Setup] and [TearDown] methods (if they’re fields) or made local to
  the test method.

I though JUnit behaves just as they describe the NUnit behaviour, so your class instances are reusable in the same class and you use Setups and TearDown to reset them.

So, how JUnit behaves, it instantiates the test class in each method or otherwise it instantitates the test class once.

Maybe I don't understand what the authors mean. What they mean?

答:
JUnit instantiates the test class for each test (aka method annotated with @Test).

The setup and teardown methods are there only to help you writing clear and easy to read test - by extracting common setup of test environment, preconditions and verifications so it doesn't mess up the test itself.

The environment setup is static and can be shared accros all tests in the class - it's ok to create it only once - the @BeforeClass and @AfterClass annotations (note that the methods must be static)

The environment setup is specific for each test and can't be shared accros all tests in the class - the @Before and @After annotations


问:
Open URL Schemes in IOS
I have 2 apps, which are meant for different purpose, where I should not allow user to use both apps in same device. How can I check whether other app installed or not?
I think I can do it using Open URL as following by putting app bundle id which is not working, I am stuck to get url for my app
EX : "fb://"</p>

```<code>       if ([[UIApplication sharedApplication] canOpenURL:@"My App URL"]) {
            //App installed
        }
        else{
            //App Not installed
        }
</code>```

答:
Swift 3.0 working Answer :

Everything remains same as Selected answer  ( above answer which is answered by user3182143 as this causes few issue by other user so i answered this way , only code implementation is different rest follow same step as answered by above correct answer )

But code implementation is different now :

```<code>let kCustomURLScheme = "yourappscheme://"

 func openCustomApp() {
    if (UIApplication.shared.canOpenURL(URL(string:kCustomURLScheme)!)) {
        print("true")
    }

    if openCustomURLScheme(customURLScheme: kCustomURLScheme) {
        // app was opened successfully
    } else {
        // handle unable to open the app, perhaps redirect to the App Store
        print("unable to open , go to itune store to download it ")
    }
}
</code>```

This function using APPSCHEME to check whether any installed app with specific APPSCHEME can be launched or not , if yes then it will launch else if you having application iTune link then it will open app link (above function calling below method for final launching ):

```<code> func openCustomURLScheme(customURLScheme: String) -> Bool {
        let customURL = URL(string: customURLScheme)!

        if UIApplication.shared.canOpenURL(customURL) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(customURL)
                UIApplication.shared.open(URL(string: "https://itunes.apple.com/in/app/appname/id404249815?mt=8")!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(customURL)
            }
            return true
        }

        return false
    }
</code>```

This code working fine for Swift3.0 and iOS 10 , feel free to share your feedback and comment .

Title: Open URL Schemes in IOS

Body:
I have 2 apps, which are meant for different purpose, where I should not allow user to use both apps in same device. How can I check whether other app installed or not?
I think I can do it using Open URL as following by putting app bundle id which is not working, I am stuck to get url for my app
EX : "fb://"

       if ([[UIApplication sharedApplication] canOpenURL:@"My App URL"]) {
            //App installed
        }
        else{
            //App Not installed
        }

Body:
Swift 3.0 working Answer :

Everything remains same as Selected answer  ( above answer which is answered by user3182143 as this causes few issue by other user so i answered this way , only code implementation is different rest follow same step as answered by above correct answer )

But code implementation is different now :

let kCustomURLScheme = "yourappscheme://"

 func openCustomApp() {
    if (UIApplication.shared.canOpenURL(URL(string:kCustomURLScheme)!)) {
        print("true")
    }

    if openCustomURLScheme(customURLScheme: kCustomURLScheme) {
        // app was opened successfully
    } else {
        // handle unable to open the app, perhaps redirect to the App Store
        print("unable to open , go to itune store to download it ")
    }
}

This function using APPSCHEME to check whether any installed app with specific APPSCHEME can be launched or not , if yes then it will launch else if you having application iTune link then it will open app link (above function calling below method for final launching ):

 func openCustomURLScheme(customURLScheme: String) -> Bool {
        let customURL = URL(string: customURLScheme)!

        if UIApplication.shared.canOpenURL(customURL) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(customURL)
                UIApplication.shared.open(URL(string: "https://itunes.apple.com/in/app/appname/id404249815?mt=8")!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(customURL)
            }
            return true
        }

        return false
    }

This code working fine for Swift3.0 and iOS 10 , feel free to share your feedback and comment .


问:
How should I debug a Nokogiri Null Pointer exception?
A contractor created a fairly complex XSLT for a client of mine.  It works great in various transform testing tools, using real data from our application.   But Nokogiri barfs on it during transform.  With $VERBOSE and $DEBUG set, I still get the uninformative:

```<code>Exception `RuntimeError' at nokogiri/XsltStylesheet.java:231 - java.lang.NullPointerException
</code>```

So I thought I would create a custom Nokogiri Gem with some debug code in it, using this in my Gemfile:

```<code>gem 'nokogiri', :git => 'ssh://git@192.168.185.65:7999/bssc/nokogiri.git'
</code>```

That doesn't work because of a versioning issue I don't understand how to resolve:

```<code>Source does not contain any versions of 'nokogiri java'
</code>```

So at this point I thought I'd reach out and ask the community for a better idea.  I'm sure it's something in the stylesheet that Nokogiri is not happy with, but it is difficult to locate because of the complexity of the XSLT.

Suggestions?

答:
I'm not sure this is the best way, but editing the source in my RVM environment, followed by a minimized build_all, allowed me to remove the exception handling.  My modified XsltStylesheet.java :

```<code>    @JRubyMethod
    public IRubyObject serialize(ThreadContext context, IRubyObject doc) throws IOException, TransformerException {
        XmlDocument xmlDoc = (XmlDocument) doc;
        TransformerImpl transformer = (TransformerImpl) this.sheet.newTransformer();
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(writer);
        SerializationHandler serializationHandler = transformer.createSerializationHandler(streamResult);
        serializationHandler.serialize(xmlDoc.getNode());
        return context.getRuntime().newString(writer.toString());
    }

    @JRubyMethod(rest = true, required=1, optional=2)
    public IRubyObject transform(ThreadContext context, IRubyObject[] args) throws TransformerException, IOException {
        Ruby runtime = context.getRuntime();
System.out.println("in transform");
        argumentTypeCheck(runtime, args[0]);
System.out.println("before listener");

        // NokogiriXsltErrorListener elistener = new NokogiriXsltErrorListener();
    System.out.println("before dom");

        DOMSource domSource = new DOMSource(((XmlDocument) args[0]).getDocument());
        final DOMResult result; String stringResult = null;
    System.out.println("try transform");

            result = tryXsltTransformation(context, args, domSource, null); // DOMResult

        if (stringResult == null) {
            return createDocumentFromDomResult(context, runtime, result);
        } else {
            return createDocumentFromString(context, runtime, stringResult);
        }
    }

    private DOMResult tryXsltTransformation(ThreadContext context, IRubyObject[] args, DOMSource domSource, NokogiriXsltErrorListener elistener) throws TransformerException {
        Transformer transf = sheet.newTransformer();
        transf.reset();
        // transf.setErrorListener(elistener);
        if (args.length > 1) {
            addParametersToTransformer(context, transf, args[1]);
        }

        DOMResult result = new DOMResult();
        transf.transform(domSource, result);
        return result;
    }
</code>```

Here is my build-all script:

```<code>#! /usr/bin/env bash
#
#  script to build gems for all relevant platforms:
#  - MRI et al (standard gem)
#  - windows (x86-mingw32 and x64-mingw32)
#  - jruby
#

# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
    source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
    source "/usr/local/rvm/scripts/rvm"
else
    echo "ERROR: An RVM installation was not found.\n"
fi

set -o errexit

rm -rf tmp pkg
bundle exec rake clean clobber

# holding pen
rm -rf gems
mkdir -p gems

# windows

# MRI

# jruby
bundle exec rake clean clobber
bundle exec rake generate

gem install bundler --conservative
bundle install --quiet --local || bundle install
bundle exec rake gem
cp -v pkg/nokogiri*java.gem gems
</code>```

This produced the output:

```<code>...
try transform
file:///Users/jeff/Documents/BlueSageSource/plus/dummy.xsl; Line #0; Column #0; org.apache.xpath.objects.XRTreeFrag cannot be cast to org.apache.xpath.objects.XNodeSet
file:///Users/jeff/Documents/BlueSageSource/plus/dummy.xsl; Line #0; Column #0; java.lang.NullPointerException
</code>```

The 'cannot be cast' message led me to other information that indicates that Nokogiri does not support XSLT 2.   This is disappointing, not so much because of the limitation, but because it is not well documented, and failing with a null pointer exception is at best unfriendly.  I think we have enough information to create a minimal failing case to file as a request for enhancement.

references:

Nokogiri does not intend to support XSLT 2

Nokogiri does not support XSLT 2

Body:
A contractor created a fairly complex XSLT for a client of mine.  It works great in various transform testing tools, using real data from our application.   But Nokogiri barfs on it during transform.  With $VERBOSE and $DEBUG set, I still get the uninformative:

Exception `RuntimeError' at nokogiri/XsltStylesheet.java:231 - java.lang.NullPointerException

So I thought I would create a custom Nokogiri Gem with some debug code in it, using this in my Gemfile:

gem 'nokogiri', :git => 'ssh://git@192.168.185.65:7999/bssc/nokogiri.git'

That doesn't work because of a versioning issue I don't understand how to resolve:

Source does not contain any versions of 'nokogiri java'

So at this point I thought I'd reach out and ask the community for a better idea.  I'm sure it's something in the stylesheet that Nokogiri is not happy with, but it is difficult to locate because of the complexity of the XSLT.

Suggestions?

Body:
I'm not sure this is the best way, but editing the source in my RVM environment, followed by a minimized build_all, allowed me to remove the exception handling.  My modified XsltStylesheet.java :

    @JRubyMethod
    public IRubyObject serialize(ThreadContext context, IRubyObject doc) throws IOException, TransformerException {
        XmlDocument xmlDoc = (XmlDocument) doc;
        TransformerImpl transformer = (TransformerImpl) this.sheet.newTransformer();
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(writer);
        SerializationHandler serializationHandler = transformer.createSerializationHandler(streamResult);
        serializationHandler.serialize(xmlDoc.getNode());
        return context.getRuntime().newString(writer.toString());
    }

    @JRubyMethod(rest = true, required=1, optional=2)
    public IRubyObject transform(ThreadContext context, IRubyObject[] args) throws TransformerException, IOException {
        Ruby runtime = context.getRuntime();
System.out.println("in transform");
        argumentTypeCheck(runtime, args[0]);
System.out.println("before listener");

        // NokogiriXsltErrorListener elistener = new NokogiriXsltErrorListener();
    System.out.println("before dom");

        DOMSource domSource = new DOMSource(((XmlDocument) args[0]).getDocument());
        final DOMResult result; String stringResult = null;
    System.out.println("try transform");

            result = tryXsltTransformation(context, args, domSource, null); // DOMResult

        if (stringResult == null) {
            return createDocumentFromDomResult(context, runtime, result);
        } else {
            return createDocumentFromString(context, runtime, stringResult);
        }
    }

    private DOMResult tryXsltTransformation(ThreadContext context, IRubyObject[] args, DOMSource domSource, NokogiriXsltErrorListener elistener) throws TransformerException {
        Transformer transf = sheet.newTransformer();
        transf.reset();
        // transf.setErrorListener(elistener);
        if (args.length > 1) {
            addParametersToTransformer(context, transf, args[1]);
        }

        DOMResult result = new DOMResult();
        transf.transform(domSource, result);
        return result;
    }

Here is my build-all script:

#! /usr/bin/env bash
#
#  script to build gems for all relevant platforms:
#  - MRI et al (standard gem)
#  - windows (x86-mingw32 and x64-mingw32)
#  - jruby
#

# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
    source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
    source "/usr/local/rvm/scripts/rvm"
else
    echo "ERROR: An RVM installation was not found.\n"
fi

set -o errexit

rm -rf tmp pkg
bundle exec rake clean clobber

# holding pen
rm -rf gems
mkdir -p gems

# windows

# MRI

# jruby
bundle exec rake clean clobber
bundle exec rake generate

gem install bundler --conservative
bundle install --quiet --local || bundle install
bundle exec rake gem
cp -v pkg/nokogiri*java.gem gems

This produced the output:

...
try transform
file:///Users/jeff/Documents/BlueSageSource/plus/dummy.xsl; Line #0; Column #0; org.apache.xpath.objects.XRTreeFrag cannot be cast to org.apache.xpath.objects.XNodeSet
file:///Users/jeff/Documents/BlueSageSource/plus/dummy.xsl; Line #0; Column #0; java.lang.NullPointerException

The 'cannot be cast' message led me to other information that indicates that Nokogiri does not support XSLT 2.   This is disappointing, not so much because of the limitation, but because it is not well documented, and failing with a null pointer exception is at best unfriendly.  I think we have enough information to create a minimal failing case to file as a request for enhancement.

references:

Nokogiri does not intend to support XSLT 2

Nokogiri does not support XSLT 2