问:
Comparing two arrays inside ng-if
I have array inside a class, and I have to compare if the arrays are same in 2 different objects of the same class. Currently, I am doing it like this,

```<code><div class="col-md-4">{{ctrl.Obj1.arr1}}
  <span ng-if="ctrl.Obj2 != null && ctrl.Obj1.arr1 != ctrl.Obj2.arr1"
      class="glyphicon glyphicon-alert" style="margin-left: 6px;
     font-size: small; color: palevioletred">
  </span>
</div>
</code>```

But this is an incorrect way of comparison since it yields different values. My array is of the form: ["string1","string2","string3"]

What's the correct way to do it?

Edit: My question is different because I am asking about how to accomplish this in AngularJS.

答:
Instead of doing this comparision in template you should have a function that would return boolean value after comparing and then bind that to the template

```<code>ng-if="compareArrays()"
</code>```

and in controller

```<code>$scope.compareArrays = function(){
var result = $scope.array1.length == $scope.array2.length && $scope.array1.every(function(element, index) {
    return element === $scope.array2[index];
});
 return result ;
}
</code>```

Title: Comparing two arrays inside ng-if

Body:
I have array inside a class, and I have to compare if the arrays are same in 2 different objects of the same class. Currently, I am doing it like this,

{{ctrl.Obj1.arr1}}

But this is an incorrect way of comparison since it yields different values. My array is of the form: ["string1","string2","string3"]

What's the correct way to do it?

Edit: My question is different because I am asking about how to accomplish this in AngularJS.

Body:
Instead of doing this comparision in template you should have a function that would return boolean value after comparing and then bind that to the template

ng-if="compareArrays()"

and in controller

$scope.compareArrays = function(){
var result = $scope.array1.length == $scope.array2.length && $scope.array1.every(function(element, index) {
    return element === $scope.array2[index];
});
 return result ;
}


来源: stackexchange

问:
How to get all records from one table between dates of column in another table
I'm using sql server, I have a queues table has a column called process_date, and a users table has a column called process_date, there is no relation between the two tables. I want to get all users that has been processed with one queue depending on process_date (I have the queue_id and I want to return all users that have been processed with that queue)
How can I write a query to do so?

update: the process_date is date time so it's not a match for the queue and the users, that's why I needed to get the process date for the previous queue and then the current queue and then get the users that were processed in that date range

答:
Try this

```<code>SELECT
    *
    FROM Users
        WHERE EXISTS
        (
            SELECT
                1
                FROM [Queue]
                    WHERE [Queue].process_date = Users.process_date
                    AND [Queue].QueueId = 1
        )
</code>```

this will return all users processed for queue_id 1.

Note:
it is not recommended to join tables based on some dates to retrieve the records. so if possible, you should add a queue id to the users' table and create a foreign key constraint with the queue table. then update the queue id for each user because time ca  variation  in milliseconds can also leade to miss match in the above

ContentLicense: CC BY-SA 3.0

Body:
Try this

SELECT
    *
    FROM Users
        WHERE EXISTS
        (
            SELECT
                1
                FROM [Queue]
                    WHERE [Queue].process_date = Users.process_date
                    AND [Queue].QueueId = 1
        )

this will return all users processed for queue_id 1.

Note:
it is not recommended to join tables based on some dates to retrieve the records. so if possible, you should add a queue id to the users' table and create a foreign key constraint with the queue table. then update the queue id for each user because time ca  variation  in milliseconds can also leade to miss match in the above


问:
"Environment Variables" view for jenkins pipeline job
For freestyle job I used to have "environment variable" view that allowed me to view all the variables that were available during runtime of the build.

What is the equivalent for pipeline job?

答:
Add this code in your pipeline to view variables at runtime

For linux

```<code> sh 'env > env.txt'
 for (String i : readFile('env.txt').split("\r?\n")) {
     println i
 }
</code>```

For windows

```<code>bat 'set > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
    println i
}
</code>```

Body:
Add this code in your pipeline to view variables at runtime

For linux

 sh 'env > env.txt'
 for (String i : readFile('env.txt').split("\r?\n")) {
     println i
 }

For windows

bat 'set > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
    println i
}


问:
Golang Channel Won't Receive Messages
I try to explore go channel, i create channel buffer max 10, with gomaxprocess is 2, but i wonder why this code won't receive message</p>

```<code>runtime.GOMAXPROCS(2)
messages := make(chan int, 9)

go func() {
    for {
        i := <-messages
        fmt.Println("Receive data:", i)
    }
}()
for i := 0; i <= 9; i++ {
    fmt.Println("Send data ", i)
    messages <- i
}
</code>```

答:
Your case works like this, though it may appear to work certain times, but it's not guaranteed to always.

Just to add some context, in an unbuffered channel, the sending go routine is blocked as it tries to send a value and a receive is guaranteed to occur before the sending go routine is awakened (in this case the main), so it may seem like a viable option in such cases. But the sending go routine may still exit before the print statement in the receiving go routine is executed. So basically you need to use a synchronization mechanism such that the sending go routine exits only after the work in the receiver is completed.

Here's how you can use a synchronization mechanism, have annotated it so that you can make better sense out of it. This will work for both buffered and unbuffered channels. Another option is to have the receive in the main thread itself so that it doesn't exit before receive processing is done, this way you won't need a separate synchronization mechanism. Hope this helps.

Title: Golang Channel Won't Receive Messages

Body:
I try to explore go channel, i create channel buffer max 10, with gomaxprocess is 2, but i wonder why this code won't receive message

runtime.GOMAXPROCS(2)
messages := make(chan int, 9)

go func() {
    for {
        i := <-messages
        fmt.Println("Receive data:", i)
    }
}()
for i := 0; i <= 9; i++ {
    fmt.Println("Send data ", i)
    messages <- i
}


问:
IUserType Corresponding to Int64 With ODP.net
We have a custom type that mostly corresponds to System.Int64 that's used for our system identifiers (it provides a few extra constraints on what the underlying long value can be).

We've also got an IUserType defined to allow us to map properties of this type with NHibernate, but when running against an oracle database we run into what it seems is known as the "Int/Decimal Problem"

The relevant parts of the user type (get / set) are here:

```<code>public object NullSafeGet(IDataReader rs, string[] names, object owner) {
    var longValue = Convert.ToInt64(NHibernateUtil.Int64.NullSafeGet(rs, names[0]));
    return new Identifier(longValue);
}

public void NullSafeSet(IDbCommand cmd, object value, int index) {
    if (value == null || ((Identifier)value).IsNew) {
        NHibernateUtil.Int64.NullSafeSet(cmd, null, index);
        return;
    }
    NHibernateUtil.Int64.NullSafeSet(cmd, ((Identifier)value).Value, index);
}
</code>```

We're currently getting invalid cast exceptions from the ISession's SaveOrUpdate method when trying to save anything that contains an identifier property.

Is there a good (or even an alright) way to handle this issue in a way that works both for oracle and SQL server, or will we need to create two different UserType implementations?

答:
After some more investigation it appears the problem may be with the sequence-identity generation strategy.  It attempts to use a query like this:

```<code>INSERT INTO my_entity (id, name)
VALUES (hibernate_sequence.nextval, :p0)
returning id into :nhIdOutParam
</code>```

To make a sequence based identity work similarly to the way it would on SQL server (allowing an insert and ID retrieval with a single query).  I'm guessing that the out param comes through as a decimal and that is where I'm having problems.

Switching to the "native" generation strategy it is working, but I'd still like to hear any other insights on this.

ContentLicense: CC BY-SA 2.5

Body:
We have a custom type that mostly corresponds to System.Int64 that's used for our system identifiers (it provides a few extra constraints on what the underlying long value can be).

We've also got an IUserType defined to allow us to map properties of this type with NHibernate, but when running against an oracle database we run into what it seems is known as the "Int/Decimal Problem"

The relevant parts of the user type (get / set) are here:

public object NullSafeGet(IDataReader rs, string[] names, object owner) {
    var longValue = Convert.ToInt64(NHibernateUtil.Int64.NullSafeGet(rs, names[0]));
    return new Identifier(longValue);
}

public void NullSafeSet(IDbCommand cmd, object value, int index) {
    if (value == null || ((Identifier)value).IsNew) {
        NHibernateUtil.Int64.NullSafeSet(cmd, null, index);
        return;
    }
    NHibernateUtil.Int64.NullSafeSet(cmd, ((Identifier)value).Value, index);
}

We're currently getting invalid cast exceptions from the ISession's SaveOrUpdate method when trying to save anything that contains an identifier property.

Is there a good (or even an alright) way to handle this issue in a way that works both for oracle and SQL server, or will we need to create two different UserType implementations?

Body:
After some more investigation it appears the problem may be with the sequence-identity generation strategy.  It attempts to use a query like this:

INSERT INTO my_entity (id, name)
VALUES (hibernate_sequence.nextval, :p0)
returning id into :nhIdOutParam

To make a sequence based identity work similarly to the way it would on SQL server (allowing an insert and ID retrieval with a single query).  I'm guessing that the out param comes through as a decimal and that is where I'm having problems.

Switching to the "native" generation strategy it is working, but I'd still like to hear any other insights on this.


问:
Magento custom shipping cost
Is there a way to add a custom shipping rate for to basket (order) in magento not from admin but in programing.

