问:
Appending an element to the end of a list in Scala
I can't add an element of type T into a list List[T].
I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?

答:
We can append or prepend two lists or list&array

Append:

```<code>var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
  l.foreach(println)

Result:1 2 3 4 5 6
</code>```

Prepending:

```<code>var l = List[Int]()
   for(x <- ar)
    { l= x :: l } //prepending
     l.foreach(println)

Result:6 5 4 1 2 3
</code>```

Body:
We can append or prepend two lists or list&array

Append:

var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
  l.foreach(println)

Result:1 2 3 4 5 6

Prepending:

var l = List[Int]()
   for(x <- ar)
    { l= x :: l } //prepending
     l.foreach(println)

Result:6 5 4 1 2 3


来源: stackexchange

问:
"Gradle files have changed since last project sync." message always shows up
I'm working on an Android Studio project of which I write while constantly move back and forth from laptop to desktop using usb stick. There has been no problem for couple of months I tried this since Android Studio went stable, until today this message keeps showing up no matter how many times I sync the gradle:

Gradle files have changed since last project sync. A project sync may be necessary for the IDE to work properly.

Gradle Console indicates that the build is successful. I also tried cleaning and rebuilding the project, even reinstalling Android Studio, still the message pops out.

What seems to be the problem? Is it not recommended to write a project on multiple Android Studios?

Here's a look of my build.gradle:

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

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.simplifyinc.prodigy"
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 1
    versionName "0.3.2"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'net.the4thdimension:audio-wife:1.0.3'
    compile project('libraries:android-crop')
}
</code>```

答:
this error had happened to me when I changed my computer time carelessly
configer my computer time,and reset the time,this error solved</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an Android Studio project of which I write while constantly move back and forth from laptop to desktop using usb stick. There has been no problem for couple of months I tried this since Android Studio went stable, until today this message keeps showing up no matter how many times I sync the gradle:

Gradle files have changed since last project sync. A project sync may be necessary for the IDE to work properly.

Gradle Console indicates that the build is successful. I also tried cleaning and rebuilding the project, even reinstalling Android Studio, still the message pops out.

What seems to be the problem? Is it not recommended to write a project on multiple Android Studios?

Here's a look of my build.gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.simplifyinc.prodigy"
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 1
    versionName "0.3.2"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'net.the4thdimension:audio-wife:1.0.3'
    compile project('libraries:android-crop')
}


问:
Yet struggling to parse JSON with jq
I'm slowly getting a grip of how jq works but am still far from mastering it.
Now I'm in a situation I've kinda managed to get what I wanted but not to display it the way I want. I'm sure it's quite simple but I'm missing it...

Here's a sample of the JSON I want to parse:

```<code>{
    "sites": [
        {
            "site_id": 123456,
            "status": "configured",
            "domain": "www.domain.com",
            "account_id": 654321,
            "security": {
                "waf": {
                    "rules": [
                        {
                            "action": "block_request",
                            "action_text": "Block",
                            "id": "sqli",
                            "name": "SQLi"
                        },
                        {
                            "action": "block_request",
                            "action_text": "Block",
                            "id": "xss",
                            "name": "XSS"
                        },
                        {
                            "action": "alert",
                            "action_text": "Alert",
                            "id": "path_vector",
                            "name": "Path Vector"
                        }
                    ]
                }
            }
        }
    ],
    "res": 0,
    "res_message": "OK",
    "debug_info": {
        "id-info": "9123"
    }
}
</code>```

I only need a few details and put them in CSV format, here's what I did so far:

```<code>cat test.json | jq -r '.sites [] | [.site_id,.domain],(.security.waf.rules[] | [.action_text]) | @csv'
</code>```

This is the ouput I got:

```<code>123456,"www.domain.com"
"Block"
"Block"
"Alert"
</code>```

Not so bad, but what I'm looking for is something like this:

```<code>123456,"www.domain.com","Block","Block","Alert"
</code>```

Same result, just displayed in one single line.
I went over the man pages and fiddled around for a while to no avail.
Is it possible to do it or I need a different tool to manipulate it?

Thanks in advance!

答:
All the values to be printed in a CSV row must be collected in a JSON array.  A solution that is very similar to your attempt would therefore be:

```<code>.sites[]
| [.site_id, .domain, (.security.waf.rules[] | .action_text) ]
| @csv
</code>```

By the way, there is no need to use cat:

```<code>jq -r -f program.jq test.json
</code>```

Title: Yet struggling to parse JSON with jq

Body:
I'm slowly getting a grip of how jq works but am still far from mastering it.
Now I'm in a situation I've kinda managed to get what I wanted but not to display it the way I want. I'm sure it's quite simple but I'm missing it...

Here's a sample of the JSON I want to parse:

{
    "sites": [
        {
            "site_id": 123456,
            "status": "configured",
            "domain": "www.domain.com",
            "account_id": 654321,
            "security": {
                "waf": {
                    "rules": [
                        {
                            "action": "block_request",
                            "action_text": "Block",
                            "id": "sqli",
                            "name": "SQLi"
                        },
                        {
                            "action": "block_request",
                            "action_text": "Block",
                            "id": "xss",
                            "name": "XSS"
                        },
                        {
                            "action": "alert",
                            "action_text": "Alert",
                            "id": "path_vector",
                            "name": "Path Vector"
                        }
                    ]
                }
            }
        }
    ],
    "res": 0,
    "res_message": "OK",
    "debug_info": {
        "id-info": "9123"
    }
}

I only need a few details and put them in CSV format, here's what I did so far:

cat test.json | jq -r '.sites [] | [.site_id,.domain],(.security.waf.rules[] | [.action_text]) | @csv'

This is the ouput I got:

123456,"www.domain.com"
"Block"
"Block"
"Alert"

Not so bad, but what I'm looking for is something like this:

123456,"www.domain.com","Block","Block","Alert"

Same result, just displayed in one single line.
I went over the man pages and fiddled around for a while to no avail.
Is it possible to do it or I need a different tool to manipulate it?

Thanks in advance!

Body:
All the values to be printed in a CSV row must be collected in a JSON array.  A solution that is very similar to your attempt would therefore be:

.sites[]
| [.site_id, .domain, (.security.waf.rules[] | .action_text) ]
| @csv

By the way, there is no need to use cat:

jq -r -f program.jq test.json


问:
Get shared calendars from Office 365 API
So, here is the problem. I searched all over the MSDN and here on Stack but there isn't one definitive answer how to get (or is it even possible as of today?) to access Shared calendars in Office365.

I followed this tutorial and here is offending method:

```<code>public async Task<ActionResult> Index()
    {
        List<MyCalendar> myCalendars = new List<MyCalendar>();

        var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

        try
        {
            DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });

            var discoveryCapabilitiesResult = await discClient.DiscoverCapabilitiesAsync();

            var dcr = await discClient.DiscoverCapabilityAsync("Calendar");

            OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });

            //var calendarsResult = await exClient.Me.Calendars.ExecuteAsync();

            var calendarsResult = await exClient.Me.Calendars.ExecuteAsync();

            do
            {
                var calendars = calendarsResult.CurrentPage;
                foreach (var c in calendars)
                {
                    myCalendars.Add(new MyCalendar { DisplayName = c.Name });
                }

                calendarsResult = await calendarsResult.GetNextPageAsync();

            } while (calendarsResult != null);
        }
        catch (AdalException exception)
        {
            //handle token acquisition failure
            if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
            {
                authContext.TokenCache.Clear();

                //handle token acquisition failure
            }
        }

        return View(myCalendars);
    }