What I need is, I will have a field with each product "shipping_cost" , now suppose customer added 3 products to basket, now the shipping cost of the order will be the highest of shipping_costs of the products. For example, the 3 products have shipping_costs like $10, $20 and $30 , so the shipping_cost for basket will be $30.

答:
Yes, in your condition you need to get maximum shipping rate and assign that value to $shippingprice. You can add your custom shipping price for an order in magento using given code:

```<code>$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');

$shippingprice = 30;

$order->setShippingAmount($shippingprice);

$order->setBaseShippingAmount($shippingprice);
$order->setGrandTotal($order->getGrandTotal() + $shippingprice); //adding shipping price to grand total

$order->save();
</code>```

It will update your shipping price and grand total. I guess it will be helpful to you.

ContentLicense: CC BY-SA 4.0

Title: Magento custom shipping cost

Body:
Yes, in your condition you need to get maximum shipping rate and assign that value to $shippingprice. You can add your custom shipping price for an order in magento using given code:

$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');

$shippingprice = 30;

$order->setShippingAmount($shippingprice);

$order->setBaseShippingAmount($shippingprice);
$order->setGrandTotal($order->getGrandTotal() + $shippingprice); //adding shipping price to grand total

$order->save();

It will update your shipping price and grand total. I guess it will be helpful to you.


问:
int.Parse is not working with string value (System.FormatException: Input string was not in a correct format )
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

```<code>private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}
</code>```

答:
```<code>int femaleWeight;

if (!int.TryParse(Console.ReadLine(), out femaleWeight)) {
   Console.WriteLine("Please enter your weight in US pounds")
}
else if (...)
</code>```

Body:
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}


问:
Platform Builder and C#
Platform Builder is a tool for building a Windows CE Operating system on your computer and then loading it on a Windows CE device.

All this is done through Platform Builder.  And I do it all through the Microsoft Visual Stuido Development Environment (IDE).

I want to automate the process of using the Platform Builder.  So far, I only know how to use the Platform Builder through the IDE.  I want to use the Platform Builder through another program written in C#.

Another approach to this goal is to learn how to use Platform Builder from the command line.  If it can be done by the command line, then it could also be done through a C# program.  I have seen some links here and there that say that you can do a Platform Builder build from the command line, but so far, they are not so good.

Any tips?