</code>```

This function will return only Calendar under "My Calendars" but not the others (see the picture)

I get only the first one - that is mine calendar. Second one under "My Calendars" is shared with me (I'm not the author, somebody else is and I have r/w on it) and one under "Shared Calendars" is company-wide one (on this one I also have r/w permissions).

Is there a way to get all of them? On portal.azure.com my app is added and I set permissions for both mine and shared calendars:

I have no idea what to do. Contacts are working properly but I cannot find a way to get any shared calendar.

答:
Based on the test, the Microsoft Graph could get the all calendars. Here is the rest for your reference:

Shared calendar from chenchenLi to NanYu:

Query the calendars from NanYu:

More detail about the Microsoft Graph REST to get the calendars, you can refer the link below:

List calendars

Body:
So, here is the problem. I searched all over the MSDN and here on Stack but there isn't one definitive answer how to get (or is it even possible as of today?) to access Shared calendars in Office365.

I followed this tutorial and here is offending method:

public async Task<ActionResult> Index()
    {
        List<MyCalendar> myCalendars = new List<MyCalendar>();

        var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

        try
        {
            DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });

            var discoveryCapabilitiesResult = await discClient.DiscoverCapabilitiesAsync();

            var dcr = await discClient.DiscoverCapabilityAsync("Calendar");

            OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });

            //var calendarsResult = await exClient.Me.Calendars.ExecuteAsync();

            var calendarsResult = await exClient.Me.Calendars.ExecuteAsync();

            do
            {
                var calendars = calendarsResult.CurrentPage;
                foreach (var c in calendars)
                {
                    myCalendars.Add(new MyCalendar { DisplayName = c.Name });
                }

                calendarsResult = await calendarsResult.GetNextPageAsync();

            } while (calendarsResult != null);
        }
        catch (AdalException exception)
        {
            //handle token acquisition failure
            if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
            {
                authContext.TokenCache.Clear();

                //handle token acquisition failure
            }
        }

        return View(myCalendars);
    }

This function will return only Calendar under "My Calendars" but not the others (see the picture)

I get only the first one - that is mine calendar. Second one under "My Calendars" is shared with me (I'm not the author, somebody else is and I have r/w on it) and one under "Shared Calendars" is company-wide one (on this one I also have r/w permissions).

Is there a way to get all of them? On portal.azure.com my app is added and I set permissions for both mine and shared calendars:

I have no idea what to do. Contacts are working properly but I cannot find a way to get any shared calendar.


答:
First lets discuss why you received that result.

When you use [] to extract items from objects/arrays, it yields a value for every item in that object/array.

```<code>.sites[]
</code>```

produces a result for the every value in your sites array (which in this case there's only one).

Another thing to note, using a comma (,) will yield the delimited values within that expression.

```<code>[.site_id,.domain]
</code>```

The comma here produces two values, the site_id and the domain.  But, those values are collected in to an array (as denoted by the square brackets).

Putting this into the next part of the expression

```<code>.security.waf.rules[] | [.action_text]
</code>```

The first part goes through all the rules objects in that array. Then for each of those objects, creates an array containing the action_text.  This creates three arrays (one for each of the rules).

Put this together with the previous part of the expression (slightly reformatted)

```<code>([.site_id,.domain]) , (.security.waf.rules[] | [.action_text])
</code>```

This all together produces four arrays, the array containing the site_id and domain, followed by the three arrays of action_text.

Then for each of those four arrays, a csv row is created giving you the results you see.

So how can we get the desired results?

First, we'll want to start go through all the sites.  I'm assuming you want a row per site.

```<code>.sites[]
</code>```

Then for each site, we need to build an array of the values in that row.  Start with what we have direct access to.

```<code>.site_id, .domain
</code>```

Then produce the action_text values.

```<code>.security.waf.rules[].action_text
</code>```

Note we're not putting the action_text in a separate array, we just want the value.

Now we put those values together.

```<code>.site_id, .domain, (.security.waf.rules[].action_text)
</code>```

This creates five values as we discussed, but we want to collect them in an array so we may pass it to the @csv filter.

```<code>[.site_id, .domain, (.security.waf.rules[].action_text)]
</code>```

Putting everything together will give us this filter:

```<code>.sites[] | [.site_id, .domain, (.security.waf.rules[].action_text)] | @csv
</code>```

Of course there's many approaches you can take to get these values (like building out arrays separately then combining them) but this is the most direct.

Title: Yet struggling to parse JSON with jq

Body:
First lets discuss why you received that result.

When you use [] to extract items from objects/arrays, it yields a value for every item in that object/array.

.sites[]

produces a result for the every value in your sites array (which in this case there's only one).

Another thing to note, using a comma (,) will yield the delimited values within that expression.

[.site_id,.domain]

The comma here produces two values, the site_id and the domain.  But, those values are collected in to an array (as denoted by the square brackets).

Putting this into the next part of the expression

.security.waf.rules[] | [.action_text]

The first part goes through all the rules objects in that array. Then for each of those objects, creates an array containing the action_text.  This creates three arrays (one for each of the rules).

Put this together with the previous part of the expression (slightly reformatted)

([.site_id,.domain]) , (.security.waf.rules[] | [.action_text])

This all together produces four arrays, the array containing the site_id and domain, followed by the three arrays of action_text.

Then for each of those four arrays, a csv row is created giving you the results you see.

So how can we get the desired results?

First, we'll want to start go through all the sites.  I'm assuming you want a row per site.

.sites[]

Then for each site, we need to build an array of the values in that row.  Start with what we have direct access to.

.site_id, .domain

Then produce the action_text values.

.security.waf.rules[].action_text

Note we're not putting the action_text in a separate array, we just want the value.

Now we put those values together.

.site_id, .domain, (.security.waf.rules[].action_text)

This creates five values as we discussed, but we want to collect them in an array so we may pass it to the @csv filter.

[.site_id, .domain, (.security.waf.rules[].action_text)]

Putting everything together will give us this filter:

.sites[] | [.site_id, .domain, (.security.waf.rules[].action_text)] | @csv

Of course there's many approaches you can take to get these values (like building out arrays separately then combining them) but this is the most direct.


问:
can a chef cookbook has only a resource and no recipe
I need to write a cookbook that calls a recipe of an existing cookbook. In addition to it, it will just have a  resource.

Other cookbooks will call this resource. My question is can a cookbook has only a resource and no recipe.

答: The answer is yes. There is simply no such restriction that a cookbook has to contain any recipes. You can put libraries or resources or even only attributes into a cookbook.


问:
Remove button shutdown on raspberry login screen
How can i remove the shutdown button on raspberry login screen ?

Or can i force reboot when user click on it ? Or disable it ?

Thanks

答:
I found this :

Disable shutdown with polkit

```<code>sudo nano /etc/polkit-1/localauthority/50-local.d/restrict-login-powermgmt.pkla

# Add this :
[Disable lightdm PowerMgmt]
Identity=unix-user:*
Action=org.freedesktop.login1.reboot;org.freedesktop.login1.reboot-multiple-sessions;org.freedesktop.login1.power-off;org.freedesktop.login1.power-off-multiple-sessions;org.freedesktop.login1.suspend;org.freedesktop.login1.suspend-multiple-sessions;org.freedesktop.login1.hibernate;org.freedesktop.login1.hibernate-multiple-sessions
ResultAny=no
ResultInactive=no
ResultActive=no
</code>```

Body:
I found this :

Disable shutdown with polkit

sudo nano /etc/polkit-1/localauthority/50-local.d/restrict-login-powermgmt.pkla

# Add this :
[Disable lightdm PowerMgmt]
Identity=unix-user:*
Action=org.freedesktop.login1.reboot;org.freedesktop.login1.reboot-multiple-sessions;org.freedesktop.login1.power-off;org.freedesktop.login1.power-off-multiple-sessions;org.freedesktop.login1.suspend;org.freedesktop.login1.suspend-multiple-sessions;org.freedesktop.login1.hibernate;org.freedesktop.login1.hibernate-multiple-sessions
ResultAny=no
ResultInactive=no
ResultActive=no


问:
PHP Method chaining with dynamic names
I was wondering if it's possible to create a method chaining using the values (or keys) of an array as the dynamic names of the methods.

For example, I have an array:
$methods = ['first', 'second', 'third']

Is it possible to create the following call ?

```<code>first()->second()->third();
</code>```

答:
You can also use eval function.
Example:</p>

```<code>$object = new SomeClass(); // first, second, third
$methods = ['first', 'second', 'third'];

$callStr = 'return $object->';

foreach($methods as $method){
    $callStr.= $method . '()->';
}

$callStr = substr($callStr, 0, -2);
$callStr.= ';'; // return $object->first()->second()->third();

$result = eval($callStr); // return result of call - $object->first()->second()->third();
</code>```

Title: PHP Method chaining with dynamic names

Body:
I was wondering if it's possible to create a method chaining using the values (or keys) of an array as the dynamic names of the methods.

For example, I have an array:
$methods = ['first', 'second', 'third']

Is it possible to create the following call ?

first()->second()->third();

Body:
You can also use eval function.
Example:

$object = new SomeClass(); // first, second, third
$methods = ['first', 'second', 'third'];

$callStr = 'return $object->';

foreach($methods as $method){
    $callStr.= $method . '()->';
}

$callStr = substr($callStr, 0, -2);
$callStr.= ';'; // return $object->first()->second()->third();

$result = eval($callStr); // return result of call - $object->first()->second()->third();


问:
is there a way to read only new (unread) messages in kafka consumer?
in consumer when subscribed to a topic and start consuming messages it read the messages from the the beginning is there any way to read only unread messages ? this is the code i used for consuming the messages.</p>

```<code>  Properties props = new Properties();
  props.put("bootstrap.servers", "localhost:9092");
  props.put("group.id", "test");
  props.put("enable.auto.commit", "true");
  props.put("auto.commit.interval.ms", "1000");
  props.put("session.timeout.ms", "30000");
  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");

  KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

  //Kafka Consumer subscribes list of topics here.
  consumer.subscribe(Arrays.asList(topicName));

  while (true) {
      ConsumerRecords<String, String> records = consumer.poll(100);
      for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value= %s\n", record.offset(), record.key(), record.value());

  }
</code>```

答: Turn off auto.commit and manually commit each message offset after your app has successfully read it. That way if the app crashes it will restart at exactly the last committed offset.</p>

Body:
in consumer when subscribed to a topic and start consuming messages it read the messages from the the beginning is there any way to read only unread messages ? this is the code i used for consuming the messages.

  Properties props = new Properties();
  props.put("bootstrap.servers", "localhost:9092");
  props.put("group.id", "test");
  props.put("enable.auto.commit", "true");
  props.put("auto.commit.interval.ms", "1000");
  props.put("session.timeout.ms", "30000");
  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");

  KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

  //Kafka Consumer subscribes list of topics here.
  consumer.subscribe(Arrays.asList(topicName));

  while (true) {
      ConsumerRecords<String, String> records = consumer.poll(100);
      for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value= %s\n", record.offset(), record.key(), record.value());

  }


问:
How to redirect subdomain to main domain maintaining the same URL?
My main domain(www.mysite.com) is pointing to a folder in my server (/home/user_name/htdocs/mysite.com).

I have recently created a subdomain(m.mysite.com) through my hosting account. But it is pointing it to a new folder (/home/user_name/htdocs/m.mysite.com) in my server. I am not able to edit the path to which this new subdomain points to. All my files are hosted in my main folder path.

My Requirement -

When a user visits m.mysite.com he should be redirected to mysite.com but the URL in the browser should still say m.mysite.com

I'm handling the mobile view by detecting the subdomain using $_SERVER['SERVER_NAME']

答:
```<code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^m.mysite\.com
RewriteRule (.*) http://www.mysite.com/$1 [R=301, L]
</code>```

ContentLicense: CC BY-SA 2.5


问:
How to resolve request mapping "ambiguous" situation in spring controller?
I have written a spring controller in which I just wanted to use single URL for all methods.
Even I am using different method signature int, string, object i am getting error.

```<code>@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketData(@RequestParam("customerId") int customerId) {
    return "customer Id: "+customerId+" has active Ticket:1010101";
}