This link:
http://msdn.microsoft.com/en-us/library/ms924536.aspx
talks about "How to Use the Command Line to Create, Customize, and Build a Run-Time Image"
but it has links about Creating ai OS Design ( http://msdn.microsoft.com/en-us/library/aa448498.aspx ) that requires using the IDE.

It would be great to find a good link about this topic.  If I can do what I need to do using the IDE, I should be able to do what I need to do from the command line.  If I can do what I need to do from the command line, I should be able to do what I need to do from a C# program.  That is my goal.

答:
This link mentions Windows CE Build Environment tool (Wince.bat) that sets up the Windows CE build environment.
http://msdn.microsoft.com/en-us/library/ms938334.aspx

And this link describes how to use the Windows CD Build Environment Tool:
http://msdn.microsoft.com/en-us/library/ms930978.aspx

Basically, when you use wince.bat, you pass it three arguments: CPU; PROJECT, and PLATFORM.
I have figured out what to input for the CPU and the PLATFORM.  But what to use for the "PROJECT" has me a little puzzled.  It seems that for this argument, you can give it any project name you want.  This does not work.  So I have tried the names of a few existing project folders.  This does not work either.  So now I am thinking that I am supposed to define a project name prior to making the wince.bat call.  How do I do this?

OwnerDisplayName: xarzu

Title: Platform Builder and C#


问:
T-SQL CASE Clause: How to specify WHEN NULL
I wrote a T-SQL Statement similar like this (the original one looks different but I want to give an easy example here):

```<code>SELECT first_name +
    CASE last_name WHEN null THEN 'Max' ELSE 'Peter' END AS Name
FROM dbo.person
</code>```

This Statement does not have any syntax errors but the case-clause always chooses the ELSE-part - also if the last_name is null. But Why?

What I want to do is to unite first_name and last_name, but if last_name is null the whole name becomes null:

```<code>SELECT first_name +
   CASE last_name WHEN null THEN '' ELSE ' ' + last_name END AS Name
FROM dbo.person
</code>```

Do you know where the problem is?

答:
Use the CONCAT function available in SQL Server 2012 onward.</p>

```<code>SELECT CONCAT([FirstName], ' , ' , [LastName]) FROM YOURTABLE
</code>```

Body:
I wrote a T-SQL Statement similar like this (the original one looks different but I want to give an easy example here):

SELECT first_name +
    CASE last_name WHEN null THEN 'Max' ELSE 'Peter' END AS Name
FROM dbo.person

This Statement does not have any syntax errors but the case-clause always chooses the ELSE-part - also if the last_name is null. But Why?

What I want to do is to unite first_name and last_name, but if last_name is null the whole name becomes null:

SELECT first_name +
   CASE last_name WHEN null THEN '' ELSE ' ' + last_name END AS Name
FROM dbo.person

Do you know where the problem is?

Body:
Use the CONCAT function available in SQL Server 2012 onward.

SELECT CONCAT([FirstName], ' , ' , [LastName]) FROM YOURTABLE


问:
Compute 3 Month return for dataframe of monthly returns
I have a dataframe of monthly stock returns:

```<code>d<-data.frame(replicate(5,sample(rnorm(1),6,rep=TRUE)))
</code>```

Now I would like to transform these returns to n-month returns in the following manner (e.g. for n=3):

```<code>d[1,1]=(1+d[1,1])*(1+d[2,1])*(1+d[3,1])
d[2,1]=(1+d[2,1])*(1+d[3,1])*(1+d[4,1])
d[3,1]=(1+d[3,1])*(1+d[4,1])*(1+d[5,1])
</code>```

And then the same for the next column:

```<code>d[1,2]=(1+d[1,2])*(1+d[2,2])*(1+d[3,2])
d[2,2]=(1+d[2,2])*(1+d[3,2])*(1+d[4,2])
d[3,2]=(1+d[3,2])*(1+d[4,2])*(1+d[5,2])
</code>```

I think you get the idea.

Now, the way I was thinking to proceed is as follows:

```<code>apply(d, 2, fun)
</code>```

where fun is defined as:

```<code>fun<-function(df_column)
{
  # Loop over df_column rows
 for (row in 1:nrow(df_column)) {
   d[row]=(1+d[row])*(1+d[row+1])*(1+d[row+2])
 }
}
</code>```

Does this approach make sense or is there a more elegant way?

答:
Try rollapply in one of these forms depending on what it is you prefer. The first puts NAs in the last two rows.  The second fills them with partial products and the third drops the last two rows.  The 3 argument specifies the width of the rolling product and could be changed if you want to try other widths.  See ?rollapply for more info.

```<code>library(zoo)

rollapplyr(d + 1, 3, prod, align = "left", fill = NA)

rollapplyr(d + 1, 3, prod, align = "left", partial = TRUE)

rollapplyr(d + 1, 3, prod, align = "left")
</code>```

Body:
I have a dataframe of monthly stock returns:

d<-data.frame(replicate(5,sample(rnorm(1),6,rep=TRUE)))

Now I would like to transform these returns to n-month returns in the following manner (e.g. for n=3):

d[1,1]=(1+d[1,1])*(1+d[2,1])*(1+d[3,1])
d[2,1]=(1+d[2,1])*(1+d[3,1])*(1+d[4,1])
d[3,1]=(1+d[3,1])*(1+d[4,1])*(1+d[5,1])

And then the same for the next column:

d[1,2]=(1+d[1,2])*(1+d[2,2])*(1+d[3,2])
d[2,2]=(1+d[2,2])*(1+d[3,2])*(1+d[4,2])
d[3,2]=(1+d[3,2])*(1+d[4,2])*(1+d[5,2])

I think you get the idea.

Now, the way I was thinking to proceed is as follows:

apply(d, 2, fun)

where fun is defined as:

fun<-function(df_column)
{
  # Loop over df_column rows
 for (row in 1:nrow(df_column)) {
   d[row]=(1+d[row])*(1+d[row+1])*(1+d[row+2])
 }
}

Does this approach make sense or is there a more elegant way?

Body:
Try rollapply in one of these forms depending on what it is you prefer. The first puts NAs in the last two rows.  The second fills them with partial products and the third drops the last two rows.  The 3 argument specifies the width of the rolling product and could be changed if you want to try other widths.  See ?rollapply for more info.

library(zoo)

rollapplyr(d + 1, 3, prod, align = "left", fill = NA)

rollapplyr(d + 1, 3, prod, align = "left", partial = TRUE)

rollapplyr(d + 1, 3, prod, align = "left")


问:
Aligning Image Caption
Currently, I have a problem with an image slideshow caption not positioning itself relative to the parent container. This may be a simple fix with the DIV floating but for the life of me I can't figure it out. The problem is the text does not stay within the constraints of the container that houses the image; and as such transforms differently upon resizing the webpage (basically moves off the visible area of the page). I'm hoping to set the height of the container housing the text to that of the parent container (the one housing the image) before formatting it to stay at the top 1/3 of the image in the center of the page. The text is based in an UL and transitions between items on the list as an overlay over the image.

This is the code on Codepen.As seen when the CSS transitions the Text (and the white background used for example) both are outside the bounds of the .container DIV (the UL with the dropshadow where I'm hoping to constrain the Text to.

Any help would be grately appreciated.

This is the HTML

```<code><div class="container" >
<ul class="imageBanner">
<li>
<span>Image 01</span>
<div>
<h2>Ahoy.</h2>
</div>
</li>
<li><span>Image 02</span>
<div>
<h2>Welcome.</h2>
</div></li>
<li><span>Image 03</span>
<div>
<h2>Bonjour.</h2>
</div></li>
</ul>
</div>
</code>```

This is the CSS

```<code>    .container {
  /* Full height*/
    height: 100%;
    box-shadow: 0px 8px 5px #888888;
    background:#ccc;
}

/* Image Slideshow Banner */

.imageBanner li span {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   color: transparent;
   background-size: cover;
   background-position: 30%;
   background-repeat: none;
   opacity: 0;
   z-index: 0;
   animation: imageAnimation 18s linear infinite 0s;
 }
 .imageBanner li div {
     z-index: 1;
     position: absolute;
     top:0px;
     width: 100%;
     text-align: center;
     opacity: 0;
     animation: titleAnimation 18s linear infinite 0s;
 }
 .imageBanner li div h2 {

     font-family:Calibri, Arial, sans-serif;
     background: #fff;
     font-size: 7em;
     color: rgb(46,105,163);

     line-height: 6em;
 }
.imageBanner li:nth-child(1) span {
 background-image: url('./images/iron_giant.jpg');
}
.imageBanner li:nth-child(2) span {
   background-image: url("./images/lonely_island.jpg");
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) span {
   background-image: url("./images/mountain_range.jpg");
   animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) div {
   animation-delay: 12s;
}
   @keyframes imageAnimation {
     0% { opacity: 0; animation-timing-function: ease-in; }
     8% { opacity: 1; animation-timing-function: ease-out; }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
 @keyframes titleAnimation {
     0% { opacity: 0 }
     8% { opacity: 1 }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
</code>```

答:
HTML5 markup will help you to understand center caption alignment.

Here is a Basic Example:

.container {
  /* Full height*/
  height: 100%;
  box-shadow: 0px 8px 5px #888888;
  background: #ccc;
}

ul {
  margin: 0;
  padding: 0;
  display: block;
}

li {
  list-style: none;
  height: 100% display: block;
}

/* Image Slideshow Banner */

.imageBanner li span {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  background-size: cover;
  background-repeat: none;
  z-index: 0;
  animation: imageAnimation 18s linear infinite 0s;
}

.imageBanner li div {
  z-index: 1;
  position: absolute;
  top: 0px;
  width: 100%;
  text-align: center;
  opacity: 0;
  animation: titleAnimation 18s linear infinite 0s;
}

.imageBanner li div h3 {
  font-family: Calibri, Arial, sans-serif;
  background: #fff;
  font-size: 7em;
  color: #2e69a3;
  line-height: 6em;
}

.imageBanner li:nth-child(1) span {
  background-image: url("https://unsplash.it/1200/800");
}

.imageBanner li:nth-child(2) span {
  background-image: url("https://unsplash.it/1200/800");
  animation-delay: 6s;
}

.imageBanner li:nth-child(3) span {
  background-image: url("https://unsplash.it/1200/800");
  animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
  animation-delay: 6s;
}

.imageBanner li:nth-child(3) div {
  animation-delay: 12s;
}

@keyframes imageAnimation {
  0% {
    opacity: 0;
    animation-timing-function: ease-in;
  }
  8% {
    opacity: 1;
    animation-timing-function: ease-out;
  }
  17% {
    opacity: 1;
  }
  35% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

@keyframes titleAnimation {
  0% {
    opacity: 0;
  }
  8% {
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  35% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <ul class="imageBanner">
    <li>
      <span></span>
      <div>
        <h3>Ahoy.</h3>
      </div>
    </li>
    <li><span></span>
      <div>
        <h3>Welcome.</h3>
      </div>
    </li>
    <li><span></span>
      <div>
        <h3>Bonjour.</h3>
      </div>
    </li>
  </ul>
</div></code>```

Title: Aligning Image Caption

Body:
Currently, I have a problem with an image slideshow caption not positioning itself relative to the parent container. This may be a simple fix with the DIV floating but for the life of me I can't figure it out. The problem is the text does not stay within the constraints of the container that houses the image; and as such transforms differently upon resizing the webpage (basically moves off the visible area of the page). I'm hoping to set the height of the container housing the text to that of the parent container (the one housing the image) before formatting it to stay at the top 1/3 of the image in the center of the page. The text is based in an UL and transitions between items on the list as an overlay over the image.

This is the code on Codepen.As seen when the CSS transitions the Text (and the white background used for example) both are outside the bounds of the .container DIV (the UL with the dropshadow where I'm hoping to constrain the Text to.

Any help would be grately appreciated.

This is the HTML

Image 01

Ahoy.

Image 02

Welcome.

Image 03

Bonjour.

This is the CSS

    .container {
  /* Full height*/
    height: 100%;
    box-shadow: 0px 8px 5px #888888;
    background:#ccc;
}

/* Image Slideshow Banner */

.imageBanner li span {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   color: transparent;
   background-size: cover;
   background-position: 30%;
   background-repeat: none;
   opacity: 0;
   z-index: 0;
   animation: imageAnimation 18s linear infinite 0s;
 }
 .imageBanner li div {
     z-index: 1;
     position: absolute;
     top:0px;
     width: 100%;
     text-align: center;
     opacity: 0;
     animation: titleAnimation 18s linear infinite 0s;
 }
 .imageBanner li div h2 {

     font-family:Calibri, Arial, sans-serif;
     background: #fff;
     font-size: 7em;
     color: rgb(46,105,163);

     line-height: 6em;
 }
.imageBanner li:nth-child(1) span {
 background-image: url('./images/iron_giant.jpg');
}
.imageBanner li:nth-child(2) span {
   background-image: url("./images/lonely_island.jpg");
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) span {
   background-image: url("./images/mountain_range.jpg");
   animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) div {
   animation-delay: 12s;
}
   @keyframes imageAnimation {
     0% { opacity: 0; animation-timing-function: ease-in; }
     8% { opacity: 1; animation-timing-function: ease-out; }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
 @keyframes titleAnimation {
     0% { opacity: 0 }
     8% { opacity: 1 }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }

Body:
HTML5 markup will help you to understand center caption alignment.

Here is a Basic Example:

.container {
  /* Full height*/
  height: 100%;
  box-shadow: 0px 8px 5px #888888;
  background: #ccc;
}

ul {
  margin: 0;
  padding: 0;
  display: block;
}

li {
  list-style: none;
  height: 100% display: block;
}

/* Image Slideshow Banner */

.imageBanner li span {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  background-size: cover;
  background-repeat: none;
  z-index: 0;
  animation: imageAnimation 18s linear infinite 0s;
}

.imageBanner li div {
  z-index: 1;
  position: absolute;
  top: 0px;
  width: 100%;
  text-align: center;
  opacity: 0;
  animation: titleAnimation 18s linear infinite 0s;
}

.imageBanner li div h3 {
  font-family: Calibri, Arial, sans-serif;
  background: #fff;
  font-size: 7em;
  color: #2e69a3;
  line-height: 6em;
}

.imageBanner li:nth-child(1) span {
  background-image: url("https://unsplash.it/1200/800");
}

.imageBanner li:nth-child(2) span {
  background-image: url("https://unsplash.it/1200/800");
  animation-delay: 6s;
}

.imageBanner li:nth-child(3) span {
  background-image: url("https://unsplash.it/1200/800");
  animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
  animation-delay: 6s;
}

.imageBanner li:nth-child(3) div {
  animation-delay: 12s;
}

@keyframes imageAnimation {
  0% {
    opacity: 0;
    animation-timing-function: ease-in;
  }
  8% {
    opacity: 1;
    animation-timing-function: ease-out;
  }
  17% {
    opacity: 1;
  }
  35% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

@keyframes titleAnimation {
  0% {
    opacity: 0;
  }
  8% {
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  35% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

<div class="container">
  <ul class="imageBanner">
    <li>
      <span></span>
      <div>
        <h3>Ahoy.</h3>
      </div>
    </li>
    <li><span></span>
      <div>
        <h3>Welcome.</h3>
      </div>
    </li>
    <li><span></span>
      <div>
        <h3>Bonjour.</h3>
      </div>
    </li>
  </ul>
</div>


问:
C++ ReadProcessMemory returns strange character
I try to read the memory of a process with this code :

```<code>int main() {
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, 0, FindProcessId());

DWORD me;
cin >> me;

char buffer[256];

ReadProcessMemory(hProcess, (LPVOID)me, &buffer, sizeof(buffer), 0);

cout << "Data read : " << buffer << endl;

system("pause");

return 0;}
</code>```

but when I start and enter an adress like : 0x7ffe0014

It prints this : ╠╠╠╠╠╠╠╠          (this * 256 I think)

But I don't know why.

Can you help me ?
Thank you.

答:
buffer is defined as a char and when you pass buffer to std::cout it prints the char representation of the bytes stored in buffer.  You try to fill buffer by calling ReadProcessMemory() on an arbitrary memory address, but it fails.

buffer is not initialized and because ReadProcessMemory fails it's printing the char representation of the un-initialized memory inside buffer.

Here is your code modified to call ReadProcessMemory on a variable in the current process, perhaps easier for learning purposes.

```<code>HANDLE hProcess = OpenProcess(PROCESS_VM_READ, 0, GetCurrentProcessId());

char buffer[20];

char* me = "Test";

ReadProcessMemory(hProcess, me, &buffer, sizeof(me)+1, 0);

std::cout << "Data read : " << buffer << std::endl;

system("pause");

return 0;
</code>```

This would correctly output "Data read : Test" to the console.

If you assign nullptr to "char* me" you will get the same "╠╠╠╠╠╠╠╠" mumbo jumbo that you got previously as it will point at address 0x0 which is typically uninitialized.

Keep in mind if you're trying to read a string from another process you will want to reverse engineer the hard coded string size if it's not null terminated and only read the correct number of bytes.

Body:
I try to read the memory of a process with this code :

int main() {
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, 0, FindProcessId());

DWORD me;
cin >> me;

char buffer[256];

ReadProcessMemory(hProcess, (LPVOID)me, &buffer, sizeof(buffer), 0);

cout << "Data read : " << buffer << endl;

system("pause");

return 0;}

but when I start and enter an adress like : 0x7ffe0014

It prints this : ╠╠╠╠╠╠╠╠          (this * 256 I think)

But I don't know why.

Can you help me ?
Thank you.

Body:
buffer is defined as a char and when you pass buffer to std::cout it prints the char representation of the bytes stored in buffer.  You try to fill buffer by calling ReadProcessMemory() on an arbitrary memory address, but it fails.

buffer is not initialized and because ReadProcessMemory fails it's printing the char representation of the un-initialized memory inside buffer.

Here is your code modified to call ReadProcessMemory on a variable in the current process, perhaps easier for learning purposes.

HANDLE hProcess = OpenProcess(PROCESS_VM_READ, 0, GetCurrentProcessId());

char buffer[20];

char* me = "Test";

ReadProcessMemory(hProcess, me, &buffer, sizeof(me)+1, 0);

std::cout << "Data read : " << buffer << std::endl;

system("pause");

return 0;

This would correctly output "Data read : Test" to the console.

If you assign nullptr to "char* me" you will get the same "╠╠╠╠╠╠╠╠" mumbo jumbo that you got previously as it will point at address 0x0 which is typically uninitialized.

Keep in mind if you're trying to read a string from another process you will want to reverse engineer the hard coded string size if it's not null terminated and only read the correct number of bytes.


问:
Replication MySQL & MS SQL
How make replication between MySQL and MS SQL server 2005. I want flow data from MySQL to MS SQL server, when ever any changes makes in MySQL.

Thank you,

答: Creating a SSIS procedure to do this is not difficult if you're willing to do it as a "batch" process. Replicating in real-time has caused our SQL Server to burp big time. We now do a nightly process that copies the data from one server to the other.</p>

Title: Replication MySQL & MS SQL


问:
Why does this if true condition in js doesn't work
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

```<code><!DOCTYPE html>
<html>
<head>
    <title>ch6</title>
</head>
<body>
    <h1>List</h1>
    <h2>audio note</h2>
    <p>Enter note name</p>
    <input type="text" >
<br>
    <img id="pic" onclick="click()" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
<script type="text/javascript">
    function click(){
        var butt = true;
        if(butt === true)
        {
            document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }

</script>

</body>
</html>
</code>```

`

 I hope to click to change the image.

 The image doesn't change when I click it.

答:
Declare the variable outside the click function::

```<code>var butt = true;
function click(){
}
</code>```

now work same in that function

Body:
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

<!DOCTYPE html>

    <title>ch6</title>

List

audio note

Enter note name

    <input type="text" >

`

 I hope to click to change the image.

 The image doesn't change when I click it.

Body:
Declare the variable outside the click function::

var butt = true;
function click(){
}

now work same in that function


问:
angularjs function called multiple times while pushing data into array
I am concatenating few columns into a single column and showing it on a grid. I want to push that value into an array. While doing that i am getting this error.

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
  Watchers fired in the last 5 iterations:

Also i noticed that this function is called many times. I did few thing as suggested in other posts, but nothing worked.
In the following code i am concatenating columns in the getLoss() function and i am trying to insert that value into an array.

How can i push the value into an array when the function is called for each row?

```<code>columnDefs: [{ field        : 'loss',
                cellTemplate : '<div id="grid-cell-template">
                                   {{grid.appScope.getLoss(row.entity)}}</div>'}]

var totalLoss = [];

$scope.getLoss = function(rowEntity) {

            var ls1 = rowEntity.loss1;
            var ls2 = rowEntity.loss2;
            var ls3 = rowEntity.loss3;

           loss= ls1+ls2+ls3;
           console.log("loss=", loss);

           totalLoss.push(loss);

            return loss;
        };
</code>```

答:
instead of calling the function like an expression, call it inside the ng-init

```<code>columnDefs: [{ field        : 'loss',
                cellTemplate : '<div id="grid-cell-template" ng-init="grid.appScope.getLoss(row.entity)">
                                   {{loss}}</div>'}]
</code>```

change the loss variable to a scope and make your totalLoss empty inside the function.

```<code>var totalLoss = [];
$scope.getLoss = function(rowEntity) {

           totalLoss = [];
           var ls1 = rowEntity.loss1;
           var ls2 = rowEntity.loss2;
           var ls3 = rowEntity.loss3;

           $scope.loss= ls1+ls2+ls3;
           console.log("loss=", loss);

           totalLoss.push(loss);

};
</code>```

Body:
I am concatenating few columns into a single column and showing it on a grid. I want to push that value into an array. While doing that i am getting this error.

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
  Watchers fired in the last 5 iterations:

Also i noticed that this function is called many times. I did few thing as suggested in other posts, but nothing worked.
In the following code i am concatenating columns in the getLoss() function and i am trying to insert that value into an array.

How can i push the value into an array when the function is called for each row?

columnDefs: [{ field        : 'loss',
                cellTemplate : '

                                   {{grid.appScope.getLoss(row.entity)}}
'}]

var totalLoss = [];

$scope.getLoss = function(rowEntity) {

            var ls1 = rowEntity.loss1;
            var ls2 = rowEntity.loss2;
            var ls3 = rowEntity.loss3;

           loss= ls1+ls2+ls3;
           console.log("loss=", loss);

           totalLoss.push(loss);

            return loss;
        };

Body:
instead of calling the function like an expression, call it inside the ng-init

columnDefs: [{ field        : 'loss',
                cellTemplate : '<div id="grid-cell-template" ng-init="grid.appScope.getLoss(row.entity)">
                                   {{loss}}</div>'}]

change the loss variable to a scope and make your totalLoss empty inside the function.

var totalLoss = [];
$scope.getLoss = function(rowEntity) {

           totalLoss = [];
           var ls1 = rowEntity.loss1;
           var ls2 = rowEntity.loss2;
           var ls3 = rowEntity.loss3;

           $scope.loss= ls1+ls2+ls3;
           console.log("loss=", loss);

           totalLoss.push(loss);

};


问:
How to use Vuex types constants with module namespace?
I have this Vuex module:

```<code>//modules/things.js
const state = {
  firstThing: 'abc',
  secondThing: 'def',
};

const getters = {
  getFirstThing: state => state.firstThing,
  getSecondThing: state => state.secondThing,
};

const mutations = {
  setFirstThing: (state, payload) => state.firstThing = payload,
  setSecondThing: (state, payload) => state.secondThing = payload
};

const actions = {};

export default {
  namespaced: true,   // <------
  state,
  mutations,
  actions,
  getters
};
</code>```

I use namespaced: true flag and can work with this module like this:

```<code>this.$store.state.things.firstThing             // <-- return abc here
this.$store.commit('things/setFirstThing', 10)
this.$store.getters['things/getFirstThing']     // <-- return abc here
</code>```

If I will use constants like in Vuex official example, and refactor my modules/things.js file like this:

```<code>export const Types = {
  getters: {
    GET_FIRST_THING: 'GET_FIRST_THING',
    GET_SECOND_THING: 'GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'SET_FIRST_THING',
    SET_SECOND_THING: 'SET_SECOND_THING',
  }
};

const getters = {
  [Types.getters.GET_FIRST_THING]: state => state.firstThing,
  [Types.getters.GET_SECOND_THING]: state => state.secondThing,
};

const mutations = {
  [Types.mutations.SET_FIRST_THING]: (state, payload) => state.firstThing = payload,
  [Types.mutations.SET_SECOND_THING]: (state, payload) => state.secondThing = payload
};
</code>```

I will have to use namespace prefix:

```<code>this.$store.commit('things/' + Types.mutations.SET_FIRST_THING, 10);
this.$store.getters['things/' +  + Types.getters.GET_FIRST_THING]
</code>```

If I will include module namespace prefix to Types constant, I will have to use string prefix things/ for mutations/actions/getters declaration:

```<code>const getters = {
  ['things/' + Types.getters.GET_FIRST_THING]: state => state.firstThing,
  ['things/' + Types.getters.GET_SECOND_THING]: state => state.secondThing,
};
</code>```

How to avoid that?

答:
You can disable namespacing by namespaced: false and just use constants with prefixes:

```<code>export const Types = {
  getters: {
    GET_FIRST_THING: 'THINGS_GET_FIRST_THING',    // your namespace without '/' slash
    GET_SECOND_THING: 'THINGS_GET_SECOND_THING',
  },
  // ...
}
</code>```

- it will work.

But if you still want to keep namespaced: true in module and use constants also, you can define two types of constants: public and private:

```<code>export const Types = {                                               // <-- public
  getters: {
    GET_FIRST_THING: 'things/GET_FIRST_THING',
    GET_SECOND_THING: 'things/GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'things/SET_FIRST_THING',
    SET_SECOND_THING: 'things/SET_SECOND_THING',
  }
};

const _types = removeNamespace('things/', Types);                    // <-- private
</code>```

Then use private _types only inside Vuex module:

```<code>const getters = {
  [_types.getters.GET_FIRST_THING]: state => state.firstThing,
  [_types.getters.GET_SECOND_THING]: state => state.secondThing,
};

//...
</code>```

and public Types outside module:

```<code>// some-component.vue
this.$store.commit(Types.mutations.SET_FIRST_THING, 10);
this.$store.getters[Types.getters.GET_FIRST_THING]
// ...
</code>```

Also implement simple removeNamespace function in your new namespace-helper.js file:

```<code>export default function removeNamespace(namespace, types){
  return _.reduce(types, (typeObj, typeValue, typeName) => {
    typeObj[typeName] = _.reduce(typeValue, (obj, v, k)=>{
      obj[k] = v.replace(namespace, '');
      return obj;
    }, {});
    return typeObj;
  }, {});
}
</code>```

Body:
I have this Vuex module:

//modules/things.js
const state = {
  firstThing: 'abc',
  secondThing: 'def',
};

const getters = {
  getFirstThing: state => state.firstThing,
  getSecondThing: state => state.secondThing,
};

const mutations = {
  setFirstThing: (state, payload) => state.firstThing = payload,
  setSecondThing: (state, payload) => state.secondThing = payload
};

const actions = {};

export default {
  namespaced: true,   // <------
  state,
  mutations,
  actions,
  getters
};

I use namespaced: true flag and can work with this module like this:

this.$store.state.things.firstThing             // <-- return abc here
this.$store.commit('things/setFirstThing', 10)
this.$store.getters['things/getFirstThing']     // <-- return abc here

If I will use constants like in Vuex official example, and refactor my modules/things.js file like this:

export const Types = {
  getters: {
    GET_FIRST_THING: 'GET_FIRST_THING',
    GET_SECOND_THING: 'GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'SET_FIRST_THING',
    SET_SECOND_THING: 'SET_SECOND_THING',
  }
};

const getters = {
  [Types.getters.GET_FIRST_THING]: state => state.firstThing,
  [Types.getters.GET_SECOND_THING]: state => state.secondThing,
};

const mutations = {
  [Types.mutations.SET_FIRST_THING]: (state, payload) => state.firstThing = payload,
  [Types.mutations.SET_SECOND_THING]: (state, payload) => state.secondThing = payload
};

I will have to use namespace prefix:

this.$store.commit('things/' + Types.mutations.SET_FIRST_THING, 10);
this.$store.getters['things/' +  + Types.getters.GET_FIRST_THING]

If I will include module namespace prefix to Types constant, I will have to use string prefix things/ for mutations/actions/getters declaration:

const getters = {
  ['things/' + Types.getters.GET_FIRST_THING]: state => state.firstThing,
  ['things/' + Types.getters.GET_SECOND_THING]: state => state.secondThing,
};

How to avoid that?

Body:
You can disable namespacing by namespaced: false and just use constants with prefixes:

export const Types = {
  getters: {
    GET_FIRST_THING: 'THINGS_GET_FIRST_THING',    // your namespace without '/' slash
    GET_SECOND_THING: 'THINGS_GET_SECOND_THING',
  },
  // ...
}

- it will work.

But if you still want to keep namespaced: true in module and use constants also, you can define two types of constants: public and private:

export const Types = {                                               // <-- public
  getters: {
    GET_FIRST_THING: 'things/GET_FIRST_THING',
    GET_SECOND_THING: 'things/GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'things/SET_FIRST_THING',
    SET_SECOND_THING: 'things/SET_SECOND_THING',
  }
};

const _types = removeNamespace('things/', Types);                    // <-- private

Then use private _types only inside Vuex module:

const getters = {
  [_types.getters.GET_FIRST_THING]: state => state.firstThing,
  [_types.getters.GET_SECOND_THING]: state => state.secondThing,
};

//...

and public Types outside module:

// some-component.vue
this.$store.commit(Types.mutations.SET_FIRST_THING, 10);
this.$store.getters[Types.getters.GET_FIRST_THING]
// ...

Also implement simple removeNamespace function in your new namespace-helper.js file:

export default function removeNamespace(namespace, types){
  return _.reduce(types, (typeObj, typeValue, typeName) => {
    typeObj[typeName] = _.reduce(typeValue, (obj, v, k)=>{
      obj[k] = v.replace(namespace, '');
      return obj;
    }, {});
    return typeObj;
  }, {});
}


问:
How does select work when multiple channels are involved?
I found when using select on multiple non buffered channels like

```<code>select {
case <- chana:
case <- chanb:
}
</code>```

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

```<code>package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}
</code>```

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

答:
As mentioned in the comment, if you want to ensure balance, you can just forgo using select altogether in the reading goroutine and rely on the synchronisation provided by unbuffered channels:

```<code>go func() {
    for {
        <-chana
        acount++
        <-chanb
        bcount++

        if acount == 1000 || bcount == 1000 {
            fmt.Println("finish one acount, bcount", acount, bcount)
            break
        }
    }
    wg.Done()
}()
</code>```

Body:
I found when using select on multiple non buffered channels like

select {
case <- chana:
case <- chanb:
}

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

Body:
As mentioned in the comment, if you want to ensure balance, you can just forgo using select altogether in the reading goroutine and rely on the synchronisation provided by unbuffered channels:

go func() {
    for {
        <-chana
        acount++
        <-chanb
        bcount++

        if acount == 1000 || bcount == 1000 {
            fmt.Println("finish one acount, bcount", acount, bcount)
            break
        }
    }
    wg.Done()
}()


问:
Multiple Table search query in Laravel 5.2
Trying to search Patient record from three tables in a filter...I have already write the code for patient name and patient phone but got stuck at area of treatment and doctor because both of them are in different table..Please help to write a query for this filter...

Here is my filter:

Patient Data along with billing(doctor and area of treatment):

Patient Model:

```<code>public function scopeQueryStringFilters( $query )
{

    if(request()->has('patient_name'))
    {
        $query->where('name',request('patient_name'));
    }

    if(request()->has('patient_phone'))
    {
        $query->where('phone',request('patient_phone'));
    }

}
</code>```

答:
You can use whereHas method.

```<code>Patient::whereHas('billing', function($query){
    $query->where('area_of_treatment_id', request('area_of_treatment_id'));
})
->get();

Patient::whereHas('billing.doctor', function($query){
    $query->where('name', request('doctor'));
})
->get();
</code>```

Body:
Trying to search Patient record from three tables in a filter...I have already write the code for patient name and patient phone but got stuck at area of treatment and doctor because both of them are in different table..Please help to write a query for this filter...

Here is my filter:

Patient Data along with billing(doctor and area of treatment):

Patient Model:

public function scopeQueryStringFilters( $query )
{

    if(request()->has('patient_name'))
    {
        $query->where('name',request('patient_name'));
    }

    if(request()->has('patient_phone'))
    {
        $query->where('phone',request('patient_phone'));
    }

}

Body:
You can use whereHas method.

Patient::whereHas('billing', function($query){
    $query->where('area_of_treatment_id', request('area_of_treatment_id'));
})
->get();

Patient::whereHas('billing.doctor', function($query){
    $query->where('name', request('doctor'));
})
->get();


问:
How do I localize the jQuery UI Datepicker?
I really need a localized dropdown calendar. An English calendar doesn't exactly communicate excellence on a Norwegian website ;-)

I have experimented with the jQuery DatePicker, their website says it can be localized, however that doesn't seem to work.

I am using ASPNET.MVC, and I really want to stick to one javascript library. In this case jQuery.

The ajax toolkit calendar would be acceptable, if only it too would display Norwegian names.

Update: Awesome! I see I am missing the language files, a not so minor detail :-)

答:
This solution may help.

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ui-datepicker-div {
  font-size: 14px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">

Japanese JQuery UI Datepicker

<input type="text" id="japaneseCalendar"/>

```

OwnerDisplayName: Thomas Eyde

LastEditorDisplayName: Schnapple

Body:
This solution may help.

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});

#ui-datepicker-div {
  font-size: 14px;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
</head>
<body>
<h3>Japanese JQuery UI Datepicker</h3>
<input type="text" id="japaneseCalendar"/>

</body>
</html>


问:
search data frame 1 values in data frame 2 and count the occurrence
I have two data frames as below:
data frame df1 (with one column):

```<code>names
alpha beta
test1 test2
abc def
</code>```

and data frame df2 (also with one column):

```<code>names
alpha beta (abc)
abc def d
abc def (xyz)
test1 test2
test1 test2 (a)
alpha beta d
alpha beta (1)
alpha beta (2)
</code>```

I want output such that code will search df1 values in df2 and count the occurrence of those values to show the output as below.

Desired output data frame (two columns):

```<code>names          occurrence
alpha beta         4
test1 test2        2
abc def            2
</code>```

答:
You can use str.extract + value_counts -

```<code>p = '(' + df1.names.str.cat(sep='|') + ')'
df2.names.str.extract(p, expand=False).value_counts()

alpha beta     4
abc def        2
test1 test2    2
Name: names, dtype: int64
</code>```

If it's possible for multiple matches to occur for a given row, you can use extractall instead -

```<code>df2.names.str.extractall(p).iloc[:, 0].value_counts()

alpha beta     4
abc def        2
test1 test2    2
Name: 0, dtype: int64
</code>```

Body:
I have two data frames as below:
data frame df1 (with one column):

names
alpha beta
test1 test2
abc def

and data frame df2 (also with one column):

names
alpha beta (abc)
abc def d
abc def (xyz)
test1 test2
test1 test2 (a)
alpha beta d
alpha beta (1)
alpha beta (2)

I want output such that code will search df1 values in df2 and count the occurrence of those values to show the output as below.

Desired output data frame (two columns):

names          occurrence
alpha beta         4
test1 test2        2
abc def            2

Body:
You can use str.extract + value_counts -

p = '(' + df1.names.str.cat(sep='|') + ')'
df2.names.str.extract(p, expand=False).value_counts()

alpha beta     4
abc def        2
test1 test2    2
Name: names, dtype: int64

If it's possible for multiple matches to occur for a given row, you can use extractall instead -

df2.names.str.extractall(p).iloc[:, 0].value_counts()

alpha beta     4
abc def        2
test1 test2    2
Name: 0, dtype: int64


问:
Angular 2 child component loads before data passed with @input()
I have two component in my angular 2 application : component A (parent) and component B (child).

When i passe data (myData) from A to B with @Input() i get my data in my B (child component), but the problem is that the child component loads BEFORE myData and i got indefined, the only way a can console.log(myData) is in ngOnDestroy hook !

How to deal with this kind of load order ?

答:
Here is a solution that was easiest for me. Use *ngIf in your parent component to delay the initialization of the child component. You will bind the child component only if myData has a value.

```<code><parent-component>
  <child-component [input]="myData" *ngIf="myData"></child-component>
</parent-component>
</code>```

Body:
Here is a solution that was easiest for me. Use *ngIf in your parent component to delay the initialization of the child component. You will bind the child component only if myData has a value.

<parent-component>
  <child-component [input]="myData" *ngIf="myData"></child-component>
</parent-component>


问:
Undefined method skills_path Rails
I am trying to create a new skill in my belongs_to and has_many through relationship.

```<code>class Row < ApplicationRecord
  belongs_to :timeframe, required: false
  belongs_to :map, required: false
  belongs_to :standard, required: false
  belongs_to :content, required: false
  belongs_to :skill, required: false
  belongs_to :resource, required: false
  belongs_to :assignment, required: false
end

class Skill < ApplicationRecord
  has_many :rows
  has_many :maps, through: :rows
end
</code>```

I want to create a new skill under a row so I created the following route to do so.

resources :rows do
    resources :skills
  end

If I do a rake routes I see that I need to use the following route to create that skill under the row. new_row_skill_path

If I use this link_to I would like it to go to the form to create that form.

<%= link_to '+', new_row_skill_path(row), class: 'btn btn-primary' %>

This is the form I am using:

```<code><%= form_with(model: skill, local: true) do |form| %>
  <div class="form-group">
    <%= form.label :skill %>
    <%= form.text_field :skill, class: 'form-control' %>
  </div>

  <%= form.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
</code>```

However when I am clicking that add button I get this error.
undefined methodskills_path'`

Does this have something to do with me using the form_with(model: skill)? I tried custom writing a route under the rows do like so but I am still getting that error.

```<code>resources :rows do
  get 'rows/:id/skills/new', to: 'skills#new'
end
</code>```

Skills controller

```<code>class SkillsController < ApplicationController
  def new
    @skill = Skill.new
  end

  def create
    @skill = Skill.new(skill_params)

    respond_to do |format|
      if @skill.save
        format.html { redirect_to root_path, notice: 'Skill created.' }
      else
        format.html { render :new, notice: 'That shit failed.' }
      end
    end
  end

  private
    def skill_params
      params.require(:skill).permit(:skill_id, :skills)
    end
end
</code>```

答:
In your routes file, go back to using:

```<code>resources :rows do
  resources :skills
end
</code>```

Then try specifying a url like so:

<%= form_with(model: skill, local: true, url: row_skills_path) do |form| %>

Title: Undefined method skills_path Rails

Body:
I am trying to create a new skill in my belongs_to and has_many through relationship.

class Row < ApplicationRecord
  belongs_to :timeframe, required: false
  belongs_to :map, required: false
  belongs_to :standard, required: false
  belongs_to :content, required: false
  belongs_to :skill, required: false
  belongs_to :resource, required: false
  belongs_to :assignment, required: false
end

class Skill < ApplicationRecord
  has_many :rows
  has_many :maps, through: :rows
end

I want to create a new skill under a row so I created the following route to do so.

resources :rows do
    resources :skills
  end

If I do a rake routes I see that I need to use the following route to create that skill under the row. new_row_skill_path

If I use this link_to I would like it to go to the form to create that form.

<%= link_to '+', new_row_skill_path(row), class: 'btn btn-primary' %>

This is the form I am using:

<%= form_with(model: skill, local: true) do |form| %>

    <%= form.label :skill %>
    <%= form.text_field :skill, class: 'form-control' %>

  <%= form.submit 'Submit', class: 'btn btn-primary' %>
<% end %>

However when I am clicking that add button I get this error.
undefined methodskills_path'`

Does this have something to do with me using the form_with(model: skill)? I tried custom writing a route under the rows do like so but I am still getting that error.

resources :rows do
  get 'rows/:id/skills/new', to: 'skills#new'
end

Skills controller

class SkillsController < ApplicationController
  def new
    @skill = Skill.new
  end

  def create
    @skill = Skill.new(skill_params)

    respond_to do |format|
      if @skill.save
        format.html { redirect_to root_path, notice: 'Skill created.' }
      else
        format.html { render :new, notice: 'That shit failed.' }
      end
    end
  end

  private
    def skill_params
      params.require(:skill).permit(:skill_id, :skills)
    end
end

Body:
In your routes file, go back to using:

resources :rows do
  resources :skills
end

Then try specifying a url like so:

<%= form_with(model: skill, local: true, url: row_skills_path) do |form| %>


问:
How to prompt the user to enter a integer within a certain amount of numbers
I was trying to figure out what statement to use to get the user to enter a number between 1 and 10.

here is what i have so far.

```<code>int a;
printf("Enter a number between 1 and 10: \n);
scanf("%d", &a);
</code>```

答:
Why not use the do .. while loop?

```<code>int a;

do {
  printf("Enter a number between 1 and 10: \n");
  scanf("%d", &a);
} while (a < 1 || a > 10);
</code>```

Body:
I was trying to figure out what statement to use to get the user to enter a number between 1 and 10.

here is what i have so far.

int a;
printf("Enter a number between 1 and 10: \n);
scanf("%d", &a);

Body:
Why not use the do .. while loop?

int a;

do {
  printf("Enter a number between 1 and 10: \n");
  scanf("%d", &a);
} while (a < 1 || a > 10);


问:
jQuery How do set text in a input field then press enter?
jQuery How do set text in a input field then press enter?  I have input field if I manually enter text then submit button will get enabled but if I use jQuery to enter text, then the button won't enabled. How can I make the button enabled?  I am using jQuery with Selenium

Here is what I am looking for verizonwireless.com/support/contact-us on this page, if you enter something in search field, "X" will show up but if you enter using JQuery it won't. So how will I make the "X" show up when I use jquery to enter the text? $('#vgn_q').val('iphone').change(); I tried this but no luck

答:
Here you go with a solution

$("input").on("change keyup",function(){
  if($(this).val() !== ''){
    $('button').prop("disabled",false);
  }else{
    $('button').prop("disabled",true);
  }
})

//Setting the value using jQuery
setTimeout(function(){
  $('input').val("test").change();
}, 2000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button disabled="disabled">submit</button></code>```

I've used setTimeout to showcase the value of the input textbox is set after 2secs.

After setting the value of input textbox you need to trigger the change event.

Hope this will help you.

Body:
Here you go with a solution

$("input").on("change keyup",function(){
  if($(this).val() !== ''){
    $('button').prop("disabled",false);
  }else{
    $('button').prop("disabled",true);
  }
})

//Setting the value using jQuery
setTimeout(function(){
  $('input').val("test").change();
}, 2000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button disabled="disabled">submit</button>

I've used setTimeout to showcase the value of the input textbox is set after 2secs.

After setting the value of input textbox you need to trigger the change event.

Hope this will help you.


问:
How to solve "config.h file not found"? when running app from the react native on the device?
Getting error "Config.h file not found, lexical or preprocessor error."

I am running app in the device from the xcode project.

I have google and found many solutions but haven't worked, I tried this

https://github.com/facebook/react-native/issues/14382

And when I try to run in the iOS simulator getting this error

https://github.com/facebook/react-native/issues/10401

Tried to follow the above url but didn't work.

Please let me know how to solve the issue.
Thanks

答:
I faced the same issue and it's fixed by these commands:-

yarn

```<code>rm -rf node_modules/
yarn cache clean
yarn install
</code>```

npm

```<code>rm -rf node_modules/
npm cache clean
npm i
</code>```

Body:
I faced the same issue and it's fixed by these commands:-

yarn

rm -rf node_modules/
yarn cache clean
yarn install

npm

rm -rf node_modules/
npm cache clean
npm i


问:
AWS - Serverless - "message": "Internal server error" when deploying, but work offline
I have a problem when deploying a project using Serverless framework and Amazon Web Services (more specifically API Gateway service).

On my local machine, when I do serverless offline everything works fine:
When going to http://localhost:3000/, I have:

```<code>{
    "message": "welcome"
}
</code>```

When navigating to http://localhost:3000/examples, I have:

```<code>{
    "message": "Example test"
}
</code>```

However, when deploying with serverless deploy, only the first one works. The next one displays the following:

```<code>{
    "message": "Internal server error"
}
</code>```

In my code I have the following routes:

```<code>app.use('/examples', ExampleController)

app.get('/', (request, response) => {
  response.json({
    message: 'welcome'
  })
})
</code>```

And this is what I have in my ExampleController:

```<code>ExampleController.get('/', (request, response) => {
  response.json({
    message: 'Example test'
  })
})
</code>```

What can be the problem here?

答:
Fixed my problem by adding the following role in iamRoleStatements in serverless.yml:</p>

```<code>-  Effect: "Allow"
   Action:
     - "cloudformation:DescribeStackResource"
   Resource: "*"
</code>```

Body:
I have a problem when deploying a project using Serverless framework and Amazon Web Services (more specifically API Gateway service).

On my local machine, when I do serverless offline everything works fine:
When going to http://localhost:3000/, I have:

{
    "message": "welcome"
}

When navigating to http://localhost:3000/examples, I have:

{
    "message": "Example test"
}

However, when deploying with serverless deploy, only the first one works. The next one displays the following:

{
    "message": "Internal server error"
}

In my code I have the following routes:

app.use('/examples', ExampleController)

app.get('/', (request, response) => {
  response.json({
    message: 'welcome'
  })
})

And this is what I have in my ExampleController:

ExampleController.get('/', (request, response) => {
  response.json({
    message: 'Example test'
  })
})

What can be the problem here?

Body:
Fixed my problem by adding the following role in iamRoleStatements in serverless.yml:

-  Effect: "Allow"
   Action:
     - "cloudformation:DescribeStackResource"
   Resource: "*"


问:
If statement always returns true c#
When I run this statement I always get a return of true even if some of the bools return false. Any ideas on a fix?

```<code>public bool Enabled() {
          foreach (LinkIn link in linksIn) {
            if (link.source.amount < link.amount) {
              return false;
            }
          }
          //Not checking capacity correctly
          foreach (LinkOut link in linksOut) {
            if (link.target.Limited()
                && link.target.capacity < link.amount
                && link.target.amount + link.amount > link.target.capacity)
                {
                 return false;
                }
          }
          return true;
        }
</code>```

The link.target.Limited() simply checks if a target has a capacity.

答:
Trying to work out the requirements, I reckon that what you want is:

If the target is Limited(), then fail if either we are larger than the capacity, or if there is not enough space in the target to add our amount

So, that would make the condition:

```<code>if (link.target.Limited()
 && (link.target.capacity < link.amount
       || link.target.amount + link.amount > link.target.capacity))
</code>```

To be more symmetric, by swapping the LHS and RHS of the third expression this can be written as:

```<code>if (link.target.Limited()
 && (link.target.capacity < link.amount
  || link.target.capacity < link.target.amount + link.amount))
</code>```

Now, we can further see that link.target.capacity < link.amount is true if and only if link.target.capacity < link.target.amount + link.amount is also true, so we can simplify to:

```<code>if (link.target.Limited()
 && link.target.capacity < link.target.amount + link.amount)
</code>```

Title: If statement always returns true c#

Body:
When I run this statement I always get a return of true even if some of the bools return false. Any ideas on a fix?

public bool Enabled() {
          foreach (LinkIn link in linksIn) {
            if (link.source.amount < link.amount) {
              return false;
            }
          }
          //Not checking capacity correctly
          foreach (LinkOut link in linksOut) {
            if (link.target.Limited()
                && link.target.capacity < link.amount
                && link.target.amount + link.amount > link.target.capacity)
                {
                 return false;
                }
          }
          return true;
        }

The link.target.Limited() simply checks if a target has a capacity.

Body:
Trying to work out the requirements, I reckon that what you want is:

If the target is Limited(), then fail if either we are larger than the capacity, or if there is not enough space in the target to add our amount

So, that would make the condition:

if (link.target.Limited()
 && (link.target.capacity < link.amount
       || link.target.amount + link.amount > link.target.capacity))

To be more symmetric, by swapping the LHS and RHS of the third expression this can be written as:

if (link.target.Limited()
 && (link.target.capacity < link.amount
  || link.target.capacity < link.target.amount + link.amount))

Now, we can further see that link.target.capacity < link.amount is true if and only if link.target.capacity < link.target.amount + link.amount is also true, so we can simplify to:

if (link.target.Limited()
 && link.target.capacity < link.target.amount + link.amount)


问:
Retrieve JSON array from Firebase in Android
I have a JSON array where I store a few items I want to display on my app's main menu. It looks like this:

I'd like to retrieve this list but for some reason I ignore the code below doesn't work:

```<code>DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

    @Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);

    mMainMenuRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String stringValue = ds.getValue(String.class);
                Log.i("Firebase", stringValue);
            }
        }

        ...

    });
</code>```

答:
You reference points to /main_menu in the database:

```<code>DatabaseReference mMainMenuRef = mRootRef.child("main_menu");
</code>```

You then listen to that reference and loop over the data:

```<code>mMainMenuRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String stringValue = ds.getValue(String.class);
            Log.i("Firebase", stringValue);
        }
    }
</code>```

This means that you loop over the child nodes directly under /main_menu, so -L-FDnRW.... You then try to get the string value of that node. But the -L-FDnRW... contains an entire JSON object, so there is no singular string value.

To get the value of a specific property under -L-FDnRW... use the DataSnapshot.child() method:

```<code>public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        String stringValue = ds.child("0").getValue(String.class);
        Log.i("Firebase", stringValue);
    }
}
</code>```

To show the value of all children, loop over the child snapshots:

```<code>public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
      for (DataSnapshot prop : ds.getChildren()) {
        String stringValue = ptop.getValue(String.class);
        Log.i("Firebase", stringValue);
      }
    }
}
</code>```

Body:
I have a JSON array where I store a few items I want to display on my app's main menu. It looks like this:

I'd like to retrieve this list but for some reason I ignore the code below doesn't work:

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

    @Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);

    mMainMenuRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String stringValue = ds.getValue(String.class);
                Log.i("Firebase", stringValue);
            }
        }

        ...

    });

Body:
You reference points to /main_menu in the database:

DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

You then listen to that reference and loop over the data:

mMainMenuRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String stringValue = ds.getValue(String.class);
            Log.i("Firebase", stringValue);
        }
    }

This means that you loop over the child nodes directly under /main_menu, so -L-FDnRW.... You then try to get the string value of that node. But the -L-FDnRW... contains an entire JSON object, so there is no singular string value.

To get the value of a specific property under -L-FDnRW... use the DataSnapshot.child() method:

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        String stringValue = ds.child("0").getValue(String.class);
        Log.i("Firebase", stringValue);
    }
}

To show the value of all children, loop over the child snapshots:

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
      for (DataSnapshot prop : ds.getChildren()) {
        String stringValue = ptop.getValue(String.class);
        Log.i("Firebase", stringValue);
      }
    }
}


问:
bash scripting - how to write an effective case statement to handle multiple conditions
I have a script that reads a main list, call it List A using a while loop.

List A:

```<code>east-1-1
east-1-2
east-1-3
east-1-4
east-1-5
east-1-6
east-1-7
west-1-1
west-1-10
south-1-1
south-1-2
north-1-1
</code>```

What I would like to do is check it against this list:

```<code>east-1-1
east-1-3
east-1-7
west-1-10
south-1-2
</code>```

As listed in my case and for each of those items in my case I would like to flag down with an *

```<code>  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
</code>```

I am doing this within a function and using a case statement, however I think I'm doing this wrong and would like to know if there's a better way? Should I be using an if-then-else? Can I do this with the case?

If I could please get some help on this approach or if there's a better way to write this.

CODE IN PROGRESS:

```<code>#!/usr/local/bin/bash

MAP=./.clusterinfo
if ! [ -f "$MAP" ]; then
      echo "Cluster Map not found."
      exit 1
fi

while IFS='' read -r cluster; do
#Function runQuery
runQuery()
{
  getCount=$(PGPASSWORD=Abc123Pa55word psql -h myapp-"${cluster}".foobar.com -U foo -d dev -p 5439 -t -c "select count(*) from pg_database;")

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
    echo "${cluster}:${getCount}"
}

#Execute
runQuery

done < "$MAP"
</code>```

Current Output:

```<code>east-1-1:    50 *
east-1-1:    50
east-1-2:     8
east-1-3:    58 *
east-1-3:    58
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
east-1-7:    30
west-1-1:     4
west-1-10:   50 *
west-1-10:   50
south-1-2:   30 *
south-1-2:   30
</code>```

Expected Output:

```<code>east-1-1:    50 *
east-1-2:     8
east-1-3:    58 *
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
west-1-1:     4
west-1-10:   50 *
south-1-2:   30 *
</code>```

答:
I think you just need to put your last echo statement in the default of the switch, rather than after the switch. That way it will get executed when the rest of your switch-statement doesn't, instead of executing every time.

So:

```<code>case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
    *)
      echo "${cluster}:${getCount}";;
  esac
</code>```

Body:
I have a script that reads a main list, call it List A using a while loop.

List A:

east-1-1
east-1-2
east-1-3
east-1-4
east-1-5
east-1-6
east-1-7
west-1-1
west-1-10
south-1-1
south-1-2
north-1-1

What I would like to do is check it against this list:

east-1-1
east-1-3
east-1-7
west-1-10
south-1-2

As listed in my case and for each of those items in my case I would like to flag down with an *

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac

I am doing this within a function and using a case statement, however I think I'm doing this wrong and would like to know if there's a better way? Should I be using an if-then-else? Can I do this with the case?

If I could please get some help on this approach or if there's a better way to write this.

CODE IN PROGRESS:

#!/usr/local/bin/bash

MAP=./.clusterinfo
if ! [ -f "$MAP" ]; then
      echo "Cluster Map not found."
      exit 1
fi

while IFS='' read -r cluster; do
#Function runQuery
runQuery()
{
  getCount=$(PGPASSWORD=Abc123Pa55word psql -h myapp-"${cluster}".foobar.com -U foo -d dev -p 5439 -t -c "select count(*) from pg_database;")

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
    echo "${cluster}:${getCount}"
}

#Execute
runQuery

done < "$MAP"

Current Output:

east-1-1:    50 *
east-1-1:    50
east-1-2:     8
east-1-3:    58 *
east-1-3:    58
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
east-1-7:    30
west-1-1:     4
west-1-10:   50 *
west-1-10:   50
south-1-2:   30 *
south-1-2:   30

Expected Output:

east-1-1:    50 *
east-1-2:     8
east-1-3:    58 *
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
west-1-1:     4
west-1-10:   50 *
south-1-2:   30 *

Body:
I think you just need to put your last echo statement in the default of the switch, rather than after the switch. That way it will get executed when the rest of your switch-statement doesn't, instead of executing every time.

So:

case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
    *)
      echo "${cluster}:${getCount}";;
  esac


问:
By decreasing the windows size my header does this?
I was trying to create a website which has nav bar. But while coding navbar and testing i was facing issue and i observed that it was not responsive.so whenever i try to load the website in lower resolution nav bar was getting displaced from its original position to adjacent position vertically. Which was awkward as it seems in 1st image.

After Decreasing the window size navbar shift to below the image

Normal large window size

Here is the code. i have attached HTMl and CSS.

reference Video link -> https://www.youtube.com/watch?v=TTbYFzAz-Lg

I have tried to make responsive navbar.. but i'm not getting the behaviour of navbar when the window size deceases.

HTML

```<code><!DOCTYPE html>
<html>
    <head>
        <title>
            Responsive Navigation Bar
        </title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <meta name="viewport" content="width=device-width initial-scale=1">
    </head>
    <body>
        <div id="header">
            <div id="logo">
                <img src="Redbull-logo.png">
            </div>
            <ul id="navbar">
                <li><a href="#">Home</a></li>
                <li><a href="#">Service</a></li>
                <li><a href="#">Product</a></li>
                <li><a href="#">Contact</a></li>
                <li><a href="#">About</a></li>
            </ul>
        </div>
    </body>