@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketStatusByCustname(@RequestParam("customerName") String customerName) {
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

@RequestMapping(value="problemAPI/ticket", method = RequestMethod.POST )
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
    return "Mr." + bean.getCustomerName() + " Ticket" +  bean.getTicketNo() + " has been submitted successfuly";
}
</code>```

Error:

```<code>java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'problemTicketController' bean method
public String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketData(int)
to {[/problemAPI/ticket],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'problemTicketController' bean method
public java.lang.String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketByCustname(int) mapped.
</code>```

答:
You can achieve this by explicitly specifying query parameters with params annotation property:

@RequestMapping(
    value  = "problemAPI/ticket",
    params = "customerId",
    method = RequestMethod.GET
)
public @ResponseBody String getTicketData(
    @RequestParam("customerId") int customerId
){
    return "customer Id: " + customerId + " has active Ticket:1010101";
}

@RequestMapping(
    value  = "problemAPI/ticket",
    params = "customerName",
    method = RequestMethod.GET
)
public @ResponseBody String getTicketStatusByCustomerName(
    @RequestParam("customerName") String customerName
){
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}
```
<p>To make it cleaner you can use alias annotations like <code>@GetMapping</code> and <code>@PostMapping</code>:</p>
<pre class="lang-java prettyprint-override"><code>@GetMapping(
    value  = "problemAPI/ticket",
    params = "customerName"
)
public @ResponseBody String getTicketStatusByCustname(
    @RequestParam("customerName") String customerName
) {
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

@PostMapping(
    value = "problemAPI/ticket"
)
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
    return "Mr." + bean.getCustomerName() + " Ticket" +  bean.getTicketNo() + " has been submitted successfuly";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written a spring controller in which I just wanted to use single URL for all methods.
Even I am using different method signature int, string, object i am getting error.

@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketData(@RequestParam("customerId") int customerId) {
    return "customer Id: "+customerId+" has active Ticket:1010101";
}

@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketStatusByCustname(@RequestParam("customerName") String customerName) {
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

@RequestMapping(value="problemAPI/ticket", method = RequestMethod.POST )
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
    return "Mr." + bean.getCustomerName() + " Ticket" +  bean.getTicketNo() + " has been submitted successfuly";
}

Error:

java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'problemTicketController' bean method
public String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketData(int)
to {[/problemAPI/ticket],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'problemTicketController' bean method
public java.lang.String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketByCustname(int) mapped.

Body:
You can achieve this by explicitly specifying query parameters with params annotation property:

@RequestMapping(
    value  = "problemAPI/ticket",
    params = "customerId",
    method = RequestMethod.GET
)
public @ResponseBody String getTicketData(
    @RequestParam("customerId") int customerId
){
    return "customer Id: " + customerId + " has active Ticket:1010101";
}

@RequestMapping(
    value  = "problemAPI/ticket",
    params = "customerName",
    method = RequestMethod.GET
)
public @ResponseBody String getTicketStatusByCustomerName(
    @RequestParam("customerName") String customerName
){
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

To make it cleaner you can use alias annotations like @GetMapping and @PostMapping:

@GetMapping(
    value  = "problemAPI/ticket",
    params = "customerName"
)
public @ResponseBody String getTicketStatusByCustname(
    @RequestParam("customerName") String customerName
) {
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

@PostMapping(
    value = "problemAPI/ticket"
)
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
    return "Mr." + bean.getCustomerName() + " Ticket" +  bean.getTicketNo() + " has been submitted successfuly";
}


问:
Why does this error 1066 show up from join statesment
I have yet another issue. I am trying to join 2 tables so that i can pull data from both. I am new to TableGateway and am having issues finding the same situation. I have a page that will pull blogs by state and i also have a state table. I want to join these using state_id and show "state" from state table on the page. Below is what i have. Not sure if i am even using the right code!

Model - From StateTable:

```<code>public function getState($state)
{
$sqlSelect = $this->tableGateway->getSql()->select();
$sqlSelect->columns(array('state_id'));
$sqlSelect->join('states', 'states.state_id = state_id', array('state'), 'inner');

$statement =   $this->tableGateway->getSql()->prepareStatementForSqlObject($sqlSelect);
$resultSet = $statement->execute();
return $resultSet;
</code>```

}

Model from PostTable:

```<code>   public function getbystate($state_id)
   {
    $state_id  = (int) $state_id;
    $rowset = $this->tableGateway->select(array('state_id' => $state_id));

    return $rowset;
   }
</code>```

Controller action:

```<code> public function ListAction()
 {
  $state_id = $this->params()->fromRoute('state_id');
  $state = $this->params('state');
  $list = $this->getPostsTable()->getbystate($state_id);
  $states = $this->getStatesTable()->getState($state);
  $view = new ViewModel(array(
    'list' => $list,
    'states' => $states,
  ));

  return $view;
 }
</code>```

Update 8:41 EST 06/06/2017

I put the join in the Posts module instead of in the States Model.
I have gotten rid of the errors however I still need to know how to show the state. Everything above is the same except it resides in the posts module.

The "View" is below - it errors
Notice: Undefined property: Zend\Db\Adapter\Driver\Pdo\Result::$state in /var/www/html/module/Blog/view/blog/list.phtml on line 6

View:

```<code> $title = 'My Blog';
 $this->headTitle($title);
 ?>
 <h1><?php echo $this->escapeHtml($title); ?></h1>
 <td><?php echo $this->escapeHtml($states->state);?></td>
 <table class="table">
 <tr>
  <th>Title</th>
  <th>View</th>
  <th>Comments</th>
  <th>Post Date</th>

 </tr>
 <?php foreach ($list as $posts) : ?>
 <tr>
   <td>
     <a href="/Blog/view/<?php echo $this->escapeHtml($posts->post_id);?>">
     <?php echo $this->escapeHtml($posts->post_title);?>
   </a>
 </td>
 <td><?php echo $this->escapeHtml($posts->num_views);?></td>
 <td><?php echo $this->escapeHtml($posts->num_comments);?></td>
 <td><?php echo $this->escapeHtml($posts->post_date);?></td>

 </tr>
 <?php endforeach; ?>
 </table>
</code>```

Added tables 12:01 EST 06/07/2017
 Post Table:

```<code> CREATE TABLE `posts` (
 `post_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `state_id` smallint(6) DEFAULT NULL,
 `created_user_id` int(11) DEFAULT NULL,
 `post_title` varchar(255) NOT NULL,
 `post_date` datetime DEFAULT NULL,
 `is_active` tinyint(4) NOT NULL,
 `status` enum('deleted','draft','inactive','active') DEFAULT 'inactive',
 `activate_date` datetime DEFAULT NULL,
 `is_hot` tinyint(4) DEFAULT '0',
 `ordering` int(11) DEFAULT '0',
 `num_views` int(11) DEFAULT '0',
 `allow_comment` tinyint(4) DEFAULT NULL,
 `num_comments` int(11) DEFAULT '0',
 `picLink` varchar(50) DEFAULT NULL,
 `description` varchar(1000) DEFAULT NULL,
 `food` enum('Yes',' No') DEFAULT NULL,
 PRIMARY KEY (`post_id`),
 KEY `idx_latest` (`status`,`activate_date`),
 KEY `idx_latest_category` (`state_id`,`status`,`activate_date`),
 KEY `idx_most_commented` (`state_id`,`status`,`num_comments`) USING BTREE,
 KEY `idx_most_viewed` (`state_id`,`status`,`num_views`) USING BTREE,
 KEY `idx_most_viewed_2` (`status`,`num_views`),
 KEY `idx_created_user` (`created_user_id`,`post_id`)
</code>```

States Table:

```<code> CREATE TABLE `states` (
 `state_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `state` varchar(45) NOT NULL,
 PRIMARY KEY (`state_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;
</code>```

答:
You do not need to join posts and states tables to show state according to your list.phtml. You are trying to output state there like $states->state therefore, this is completely outside loop. So you need to fetch an object from which you can output state the way you wanted. Make another method in the StatesTable model to get it worked. See the following

```<code>public function getStateById($state_id)
{
    $state_id  = (int) $state_id;
    $rowset = $this->tableGateway->select(array('state_id' => $state_id));
    $row = $rowset->current();

    if (!$row) {
        throw new \Exception("Could not find row $state_id");
    }

    return $row;
}
</code>```

And getbystate($state_id) method from PostsTable model should be unchanged like you wrote above. listAction() method should be the following

```<code>public function ListAction()
{
    $state_id = $this->params()->fromRoute('state_id');

    $list = $this->getPostsTable()->getbystate($state_id);
    $states = $this->getStatesTable()->getStateById($state_id);

    $view = new ViewModel(array(
        'list' => $list,
        'states' => $states,
    ));

    return $view;
}
</code>```

Now as I told your sql query for joining two tables was not right, that would like this

```<code>public function getState($state)
{
    $state = (string) $state;
    $sqlSelect = $this->tableGateway->getSql()->select();

    // Specify columns from 'posts' table
    $sqlSelect->columns(array('post_title', 'description', 'etc'));

    // Here you can specify columns for 'states' table
    $sqlSelect->join('states', 'posts.post_id = states.state_id', array('state', 'etc'), 'inner');

    // Apply conditions here
    $sqlSelect->where(array('states.state' => $state));

    $resultSet = $this->tableGateway->selectWith($sqlSelect);

    return $resultSet;

}
</code>```

This method has a limitation. You cant convert this resultset object to array because of result-set prototype issue. But this will work somehow.

Body:
I have yet another issue. I am trying to join 2 tables so that i can pull data from both. I am new to TableGateway and am having issues finding the same situation. I have a page that will pull blogs by state and i also have a state table. I want to join these using state_id and show "state" from state table on the page. Below is what i have. Not sure if i am even using the right code!

Model - From StateTable:

public function getState($state)
{
$sqlSelect = $this->tableGateway->getSql()->select();
$sqlSelect->columns(array('state_id'));
$sqlSelect->join('states', 'states.state_id = state_id', array('state'), 'inner');

$statement =   $this->tableGateway->getSql()->prepareStatementForSqlObject($sqlSelect);
$resultSet = $statement->execute();
return $resultSet;

}

Model from PostTable:

   public function getbystate($state_id)
   {
    $state_id  = (int) $state_id;
    $rowset = $this->tableGateway->select(array('state_id' => $state_id));

    return $rowset;
   }

Controller action:

 public function ListAction()
 {
  $state_id = $this->params()->fromRoute('state_id');
  $state = $this->params('state');
  $list = $this->getPostsTable()->getbystate($state_id);
  $states = $this->getStatesTable()->getState($state);
  $view = new ViewModel(array(
    'list' => $list,
    'states' => $states,
  ));

  return $view;
 }

Update 8:41 EST 06/06/2017

I put the join in the Posts module instead of in the States Model.
I have gotten rid of the errors however I still need to know how to show the state. Everything above is the same except it resides in the posts module.

The "View" is below - it errors
Notice: Undefined property: Zend\Db\Adapter\Driver\Pdo\Result::$state in /var/www/html/module/Blog/view/blog/list.phtml on line 6

View:

 $title = 'My Blog';
 $this->headTitle($title);
 ?>

<?php echo $this->escapeHtml($title); ?>

 <?php echo $this->escapeHtml($states->state);?>

  Title
  View
  Comments
  Post Date

 <?php foreach ($list as $posts) : ?>

     <a href="/Blog/view/<?php echo $this->escapeHtml($posts->post_id);?>">
     <?php echo $this->escapeHtml($posts->post_title);?>

 <?php echo $this->escapeHtml($posts->num_views);?>
 <?php echo $this->escapeHtml($posts->num_comments);?>
 <?php echo $this->escapeHtml($posts->post_date);?>

 <?php endforeach; ?>

Added tables 12:01 EST 06/07/2017
 Post Table:

 CREATE TABLE `posts` (
 `post_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `state_id` smallint(6) DEFAULT NULL,
 `created_user_id` int(11) DEFAULT NULL,
 `post_title` varchar(255) NOT NULL,
 `post_date` datetime DEFAULT NULL,
 `is_active` tinyint(4) NOT NULL,
 `status` enum('deleted','draft','inactive','active') DEFAULT 'inactive',
 `activate_date` datetime DEFAULT NULL,
 `is_hot` tinyint(4) DEFAULT '0',
 `ordering` int(11) DEFAULT '0',
 `num_views` int(11) DEFAULT '0',
 `allow_comment` tinyint(4) DEFAULT NULL,
 `num_comments` int(11) DEFAULT '0',
 `picLink` varchar(50) DEFAULT NULL,
 `description` varchar(1000) DEFAULT NULL,
 `food` enum('Yes',' No') DEFAULT NULL,
 PRIMARY KEY (`post_id`),
 KEY `idx_latest` (`status`,`activate_date`),
 KEY `idx_latest_category` (`state_id`,`status`,`activate_date`),
 KEY `idx_most_commented` (`state_id`,`status`,`num_comments`) USING BTREE,
 KEY `idx_most_viewed` (`state_id`,`status`,`num_views`) USING BTREE,
 KEY `idx_most_viewed_2` (`status`,`num_views`),
 KEY `idx_created_user` (`created_user_id`,`post_id`)

States Table:

 CREATE TABLE `states` (
 `state_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `state` varchar(45) NOT NULL,
 PRIMARY KEY (`state_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;

Body:
You do not need to join posts and states tables to show state according to your list.phtml. You are trying to output state there like $states->state therefore, this is completely outside loop. So you need to fetch an object from which you can output state the way you wanted. Make another method in the StatesTable model to get it worked. See the following

public function getStateById($state_id)
{
    $state_id  = (int) $state_id;
    $rowset = $this->tableGateway->select(array('state_id' => $state_id));
    $row = $rowset->current();

    if (!$row) {
        throw new \Exception("Could not find row $state_id");
    }

    return $row;
}

And getbystate($state_id) method from PostsTable model should be unchanged like you wrote above. listAction() method should be the following

public function ListAction()
{
    $state_id = $this->params()->fromRoute('state_id');

    $list = $this->getPostsTable()->getbystate($state_id);
    $states = $this->getStatesTable()->getStateById($state_id);

    $view = new ViewModel(array(
        'list' => $list,
        'states' => $states,
    ));

    return $view;
}

Now as I told your sql query for joining two tables was not right, that would like this

public function getState($state)
{
    $state = (string) $state;
    $sqlSelect = $this->tableGateway->getSql()->select();

    // Specify columns from 'posts' table
    $sqlSelect->columns(array('post_title', 'description', 'etc'));

    // Here you can specify columns for 'states' table
    $sqlSelect->join('states', 'posts.post_id = states.state_id', array('state', 'etc'), 'inner');

    // Apply conditions here
    $sqlSelect->where(array('states.state' => $state));

    $resultSet = $this->tableGateway->selectWith($sqlSelect);

    return $resultSet;

}

This method has a limitation. You cant convert this resultset object to array because of result-set prototype issue. But this will work somehow.


问:
Custom Domain with Hadoop Cluster?
I'm working on a research project and I currently own a domain (let's call it abc.xyz). I have purchased it on NameCheap and have some basic HTML/CSS/JavaScript running at the domain name (i.e. http://abc.xyz/index.html).

What I would like to do is use that same domain's sub-domains to be the FQDN for the Hadoop's domain, such that the master host would be master.abc.xyz and slaveX (where X is a number 1, 2, 3...) host would be slaveX.abc.xyz. What are the steps I must take to achieve this configuration? Will I have to give up hosting through NameCheap's cPanel?

答:
In the control panel for your domain host you should find the option to add either A and or CNAME records to your existing domain abc.xyz.

As you have indicated you have IP addresses for each Hadoop instance then you could add A records along these lines;

```<code>master A <IP of master instance>
slave1 A <IP of slave 1>
slave2 A <IP of slave 2>
</code>```

You also have the option of using CNAME records which are simply and alias for the existing domain name your Hadoop instances have.

```<code>master CNAME <fqdn of instance>
slave1 CNAME <fqdn of instance>
slave2 CNAME <fqdn of instance>
</code>```

Once you have made your changes remember to increment your zone serial number (presuming the control panel doesn't do it for you.) wait a short time then your changes should propagate and allow you to access your instances via your own domain name.

If you need further help please post a comment & I can update my answer for you.

Title: Custom Domain with Hadoop Cluster?

Body:
In the control panel for your domain host you should find the option to add either A and or CNAME records to your existing domain abc.xyz.

As you have indicated you have IP addresses for each Hadoop instance then you could add A records along these lines;

master A <IP of master instance>
slave1 A <IP of slave 1>
slave2 A <IP of slave 2>

You also have the option of using CNAME records which are simply and alias for the existing domain name your Hadoop instances have.

master CNAME <fqdn of instance>
slave1 CNAME <fqdn of instance>
slave2 CNAME <fqdn of instance>

Once you have made your changes remember to increment your zone serial number (presuming the control panel doesn't do it for you.) wait a short time then your changes should propagate and allow you to access your instances via your own domain name.

If you need further help please post a comment & I can update my answer for you.


问:
Fairplay encryption on enterprise iOS applications
I am building an app that will be distributed with an enterprise license.  I am following these steps to build the application from xcode:

Choose Generic iOS Device.

Product -> Archive

Window -> Organizer -> Export -> Save for Enterprise Deployment

However when I generate an IPA in this fashion I don't think the binary is encrypted using apples fairplay.

I unzipped the IPA then ran this on the binary:

```<code>otool -arch armv7 -l thebinary | grep crypt
</code>```

Which produced:

```<code> cryptoff 15584
cryptsize 2364346
  cryptid 0
</code>```

From some other sources, I believe 'cryptid 0' show the binary is not encrypted.

Is this the right way to check if the binary is encrypted?

Is there a way to use FairPlay to encrypt iOS Enterprise Applications?

答:
Is this the right way to check if the binary is encrypted?

Yes:

```<code>$ otool -arch armv7 -l thebinary | grep crypt

$ otool -arch arm64 -l thebinary | grep crypt
</code>```

Is there a way to use FairPlay to encrypt iOS Enterprise Applications?

No (AppStore submissions only)

Body:
I am building an app that will be distributed with an enterprise license.  I am following these steps to build the application from xcode:

Choose Generic iOS Device.

Product -> Archive

Window -> Organizer -> Export -> Save for Enterprise Deployment

However when I generate an IPA in this fashion I don't think the binary is encrypted using apples fairplay.

I unzipped the IPA then ran this on the binary:

otool -arch armv7 -l thebinary | grep crypt

Which produced:

 cryptoff 15584
cryptsize 2364346
  cryptid 0

From some other sources, I believe 'cryptid 0' show the binary is not encrypted.

Is this the right way to check if the binary is encrypted?

Is there a way to use FairPlay to encrypt iOS Enterprise Applications?

Body:
Is this the right way to check if the binary is encrypted?

Yes:

$ otool -arch armv7 -l thebinary | grep crypt

$ otool -arch arm64 -l thebinary | grep crypt

Is there a way to use FairPlay to encrypt iOS Enterprise Applications?

No (AppStore submissions only)


问:
Calculating sum and count of detail records using Sequelize
Using Sequelize 4.1.0, I want to produce equivalent results to this PostgreSQL 9.6.3 query:

```<code>SELECT
  "user"._id,
  "user"."lastName",
  "user"."firstName",
  "user".email,
  COALESCE(purchase.purchases, 0::bigint) - COALESCE(attendance.attendances, 0::bigint) AS balance
FROM "Users" "user"
  LEFT OUTER JOIN
    (SELECT "Purchases"."UserId", SUM("Purchases".quantity) AS purchases
    FROM "Purchases"
    GROUP BY "Purchases"."UserId") purchase ON "user"._id = purchase."UserId"
  LEFT OUTER JOIN
    (SELECT "Attendances"."UserId", COUNT("Attendances"._id) AS attendances
    FROM "Attendances"
    GROUP BY "Attendances"."UserId") attendance ON "user"._id = attendance."UserId"
    WHERE "user"."firstName" ILIKE 'Smith%' OR "user"."lastName" ILIKE 'Smith%' OR "user"."email" ILIKE 'Smith%';
</code>```

My models (source: https://github.com/nstuyvesant/shy/blob/master/server/sqldb/index.js) are defined using Sequelize 4.0.0 like this...

```<code>import config from '../config/environment'; // source: https://github.com/nstuyvesant/shy/blob/master/server/config/environment/index.js
import Sequelize from 'sequelize';

let db = {
  Sequelize,
  sequelize: new Sequelize(config.sequelize.uri, config.sequelize.options)
};

// Imported model definitions
db.User = db.sequelize.import('../api/user/user.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/user.model.js
db.Purchase = db.sequelize.import('../api/user/purchase.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/purchase.model.js
db.Attendance = db.sequelize.import('../api/user/attendance.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/attendance.model.js

// Associations
db.Purchase.belongsTo(db.User);
db.Attendance.belongsTo(db.User);
db.User.hasMany(db.Purchase);
db.User.hasMany(db.Attendance);

module.exports = db;
</code>```

In my user API controller (source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/user.controller.js), I respond to GET /users with

```<code>import { User, Attendance, Purchase } from '../../sqldb';
import sequelize from 'sequelize';

export function index(req, res) {
  let startsWith = `${req.query.filter}%`;
  return User.findAll({
    where: {
      $or: [
        { firstName: { $iLike: startsWith } },
        { lastName: { $iLike: startsWith } },
        { email: { $iLike: startsWith } }
      ]
    },
    attributes: ['_id', 'lastName', 'firstName', 'email', [sequelize.literal('COALESCE(SUM(purchase.quantity), 0) - COALESCE(COUNT(attendance.id), 0)'), 'balance']],
    include: [{model: Purchase, attributes: ['quantity']}, {model: Attendance, attributes: ['_id']}],
    group: ['User._id', 'lastName', 'firstName', 'email', 'Purchases._id', 'Attendances._id']
  })
    .then(users => res.status(200).json(users))
    .catch(handleError(res));
}
</code>```

This is the query it produces:

```<code>SELECT
  "User"."_id", "User"."lastName", "User"."firstName", "User"."email", COALESCE(SUM("Purchases"."quantity"), 0) - COALESCE(COUNT("Attendances"."_id"), 0) AS "balance", "Purchases"."_id" AS "Purchases._id", "Purchases"."quantity" AS "Purchases.quantity", "Attendances"."_id" AS "Attendances._id"
FROM "Users" AS "User"
  LEFT OUTER JOIN "Purchases" AS "Purchases" ON "User"."_id" = "Purchases"."UserId"
  LEFT OUTER JOIN "Attendances" AS "Attendances" ON "User"."_id" = "Attendances"."UserId"
WHERE ("User"."firstName" ILIKE 'Stuyvesant%' OR "User"."lastName" ILIKE 'Stuyvesant%' OR "User"."email" ILIKE 'Stuyvesant%')
GROUP BY "User"."_id", "lastName", "firstName", "email", "Purchases"."_id", "Attendances"."_id";
</code>```

Any thoughts regarding what I might be doing wrong?

答:
There is the way to generate a query with difference construction but with the same result. Supposing there were defined all models with their associations, the query will looks like following</p>

```<code>User.findAll({
    attributes: ['id', 'lastName', 'firstName', 'email', [sequelize.literal('COALESCE(SUM(purchase.quantity), 0) - COALESCE(COUNT(attendance.id), 0)'), 'balance']],
    include: [{model: Purchase, attributes: 'quantity'}, {model: Attendance, attributes: 'id'}],
    group: ['id', 'lastName', 'firstName', 'email']
})
</code>```

Body:
Using Sequelize 4.1.0, I want to produce equivalent results to this PostgreSQL 9.6.3 query:

SELECT
  "user"._id,
  "user"."lastName",
  "user"."firstName",
  "user".email,
  COALESCE(purchase.purchases, 0::bigint) - COALESCE(attendance.attendances, 0::bigint) AS balance
FROM "Users" "user"
  LEFT OUTER JOIN
    (SELECT "Purchases"."UserId", SUM("Purchases".quantity) AS purchases
    FROM "Purchases"
    GROUP BY "Purchases"."UserId") purchase ON "user"._id = purchase."UserId"
  LEFT OUTER JOIN
    (SELECT "Attendances"."UserId", COUNT("Attendances"._id) AS attendances
    FROM "Attendances"
    GROUP BY "Attendances"."UserId") attendance ON "user"._id = attendance."UserId"
    WHERE "user"."firstName" ILIKE 'Smith%' OR "user"."lastName" ILIKE 'Smith%' OR "user"."email" ILIKE 'Smith%';

My models (source: https://github.com/nstuyvesant/shy/blob/master/server/sqldb/index.js) are defined using Sequelize 4.0.0 like this...

import config from '../config/environment'; // source: https://github.com/nstuyvesant/shy/blob/master/server/config/environment/index.js
import Sequelize from 'sequelize';

let db = {
  Sequelize,
  sequelize: new Sequelize(config.sequelize.uri, config.sequelize.options)
};

// Imported model definitions
db.User = db.sequelize.import('../api/user/user.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/user.model.js
db.Purchase = db.sequelize.import('../api/user/purchase.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/purchase.model.js
db.Attendance = db.sequelize.import('../api/user/attendance.model'); // source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/attendance.model.js

// Associations
db.Purchase.belongsTo(db.User);
db.Attendance.belongsTo(db.User);
db.User.hasMany(db.Purchase);
db.User.hasMany(db.Attendance);

module.exports = db;

In my user API controller (source: https://github.com/nstuyvesant/shy/blob/master/server/api/user/user.controller.js), I respond to GET /users with

import { User, Attendance, Purchase } from '../../sqldb';
import sequelize from 'sequelize';

export function index(req, res) {
  let startsWith = `${req.query.filter}%`;
  return User.findAll({
    where: {
      $or: [
        { firstName: { $iLike: startsWith } },
        { lastName: { $iLike: startsWith } },
        { email: { $iLike: startsWith } }
      ]
    },
    attributes: ['_id', 'lastName', 'firstName', 'email', [sequelize.literal('COALESCE(SUM(purchase.quantity), 0) - COALESCE(COUNT(attendance.id), 0)'), 'balance']],
    include: [{model: Purchase, attributes: ['quantity']}, {model: Attendance, attributes: ['_id']}],
    group: ['User._id', 'lastName', 'firstName', 'email', 'Purchases._id', 'Attendances._id']
  })
    .then(users => res.status(200).json(users))
    .catch(handleError(res));
}

This is the query it produces:

SELECT
  "User"."_id", "User"."lastName", "User"."firstName", "User"."email", COALESCE(SUM("Purchases"."quantity"), 0) - COALESCE(COUNT("Attendances"."_id"), 0) AS "balance", "Purchases"."_id" AS "Purchases._id", "Purchases"."quantity" AS "Purchases.quantity", "Attendances"."_id" AS "Attendances._id"
FROM "Users" AS "User"
  LEFT OUTER JOIN "Purchases" AS "Purchases" ON "User"."_id" = "Purchases"."UserId"
  LEFT OUTER JOIN "Attendances" AS "Attendances" ON "User"."_id" = "Attendances"."UserId"
WHERE ("User"."firstName" ILIKE 'Stuyvesant%' OR "User"."lastName" ILIKE 'Stuyvesant%' OR "User"."email" ILIKE 'Stuyvesant%')
GROUP BY "User"."_id", "lastName", "firstName", "email", "Purchases"."_id", "Attendances"."_id";

Any thoughts regarding what I might be doing wrong?

Body:
There is the way to generate a query with difference construction but with the same result. Supposing there were defined all models with their associations, the query will looks like following

User.findAll({
    attributes: ['id', 'lastName', 'firstName', 'email', [sequelize.literal('COALESCE(SUM(purchase.quantity), 0) - COALESCE(COUNT(attendance.id), 0)'), 'balance']],
    include: [{model: Purchase, attributes: 'quantity'}, {model: Attendance, attributes: 'id'}],
    group: ['id', 'lastName', 'firstName', 'email']
})


问:
How to change URL from this ?name=title to ../title
I have a script, which automatically add a URL for every row I insert into database with php.

This is, how it works:

```<code>if (isset($_GET['name']) )
  $title = $_GET['name'];

 <Code to select and echo data from database here>
</code>```

So, if I insert a row named "UserA", then a URL will be created like this:

```<code>example.com/users/?name=UserA
</code>```

I want to remove "?name="and make the URL like: example.com/users/UserA

答:
If you are familiar with . htaccess then it's good, else create a file in your project folder called .htaccess where htaccess is it's extension not a name:

Then put this into the .htaccess file:

```<code>RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^users/([0-9A-Za-z]+)/?$    users.php?name=$1    [NC,L]    # Handle product requests
</code>```

This will enable a url rewrite rule and redirect request from users/name to users.php file where you can manage all the request.

Now by going through the url as users/name you will be able to show data from database about that user within the file users.php:

Note: .htaccess file is an APACHE server configuration file.

Body:
I have a script, which automatically add a URL for every row I insert into database with php.

This is, how it works:

if (isset($_GET['name']) )
  $title = $_GET['name'];

So, if I insert a row named "UserA", then a URL will be created like this:

example.com/users/?name=UserA

I want to remove "?name="and make the URL like: example.com/users/UserA

Body:
If you are familiar with . htaccess then it's good, else create a file in your project folder called .htaccess where htaccess is it's extension not a name:

Then put this into the .htaccess file:

RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^users/([0-9A-Za-z]+)/?$    users.php?name=$1    [NC,L]    # Handle product requests

This will enable a url rewrite rule and redirect request from users/name to users.php file where you can manage all the request.

Now by going through the url as users/name you will be able to show data from database about that user within the file users.php:

Note: .htaccess file is an APACHE server configuration file.


问:
Webpack 2 livereload not working when moving input and output definiction from package.json to webpack.config.js
This is little bit strange. I know that webpack can be very picky about its configuration setup, but this is a very basic example:

package.json

```<code>{
  "name": "webpactest",
  "version": "1.0.0",
  "description": "",
  "main": "src/main.js",
  "scripts": {
    "server": "webpack-dev-server",
    "build": "rm -rf ./dist && webpack -d --watch",
    "build:prod": "rm -rf ./dist && webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-env": "^1.5.1",
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.0",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.5",
    "style-loader": "^0.18.2",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  }
}
</code>```

if I change the package.json "server" key to:

```<code>"server": "webpack-dev-server --entry ./src/app.js --output-filename ./dist/bundle.js",
</code>```

Live reload will work again.

I defined the "entry" and the "output" keys in webpack.config.js, so I suppose it should work... But "on file edit", no reload is triggered. What is wrong with my webpack.config.js configuration?

webpack.config.js

```<code>const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');

module.exports = {
  entry: [
    path.resolve(__dirname, "src/app.js"),
    path.resolve(__dirname, "src/sass/main.sass")
  ],
  module: {
    rules: [
      {
        test: /\.sass$/,
        include: [
          path.resolve(__dirname, "./src/sass")
        ],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: [
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                options: { sourceMap: true }
              }
            },
            'sass-loader'
          ]
        })
      },
      {
        // second rule
      }
    ]
  },
  output: {
    path: path.resolve(__dirname, 'dist/'),
    filename: 'bundle.js'
  },
  plugins: [
    new ExtractTextPlugin('bundle.css')
  ],
}
</code>```

答:
- FIXED -

This video helped me to fix it:
THE WEBPACK CORE CONCEPTS | Webpack 2 Basics Tutorial

I removed the empty object

```<code>  {
    // second rule
  }
</code>```

I moved the output key on the end of webpack.config.js.
In output I added publicPath (so that the server knows where to watch for other files). I also removed the slash (/) after dist in the path key.

```<code>  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist'
  }
</code>```

Now, live reload is working and my config file looks like this:

webpack.config.js

```<code>const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');

module.exports = {
  entry: [
    path.resolve(__dirname, "src/app.js"),
    path.resolve(__dirname, "src/sass/main.sass")
  ],
  module: {
    rules: [
      {
        test: /\.sass$/,
        include: [
          path.resolve(__dirname, "./src/sass")
        ],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: [
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                options: { sourceMap: true }
              }
            },
            'sass-loader'
          ]
        })
      },
    ]
  },
  plugins: [
    new ExtractTextPlugin('bundle.css')
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist'
  }
}
</code>```

Body:
This is little bit strange. I know that webpack can be very picky about its configuration setup, but this is a very basic example:

package.json

{
  "name": "webpactest",
  "version": "1.0.0",
  "description": "",
  "main": "src/main.js",
  "scripts": {
    "server": "webpack-dev-server",
    "build": "rm -rf ./dist && webpack -d --watch",
    "build:prod": "rm -rf ./dist && webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-env": "^1.5.1",
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.0",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.5",
    "style-loader": "^0.18.2",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  }
}

if I change the package.json "server" key to:

"server": "webpack-dev-server --entry ./src/app.js --output-filename ./dist/bundle.js",

Live reload will work again.

I defined the "entry" and the "output" keys in webpack.config.js, so I suppose it should work... But "on file edit", no reload is triggered. What is wrong with my webpack.config.js configuration?

webpack.config.js

const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');

module.exports = {
  entry: [
    path.resolve(__dirname, "src/app.js"),
    path.resolve(__dirname, "src/sass/main.sass")
  ],
  module: {
    rules: [
      {
        test: /\.sass$/,
        include: [
          path.resolve(__dirname, "./src/sass")
        ],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: [
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                options: { sourceMap: true }
              }
            },
            'sass-loader'
          ]
        })
      },
      {
        // second rule
      }
    ]
  },
  output: {
    path: path.resolve(__dirname, 'dist/'),
    filename: 'bundle.js'
  },
  plugins: [
    new ExtractTextPlugin('bundle.css')
  ],
}

Body:
- FIXED -

This video helped me to fix it:
THE WEBPACK CORE CONCEPTS | Webpack 2 Basics Tutorial

I removed the empty object

  {
    // second rule
  }

I moved the output key on the end of webpack.config.js.
In output I added publicPath (so that the server knows where to watch for other files). I also removed the slash (/) after dist in the path key.

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist'
  }

Now, live reload is working and my config file looks like this:

webpack.config.js

const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');

module.exports = {
  entry: [
    path.resolve(__dirname, "src/app.js"),
    path.resolve(__dirname, "src/sass/main.sass")
  ],
  module: {
    rules: [
      {
        test: /\.sass$/,
        include: [
          path.resolve(__dirname, "./src/sass")
        ],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: [
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                options: { sourceMap: true }
              }
            },
            'sass-loader'
          ]
        })
      },
    ]
  },
  plugins: [
    new ExtractTextPlugin('bundle.css')
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist'
  }
}


问:
"Requested URI is invalid" during upload with FtpWebRequest
I trying upload file to a directory on a FTP server. I used this method with FtpWebRequest.
I would like to upload one file to a home directory for this user, but I always get the following error message:

The requested URI is invalid for this FTP command.

What can be problem? I tried use passive mode off, but it still the same.

```<code>static void FtpUpload()
{

    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("pokus", "password");

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(path);
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

    response.Close();

}
</code>```

答:
If you want to upload something, you'll have to provide the FTPClient with a filename.</p>

```<code>FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45/myNewFile.dat");
</code>```

Body:
I trying upload file to a directory on a FTP server. I used this method with FtpWebRequest.
I would like to upload one file to a home directory for this user, but I always get the following error message:

The requested URI is invalid for this FTP command.

What can be problem? I tried use passive mode off, but it still the same.

static void FtpUpload()
{

    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("pokus", "password");

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(path);
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

    response.Close();

}

Body:
If you want to upload something, you'll have to provide the FTPClient with a filename.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45/myNewFile.dat");


问:
how to plot pie chart in R
I have following dataframe in R and want to make pie chart out of it

```<code>berth_day count
Friday    74
Monday    95
Saturday  126
Sunday    114
Thursday  62
Tuesday   85
</code>```

I am doing following in R

```<code>ggplot(aes(x=berth_day, y=count))+
geom_bar(width =1)
+ coord_polar(theta = "y")
</code>```

But,it gives me following error

```<code>> ggplot(aes(x=berth_day, y=count))+
+   geom_bar(width =1)
Error: ggplot2 doesn't know how to deal with data of class uneval
>   + coord_polar(theta = "y")
Error in +coord_polar(theta = "y") : invalid argument to unary operator
</code>```

How can I do it in R ?

答:
A proper pie is contructed this way:

library(ggplot2)
ggplot(df1, aes(x = 1, y = count, fill = berth_day))+
    geom_col(position = 'stack',
             show.legend = F) +
    geom_text(aes(label = paste(berth_day, ': ', count)),
               position = position_stack(vjust = .5)) +
    coord_polar(theta = "y") +
    theme_void()
```

<p><img src="https://i.imgur.com/d4b1uJr.png" alt=""></p>

<p>data:</p>

<pre class="lang-r prettyprint-override"><code>df1 <- read.table(text = 'berth_day count
Friday    74
                  Monday    95
                  Saturday  126
                  Sunday    114
                  Thursday  62
                  Tuesday   85', h = T)
</code>```

Title: how to plot pie chart in R

Body:
I have following dataframe in R and want to make pie chart out of it

berth_day count
Friday    74
Monday    95
Saturday  126
Sunday    114
Thursday  62
Tuesday   85

I am doing following in R

ggplot(aes(x=berth_day, y=count))+
geom_bar(width =1)
+ coord_polar(theta = "y")

But,it gives me following error

> ggplot(aes(x=berth_day, y=count))+
+   geom_bar(width =1)
Error: ggplot2 doesn't know how to deal with data of class uneval
>   + coord_polar(theta = "y")
Error in +coord_polar(theta = "y") : invalid argument to unary operator

How can I do it in R ?

Body:
A proper pie is contructed this way:

library(ggplot2)
ggplot(df1, aes(x = 1, y = count, fill = berth_day))+
    geom_col(position = 'stack',
             show.legend = F) +
    geom_text(aes(label = paste(berth_day, ': ', count)),
               position = position_stack(vjust = .5)) +
    coord_polar(theta = "y") +
    theme_void()

data:

df1 <- read.table(text = 'berth_day count
Friday    74
                  Monday    95
                  Saturday  126
                  Sunday    114
                  Thursday  62
                  Tuesday   85', h = T)


问:
How to get the first not null value from a column of values in Big Query?
I am trying to extract the first not null value from a column of values based on timestamp. Can somebody share your thoughts on this. Thank you.

What have i tried so far?

```<code>FIRST_VALUE( column ) OVER ( PARTITION BY id ORDER BY timestamp)
</code>```

Input :-

```<code>id,column,timestamp
1,NULL,10:30 am
1,NULL,10:31 am
1,'xyz',10:32 am
1,'def',10:33 am
2,NULL,11:30 am
2,'abc',11:31 am

Output(expected) :-
1,'xyz',10:30 am
1,'xyz',10:31 am
1,'xyz',10:32 am
1,'xyz',10:33 am
2,'abc',11:30 am
2,'abc',11:31 am
</code>```

答:
SELECT id,

    (SELECT top(1) column FROM test1 where id=1 and column is not null order by autoID desc) as name
    ,timestamp
    FROM yourTable

Output :-
1,'xyz',10:30 am
1,'xyz',10:31 am
1,'xyz',10:32 am
1,'xyz',10:33 am
2,'abc',11:30 am
2,'abc',11:31 am

Body:
I am trying to extract the first not null value from a column of values based on timestamp. Can somebody share your thoughts on this. Thank you.

What have i tried so far?

FIRST_VALUE( column ) OVER ( PARTITION BY id ORDER BY timestamp)

Input :-

id,column,timestamp
1,NULL,10:30 am
1,NULL,10:31 am
1,'xyz',10:32 am
1,'def',10:33 am
2,NULL,11:30 am
2,'abc',11:31 am

Output(expected) :-
1,'xyz',10:30 am
1,'xyz',10:31 am
1,'xyz',10:32 am
1,'xyz',10:33 am
2,'abc',11:30 am
2,'abc',11:31 am


问:
How do I enable help option in below script?
My program takes command line arguments.

```<code>test.pl --help
</code>```

I want to enable a "help" option in the code. How can I print usage in the code?

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Cwd 'chdir';
use Getopt::Long;
my ($application,$version, $location,$artifactid,$pomversion,$groupid);
GetOptions('application=s' => \$application,

                   'version=s' => \$version,

        'location=s' => \$location,

        'artifactid=s' => \$artifactid,

        'pomversion=s' => \$pomversion,

        'groupid=s' => \$groupid)
 or die "Usage od the script: $!\n";

print "$application, $version, $location, $artifactid, $versionnumber, $groupid \n";

if($application eq 'abc')

{      chdir("/var/ccabc/dst_${application}_${version}/abc/${location}") or die "Cannot Change Directory: $!\n";

print $ENV{PWD};

do_compile();

}
</code>```

I have tried my best..

答:
Did you read the documentation for Getopt::Std? Do you know how the getopts() function works?

The first argument to getopts() is string defining the options that you want it to parse. So you need to add 'h' to that string.

```<code>getopts('a:v:l:h', \%opts);
</code>```

As you'll see in the documentation, the ':' following the existing options, indicates that they need a value following them on the command line (for example -a foobar). The -h option doesn't need that, so we don't have a ':'.

The second argument to getopts() is a reference to a hash which will be populated with your options. As your new -h option has no value, the 'h' key in the hash will be given the value 1 if the option is given on the command line. So all you need to do is to check that value and take appropriate action.

```<code>if ($opts{h}) {
  # display your help message
  exit;
}
</code>```

But, really, all of this is in the documentation. It would be helpful for us to know what you found difficult in the documentation so that we can improve it.

Body:
My program takes command line arguments.

test.pl --help

I want to enable a "help" option in the code. How can I print usage in the code?

#!/usr/bin/perl
use strict;
use warnings;
use Cwd 'chdir';
use Getopt::Long;
my ($application,$version, $location,$artifactid,$pomversion,$groupid);
GetOptions('application=s' => \$application,

                   'version=s' => \$version,

        'location=s' => \$location,

        'artifactid=s' => \$artifactid,

        'pomversion=s' => \$pomversion,

        'groupid=s' => \$groupid)
 or die "Usage od the script: $!\n";

print "$application, $version, $location, $artifactid, $versionnumber, $groupid \n";

if($application eq 'abc')

{      chdir("/var/ccabc/dst_${application}_${version}/abc/${location}") or die "Cannot Change Directory: $!\n";

print $ENV{PWD};

do_compile();

}

I have tried my best..

Body:
Did you read the documentation for Getopt::Std? Do you know how the getopts() function works?

The first argument to getopts() is string defining the options that you want it to parse. So you need to add 'h' to that string.

getopts('a:v:l:h', \%opts);

As you'll see in the documentation, the ':' following the existing options, indicates that they need a value following them on the command line (for example -a foobar). The -h option doesn't need that, so we don't have a ':'.

The second argument to getopts() is a reference to a hash which will be populated with your options. As your new -h option has no value, the 'h' key in the hash will be given the value 1 if the option is given on the command line. So all you need to do is to check that value and take appropriate action.

if ($opts{h}) {
  # display your help message
  exit;
}

But, really, all of this is in the documentation. It would be helpful for us to know what you found difficult in the documentation so that we can improve it.


问:
Comparing output of two versions of a stored procedure using a table
I have two versions of a stored proc and want to make sure that their outputs are exactly the same. My unit tests and functional tests do verify that the two versions are the same. However before using the newer version of the proc on a live environment I want to make sure that they match.

I am trying to do the following on a copy of the live DB:

Start a transaction.

Call stored procedure sproc_v1  (internally the proc modifies table T1).

Select * into T1_v1 from T1 (with a condition to filter out those rows affected by the sproc_v1)

Rollback the transaction (so that I have same initial conditions for running V2

Call stored procedure sproc_v2

Select * into T1_v2 from T1

Well obviously after step 3 - the values in T1_v1 are also rolled back. May be I can dump the data into a file and compare the files. Was wondering if there is another way to do this kind of matching.

答: I always use excel for this. Paste the results of the first stored procedure in sheet 1, the results of the second stored procedure in the second sheet and compare the values in the third sheet.</p>


问:
CMS projects to learn from?
There have been quite a few questions about CMS systems but I wonder if there are any good open-source versions available that support ASP.NET MVC (preferably 2.0) and work well with SQL Server?
I'm not looking for a CMS system to use, although that will probably happen too. I'm looking for a CMS system to learn from! So basically, it should follow the KISS principle.
Yeah, I know about DotNetNuke. It looks okay but it feels like overkill to me. There should be alternatives, right?

And no, I'm not a beginner! My web development skills go back to the time when Internet Explorer was still displaying static pages on a Windows 3.11 system when RAM was still measured in kilobytes and with CompuServe as provider over a 33k6 model phone line. But it never hurts to learn from existing code.

答:
as far as whats readily available DNN is the best to go with and although it may seem overkill after a few hours of stepping through code you will see the patterns used and understand the DNN system is not so large as it first seems. Also the core DNN team has their code reviewed and gets much input from Microsoft corp when they want to showcase new features of the .net framework.

other than DNN there is a commercial CMS built in .net called Ektron (AKA CMS400). what a terrible system. i had the misfortune of having to use this at one job and on top of being slow it is terribly buggy as well. it has some good features but i wouldn't recommend learning from it cause the results are lack-luster at best.

good luck

Title: CMS projects to learn from?


问:
How to design complex multi component form in react redux
I have form. This form has lot of input elements.
User interaction with form: User first selects a product from multiselect (can select up to 32 products). Based on the selected product we show other form elements, which user has to fill.
Input fields for a particular product can be categorized in mainly 3 categories.

Company related fields: (Company selection component) who is the buyer? etc.

Other fields: (Radio buttons, checkboxes, text, date etc..) Does buyer has sufficient money to buy? Etc.

Special other fields: These are same as other fields but their answer can add more products in the form, which in-term will add more input fields. E.g. if answer of Does buyer has sufficient money to buy is NO. Then you might ask another question such as, if buyer doesn’t have money then do you think we should include product 2 as well which is for raising money for buyer to buy this commodity.

After that user fills some common fields, these are not related to a particular product.
As per the mocks given, entire form is divided in multiple accordions. See attached screenshots.
Notes:

Model to support this form looks like this: (One model for entire form)

Form :
{
Buyers:
[
{
Name : "Abc",
Id : 1234
},
],
Sellers:
[
{
Name : "Abc",
Id : 1234
},
],
Money: "",
Question1: "",
Question2 : "",
}

Common company related questions should be grouped together. E.g. say product 1 has a question called “Who is the buyer” and product 2 also has a question called “Who is the buyer”, then if user selects both the products, question with name Who is the buyer should not be shown more than once.

Form needs to be validated for validations such as “required”, “min-length” and any other custom validation.

Data model json (point # 1) will be saved when user clicks the submit button on the bottom of the page.

My Questions:

Scalable: How to architect the form so that adding/updating more
form sections is not a pain later. This also needs to take care of
the custom event handling for form elements. (Adding another product
based on the answer of a question is an example of that)

Performance: How to design this form so that it loads fast, even if
user adds 5+ products.

Maintainable: Another most important aspect is readability; it shouldn’t
become one giant blob of elements which a new developer in the team is
scared of touching.

High level design/architecture will be really helpful.

Tech stack I am thinking of using:
React and Redux

答:
You can use React + Redux + Webpack

Videos : Click here to watch React + Redux + Webpack videos

You have to create Model (data) and Component visibility flag (componentToLoad) inside store like:

```<code>store={
    data:{
        Buyer:'xxx',
        Seller:'xxx',
        etc,
    },
    componentToLoad:{
        LoadBuyerComponent:true,
        LoadSellerComponent:false,
        etc,
    }
}
</code>```

Create different component for Buyers,Sellers,etc

```<code>class Buyer extends Component {
    render() {
        return (
          //HTML Code
          <div>
          </div>
     )
}

class Seller extends Component {
    render() {
        return (
          //HTML Code
          <div>
          </div>
     )
}
</code>```

You can load component dynamically based on store

```<code>class MainForm extends Component {
    render() {
        var components = [];
        if(this.props.componentToLoad.LoadBuyerComponent == true)
            components.push(<Buyer/>)
        if(this.props.componentToLoad.LoadSellerComponent == true)
            components.push(<Seller/>)
        return (
          <div>
              {components}
          </div>
     )
}
</code>```

Body:
You can use React + Redux + Webpack

Videos : Click here to watch React + Redux + Webpack videos

You have to create Model (data) and Component visibility flag (componentToLoad) inside store like:

store={
    data:{
        Buyer:'xxx',
        Seller:'xxx',
        etc,
    },
    componentToLoad:{
        LoadBuyerComponent:true,
        LoadSellerComponent:false,
        etc,
    }
}

Create different component for Buyers,Sellers,etc

class Buyer extends Component {
    render() {
        return (
          //HTML Code
          <div>
          </div>
     )
}

class Seller extends Component {
    render() {
        return (
          //HTML Code
          <div>
          </div>
     )
}

You can load component dynamically based on store

class MainForm extends Component {
    render() {
        var components = [];
        if(this.props.componentToLoad.LoadBuyerComponent == true)
            components.push(<Buyer/>)
        if(this.props.componentToLoad.LoadSellerComponent == true)
            components.push(<Seller/>)
        return (
          <div>
              {components}
          </div>
     )
}


问:
Using feature, story and task branches?
We are using Visual Studio Team Services (VSTS) which have epics, features, stories and down to tasks. We will also follow git dmz flow in which development happens in feature branches. We want to use VSTS structure but not breaking the principles and benefits of git dmz flow.

I was thinking of having a feature branch that will be branched out to story branch and story branch that will be branch out to task branch (where the actual dev work happens). Is this not add too much overhead for the dev team? Can automation help in this?

I am considering to use story branches like feature branches (in git dmz flow context) wherein, when a story is done, you can make a PR going to dmz branch (but it kind of destroys the structure in VSTS/agile structure?)

I believed that tasks can be finished not more than a day so task branches should be short-lived. I also assume that features take days to complete.

答:
It seems you have bundled the work items and branches together.

In Git DMZ Flow, it talks about how to use different branches to build/release your projects efficiently. And this article has no business with WIT (work item type).

On the other hand, branches and work items usually is not one-to-one correspondence but one-to-many relationship. That means what you prepare to develop on feature branch can be listed by detail operations in work items.

For example, there has a feature branch which need to export reports for a company, let call the branch name is feature/reporting here. Now you can list detail works for this feature in work items as:

```<code>  |___ daily report                (User story)
  |         |___ template design   (task)
  |         |___ function develop  (task)
  |         |___ QA test           (task)
  |___ monthly report              (User story)
  |         |___ …                 (task)
  |___ yearly report               (User story)
            |___ …                 (task)
</code>```

Title: Using feature, story and task branches?

Body:
It seems you have bundled the work items and branches together.

In Git DMZ Flow, it talks about how to use different branches to build/release your projects efficiently. And this article has no business with WIT (work item type).

On the other hand, branches and work items usually is not one-to-one correspondence but one-to-many relationship. That means what you prepare to develop on feature branch can be listed by detail operations in work items.

For example, there has a feature branch which need to export reports for a company, let call the branch name is feature/reporting here. Now you can list detail works for this feature in work items as:

  |___ daily report                (User story)
  |         |___ template design   (task)
  |         |___ function develop  (task)
  |         |___ QA test           (task)
  |___ monthly report              (User story)
  |         |___ …                 (task)
  |___ yearly report               (User story)
            |___ …                 (task)


答:
How big is your result set?

One approach might be to declare xml variables

```<code>DECLARE @xml1 XML, @xml2 XML;
</code>```

... and use

```<code>SET @xml1=(SELECT ... FOR XML RAW) --without the "INTO SomeTable"! Same with `@xml2`
</code>```

At the end you can use

```<code>SELECT CASE WHEN CAST(@xml1 AS NVARCHAR(MAX))=CAST(@xml2 AS NVARCHAR(MAX)) THEN ...`
</code>```

Make sure, that there are no timestamps or other variable content, which would disturb of course...

UPDATE

You might use a declared table variable, which lives as long as your job lives and is not affected by the rollback:

Instead of your SELECT * INTO SomeTable you use INSERT INTO @tableVariable (col1, col2, ...) SELECT col1, col2, ... FROM ....

Just use the existing declaration of your table to create the table variable. No need to type in all columns manually...

Title: Comparing output of two versions of a stored procedure using a table

Body:
I have two versions of a stored proc and want to make sure that their outputs are exactly the same. My unit tests and functional tests do verify that the two versions are the same. However before using the newer version of the proc on a live environment I want to make sure that they match.

I am trying to do the following on a copy of the live DB:

Start a transaction.

Call stored procedure sproc_v1  (internally the proc modifies table T1).

Select * into T1_v1 from T1 (with a condition to filter out those rows affected by the sproc_v1)

Rollback the transaction (so that I have same initial conditions for running V2

Call stored procedure sproc_v2

Select * into T1_v2 from T1

Well obviously after step 3 - the values in T1_v1 are also rolled back. May be I can dump the data into a file and compare the files. Was wondering if there is another way to do this kind of matching.

Body:
How big is your result set?

One approach might be to declare xml variables

DECLARE @xml1 XML, @xml2 XML;

... and use

SET @xml1=(SELECT ... FOR XML RAW) --without the "INTO SomeTable"! Same with `@xml2`

At the end you can use

SELECT CASE WHEN CAST(@xml1 AS NVARCHAR(MAX))=CAST(@xml2 AS NVARCHAR(MAX)) THEN ...`

Make sure, that there are no timestamps or other variable content, which would disturb of course...

UPDATE

You might use a declared table variable, which lives as long as your job lives and is not affected by the rollback:

Instead of your SELECT * INTO SomeTable you use INSERT INTO @tableVariable (col1, col2, ...) SELECT col1, col2, ... FROM ....

Just use the existing declaration of your table to create the table variable. No need to type in all columns manually...


问:
Run Jenkins build for whichever branch was checked into on Gitlab
I recently made the transition from Subversion to Git for all my repos at work. However, with svn we had commit hooks in place so that our Jenkins job would run for whichever branch was checked into. Now, I'm trying to set this up using Gitlab and there appears to only be one place to add a web hook. It looks like any time something is checked into ANY branch, the web hook will run. Meaning if I have a branch_A associated with jenkins_job_A, something could be checked into branch_B and the commit hook for jenkins_job_A will still run. Is there a branch by branch way to configure these web hooks? Or is there some kind of script I can check into each branch that will act as a commit hook? Or (my fear) is this feature not supported in Gitlab?</p>

答:
I guess you set up GitLab to do a post commit request to http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>? In theory this should trigger the polling on all jobs that are configured with that URL, and in the polling step the jobs should decide whether they should build or not. In practice this will unfortunately cause all jobs to fire.

We worked around this issue by moving the Job configuration into a Jenkinsfile and then use a Multibranch Pipeline.

As an alternative you could also install the GitLab plugin for Jenkins and use the Jenkins integration in GitLab. This will allow you to trigger the correct jobs when commits are pushed on a branch. The downside is that it requires a per-job configuration.


问:
Insert many rows in a table with multiple columns having data in sequence but the columns are not INT
I want to insert many rows in a table with multiple columns having data in sequence but the columns are not INT. I need to insert data into an existing table as shown below. Please help.

Ex.

```<code>ID    ItemID    Value    Description    Active
1      2         A1       A101           1
2      2         A2       A102           1
3      2         A3       A103           1
....
</code>```

答:
You need to cast to int

```<code>SELECT CAST(varchar_column_name AS INT) FROM Table
</code>```

Body:
I want to insert many rows in a table with multiple columns having data in sequence but the columns are not INT. I need to insert data into an existing table as shown below. Please help.

Ex.

ID    ItemID    Value    Description    Active
1      2         A1       A101           1
2      2         A2       A102           1
3      2         A3       A103           1
....

Body:
You need to cast to int

SELECT CAST(varchar_column_name AS INT) FROM Table


问:
How to create a duplex connection using TcpListener and TcpClient?
I have a situation where I need to send and receive information parallelly.

My protocol can define a read port and a write port.

I currently have the following code:

```<code>public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}
</code>```

How can I create another listener from the TcpClient I am passing?

答:
A TcpClient object wraps a NetworkStream object.  You use the GetStream() method of TcpClient to access the NetworkStream object, which is then used to read data from and write data to the network.  The MSDN article for NetworkStream says the following:

Read and write operations can be
  performed simultaneously on an
  instance of the NetworkStream class
  without the need for synchronization.
  As long as there is one unique thread
  for the write operations and one
  unique thread for the read operations,
  there will be no cross-interference
  between read and write threads and no
  synchronization is required.

Use the TcpListener object to listen for incoming connections.  Use the TcpClient object returned from the call to AcceptTcpClient() to communicate (read and write) with the remote endpoint.

Body:
I have a situation where I need to send and receive information parallelly.

My protocol can define a read port and a write port.

I currently have the following code:

public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}

How can I create another listener from the TcpClient I am passing?