</html>
</code>```

CSS

```<code>*{
    margin: 0px;
    padding: 0px;
}

body{
    background: skyblue;
}

#header{
    width: 100%;
    height: 80px;
    background: #333;
    box-shadow: 0px 3px 4px gray;
}

#navbar{
    width: 1000px;
    height: 80px;
    float: right;
}

#navbar > li{
    width: 198px;
    list-style: none;
    float: left;
    border-right: 1px solid gray;
    border-left: 1px solid gray;
}

li > a{
    display: block;
    color: white;
    line-height: 80px;
    text-align: center;
    font-family: cursive;
    font-size: 20px;
    text-decoration: none;
}

li > a:hover,
li > a:focus{
    background-color: skyblue;
    color: #333;
}

#logo{
    width: 200px;
    float: left;
    height: 80px;
    padding-left: 40px;
}
</code>```

答:
Basically what is happening is when you decrease the size of the screen there isn't enough room in the nav bar for all your links and also your image so it pushes it onto two lines, I would look into media queries so at certain widths things change like the size of your image and the size of your nav links.

An example of how this would work

```<code>@media (max-width: 1080px){
   navbar-links{
     font-size: 0.8em;
     padding: 0px 5px;
   }

   navbar-image{
     width: 500px;
   }
</code>```

Body:
I was trying to create a website which has nav bar. But while coding navbar and testing i was facing issue and i observed that it was not responsive.so whenever i try to load the website in lower resolution nav bar was getting displaced from its original position to adjacent position vertically. Which was awkward as it seems in 1st image.

After Decreasing the window size navbar shift to below the image

Normal large window size

Here is the code. i have attached HTMl and CSS.

reference Video link -> https://www.youtube.com/watch?v=TTbYFzAz-Lg

I have tried to make responsive navbar.. but i'm not getting the behaviour of navbar when the window size deceases.

HTML

<!DOCTYPE html>

        <title>
            Responsive Navigation Bar
        </title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <meta name="viewport" content="width=device-width initial-scale=1">

Home

Service

Product

Contact

About

CSS

*{
    margin: 0px;
    padding: 0px;
}

body{
    background: skyblue;
}

#header{
    width: 100%;
    height: 80px;
    background: #333;
    box-shadow: 0px 3px 4px gray;
}

#navbar{
    width: 1000px;
    height: 80px;
    float: right;
}

#navbar > li{
    width: 198px;
    list-style: none;
    float: left;
    border-right: 1px solid gray;
    border-left: 1px solid gray;
}

li > a{
    display: block;
    color: white;
    line-height: 80px;
    text-align: center;
    font-family: cursive;
    font-size: 20px;
    text-decoration: none;
}

li > a:hover,
li > a:focus{
    background-color: skyblue;
    color: #333;
}

#logo{
    width: 200px;
    float: left;
    height: 80px;
    padding-left: 40px;
}

Body:
Basically what is happening is when you decrease the size of the screen there isn't enough room in the nav bar for all your links and also your image so it pushes it onto two lines, I would look into media queries so at certain widths things change like the size of your image and the size of your nav links.

An example of how this would work

@media (max-width: 1080px){
   navbar-links{
     font-size: 0.8em;
     padding: 0px 5px;
   }

   navbar-image{
     width: 500px;
   }


问:
Python ORM for massive data set
I have a massive data set of customer information (100s of millions of records, 50+ tables).

I am writing a python (twisted) app that I would like to interact with the dataset, performing table manipulation.  What I really need is an abstraction of 'table', so I can add/remove/alter columns/tables without having to resort to only creating SQL.

Is there an ORM that will not add significant overhead to my application, considering the size of the dataset?

答:
If I'd have to pick the Python ORM, I would pick SQLAlchemy.

But with Twisted you have to be cautious since Twisted is asynchronous.

See: Twisted + SQLAlchemy and the best way to do it

Title: Python ORM for massive data set


问:
Merge rows together if : is present shell script
I have data in below format in a text file.

```<code>desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :
</code>```

I am trying to get the output in below format .

```<code>desc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management
ldesc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management (BCD-WQ-UIO, BCD-WQ-BN)
</code>```

Basically I want any row which has colon but nothing following a colon should be deleted and if any row doesn't have a colon it should be merged with previous row including space if any.

I tried using awk but I am unable to proceed.

Regards.

答:
Assume your file name exp1.txt

```<code>awk -F: 'length($2) { print $0 }' exp1.txt
</code>```

You will got your expect result!

my output:

```<code>(public)landpacks-MacBook-Pro:stackoverflow frank$ cat exp1.txt
desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :
(public)landpacks-MacBook-Pro:stackoverflow frank$ awk -F: 'length($2) { print $0 }' exp1.txt
desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
(public)landpacks-MacBook-Pro:stackoverflow frank$
</code>```

Body:
I have data in below format in a text file.

desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :

I am trying to get the output in below format .

desc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management
ldesc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management (BCD-WQ-UIO, BCD-WQ-BN)

Basically I want any row which has colon but nothing following a colon should be deleted and if any row doesn't have a colon it should be merged with previous row including space if any.

I tried using awk but I am unable to proceed.

Regards.

Body:
Assume your file name exp1.txt

awk -F: 'length($2) { print $0 }' exp1.txt

You will got your expect result!

my output:

(public)landpacks-MacBook-Pro:stackoverflow frank$ cat exp1.txt
desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :
(public)landpacks-MacBook-Pro:stackoverflow frank$ awk -F: 'length($2) { print $0 }' exp1.txt
desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
(public)landpacks-MacBook-Pro:stackoverflow frank$