问:
Assigning two tables separate css styles
Why is it that when I apply a style to one table it effects the other even though I've assigned them separate classes. Table two is being pushed down by table twos padding. Have a look at this demo I created. How can I avoid this?

```<code><table id="one">
    <tr>
      <td>Hello</td>
    </tr>
  </table>

  <table id="two">
    <tr>
      <td>Goodbye</td>
    </tr>
  </table>
</code>```

css:

```<code>table{
  display: inline-block;
}

#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}
</code>```

https://jsfiddle.net/b7qdcub1/

答:
you can use vertical align to for table Jsfiddle

table{
 display: inline-block;
 vertical-align:top;
}
#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <table id="one">
<tr>
  <td>Hello</td>
</tr>
  </table>

  <table id="two">
<tr>
  <td>Goodbye</td>
</tr>
  </table></code>```

Body:
Why is it that when I apply a style to one table it effects the other even though I've assigned them separate classes. Table two is being pushed down by table twos padding. Have a look at this demo I created. How can I avoid this?

      Hello

      Goodbye

css:

table{
  display: inline-block;
}

#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}

https://jsfiddle.net/b7qdcub1/

Body:
you can use vertical align to for table Jsfiddle

table{
 display: inline-block;
 vertical-align:top;
}
#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}

  <table id="one">
<tr>
  <td>Hello</td>
</tr>
  </table>

  <table id="two">
<tr>
  <td>Goodbye</td>
</tr>
  </table>


来源: stackexchange

问:
scp - transfer reports 100% complete (and is transferred), but file size is incorrect
I am using scp to transfer files between two linux systems - when the transfer finishes, the final print to screen from SCP shows the wrong file size:

```<code>vmtbackup.zip                                       100% 2613MB  17.5MB/s   02:29 .
</code>```

As you can see here, the final reported size is 2613MB and the transfer has completed. However the actual size of the file is 2741MB

When I check on the target system, the file has the correct size (so the transfer has completed successfully).

I am using the output from SCP as part of a script, and the check condition to finish the script is when the size in SCP = the size of the file (as the 100% is equally unreliable) - it's part of an expect script, which looks like this:

```<code>function Transfer {
/usr/bin/expect <<EOD
#transfers the vmtbackup.zip file from source system to target system

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no /tmp/vmtbackup.zip $user@$ip:/tmp/
expect {
#handles all unexpected outcomes. Primarily used to capture wrong

password, as no remote connection should be caught earlier in migration.sh
default {
send_user "\nERROR: I was unable to connect to $ip for some reason.  Please try again.\n"
exit 1
}
#passes the password defined in migration.sh to scp password prompt"
-re "root@$ip's \[pP\]assword:" {
send -- "$password\r"
exp_continue
}
-re "\[pP\]assword:" {
send -- "$password\r"
exp_continue
}
-re "ETA" {
exp_continue
}
#when file transfer reaches 100%, exits script
-re "$si" {
exit 0
}
EOD
}
</code>```

I'm aware of the security implications of using password in plaintext and that I should use SSL, but for now that's not part of the problem.

Can anyone tell me why SCP behaves in this way?

答:
scp incorrectly shows MB, which means the factor is 1000 * 1000. It should show MiB, which is factor 1024 * 1024:

```<code>2613 MiB == 2613 * (1024 * 1024) / (1000 * 1000) == 2739.929088 MB
</code>```

See IEEE 1541-2002 for details.

ContentLicense: CC BY-SA 3.0

Body:
I am using scp to transfer files between two linux systems - when the transfer finishes, the final print to screen from SCP shows the wrong file size:

vmtbackup.zip                                       100% 2613MB  17.5MB/s   02:29 .

As you can see here, the final reported size is 2613MB and the transfer has completed. However the actual size of the file is 2741MB

When I check on the target system, the file has the correct size (so the transfer has completed successfully).

I am using the output from SCP as part of a script, and the check condition to finish the script is when the size in SCP = the size of the file (as the 100% is equally unreliable) - it's part of an expect script, which looks like this:

function Transfer {
/usr/bin/expect <<EOD
#transfers the vmtbackup.zip file from source system to target system

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no /tmp/vmtbackup.zip $user@$ip:/tmp/
expect {
#handles all unexpected outcomes. Primarily used to capture wrong

password, as no remote connection should be caught earlier in migration.sh
default {
send_user "\nERROR: I was unable to connect to $ip for some reason.  Please try again.\n"
exit 1
}
#passes the password defined in migration.sh to scp password prompt"
-re "root@$ip's \[pP\]assword:" {
send -- "$password\r"
exp_continue
}
-re "\[pP\]assword:" {
send -- "$password\r"
exp_continue
}
-re "ETA" {
exp_continue
}
#when file transfer reaches 100%, exits script
-re "$si" {
exit 0
}
EOD
}

I'm aware of the security implications of using password in plaintext and that I should use SSL, but for now that's not part of the problem.

Can anyone tell me why SCP behaves in this way?

Body:
scp incorrectly shows MB, which means the factor is 1000 * 1000. It should show MiB, which is factor 1024 * 1024:

2613 MiB == 2613 * (1024 * 1024) / (1000 * 1000) == 2739.929088 MB

See IEEE 1541-2002 for details.


问:
Error on lambda operators in android
i want to write a code using Runnable method using lambda operators but i got an error of
Error:(40, 33) error: lambda expressions are not supported in -source 1.7
(use -source 8 or higher to enable lambda expressions)
Here is my code:`</p>

```<code>public void countDownStart(){
    handler= new Handler();
    runnable= (Runnable) () -> {
       handler.postDelayed((Runnable) this, 1000);
        try{
            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYY-MM-DD");
            Date futureDate= dateFormat.parse("2017-03-31");
            Date currentDate= new Date();
            if (!currentDate.after(futureDate)){
                long diff = futureDate.getTime()- currentDate.getTime();
                long days = diff / (24 * 60 * 60 * 1000);
                diff -= days * (24 * 60 * 60 * 1000);
                long hours = diff / (60 * 60 * 1000);
                diff -= hours * (60 * 60 * 1000);
                long minutes = diff / (60 * 1000);
                diff -= minutes * (60* 1000);
                long seconds = diff / 1000;
             txtTimerDay.setText("" + String.format("%02d", days));
             txtTimerHour.setText("" + String.format("%02d", hours));
             txtTimerMinute.setText("" + String.format("%02d", minutes));
             txtTimerSecond.setText("" + String.format("%02d", seconds));
            }else{
                tvEvent.setVisibility(View.VISIBLE);
                tvEvent.setText("The Event Started");
                textViewGone();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    };
    handler.postDelayed(runnable, 1 * 1000);
}
</code>```

答:
Have you added following instructions in your build.gradle file?</p>

```<code>defaultConfig {

    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
</code>```

Title: Error on lambda operators in android

Body:
i want to write a code using Runnable method using lambda operators but i got an error of
Error:(40, 33) error: lambda expressions are not supported in -source 1.7
(use -source 8 or higher to enable lambda expressions)
Here is my code:`

public void countDownStart(){
    handler= new Handler();
    runnable= (Runnable) () -> {
       handler.postDelayed((Runnable) this, 1000);
        try{
            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYY-MM-DD");
            Date futureDate= dateFormat.parse("2017-03-31");
            Date currentDate= new Date();
            if (!currentDate.after(futureDate)){
                long diff = futureDate.getTime()- currentDate.getTime();
                long days = diff / (24 * 60 * 60 * 1000);
                diff -= days * (24 * 60 * 60 * 1000);
                long hours = diff / (60 * 60 * 1000);
                diff -= hours * (60 * 60 * 1000);
                long minutes = diff / (60 * 1000);
                diff -= minutes * (60* 1000);
                long seconds = diff / 1000;
             txtTimerDay.setText("" + String.format("%02d", days));
             txtTimerHour.setText("" + String.format("%02d", hours));
             txtTimerMinute.setText("" + String.format("%02d", minutes));
             txtTimerSecond.setText("" + String.format("%02d", seconds));
            }else{
                tvEvent.setVisibility(View.VISIBLE);
                tvEvent.setText("The Event Started");
                textViewGone();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    };
    handler.postDelayed(runnable, 1 * 1000);
}

Body:
Have you added following instructions in your build.gradle file?

defaultConfig {

    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }


问:
DNS not resolved after reconfigure dns properly unless restart my script on centos
I have a python script which use rest-api to communicate with my server.

I am using python-requests to handle rest-api.

The script has a loop and try-except for handling errors to keep it running.

On centos, I accidentally mis-configured the dns and started my script.

Here is the error:

HTTPConnectionPool(host='host.com', port=80): Max retries exceeded with url: //rest/url (Caused by NewConnectionError(': Failed to establish a new connection: [Errno -2] Name or service not known',))

Then I reconfigured the dns properly without restarting the script, but the script still didn't work unless restart it. Same error.

Programs started after dns reconfiguration like ping, web browsers were working fine.

Same problem happens for ping if it is started before dns reconfiguration, but not for firefox.

It seems that firefox took a while to adapt new dns configuration.

On debian, this problem does't exist.

When I reconfigured the dns properly, the script or other programs started to work almost immediately.

Is there anything special with dns on centos?

Can my script adapt new dns configuration without restarting?

==========================

python-requests version I tested:

2.11.1, 2.12.4, 2.13.0 On centos

2.11.1, 2.12.4 on debian

centos version tested:

6.2, 7.3-1611

debian version tested:

debian-sid latest update

python version:

2.7.13rc1 on debian

2.7.5 on centos 7.3-1611

2.6.6 on centos 6.2

答:
problem solved by calling __res_init in glibc.

More details see Python not getting IP if cable connected after script has started  and http://bugs.sugarlabs.org/attachment/ticket/1940/network.py.patch


问:
jQuery - Conflict between datepicker and searchable dropdown plugins
On a page I have a drop down list with <select> and  an <input> form for the date.

The dropdown list:

```<code>echo "<td>";
        $sql = "SELECT DISTINCT userName FROM users";
        $result = mysqli_query($link, $sql);

        echo "<select id='myselect' name='userName'>";
        echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['userName'])) {
            echo "<option value='" . $row['userName'] . "'>" . $row['userName'] . "</option>";
            }
        }
        echo "</select>
        </td>
</code>```

The date  form:

```<code>        <td>
        <input type='text' class='datepicker' name='entryDate'>
        </td>
</code>```

For the date input form as you can see  I have a jQuery datepicker plugin, declared as follows:

```<code><script src='../jquery/jquery-1.12.4.js'></script>
<script src='../jquery/jquery-ui.js'></script>
<script>
    $(function() {
    $(".datepicker").datepicker({dateFormat:"yy-mm-dd"});
    });
</script>
</code>```

This worked just fine, but then I wanted to add a jQuery plugin to make the dropdown list searchable. I found this plugin and added it like this:

```<code><script type="text/javascript" src="../plugins/sh/shCore.js"></script>
<script type="text/javascript" src="../plugins/sh/shBrushJScript.js"></script>
<link type="text/css" rel="stylesheet" href="../plugins/sh/shCore.css"/>
<link type="text/css" rel="stylesheet" href="../plugins/sh/shThemeDefault.css"/>
<script type="text/javascript">
    SyntaxHighlighter.all();
</script>
<!-- END syntax highlighter -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="../plugins/jquery.searchabledropdown-1.0.8.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $("select").searchable();
    });

    // demo functions
    $(document).ready(function() {
        $("#value").html($("#myselect :selected").text() + " (VALUE: " + $("#myselect").val() + ")");
        $("select").change(function(){
            $("#value").html(this.options[this.selectedIndex].text + " (VALUE: " + this.value + ")");
        });
    });

    function modifySelect() {
        $("select").get(0).selectedIndex = 5;
    }

    function appendSelectOption(str) {
        $("select").append("<option value=\"" + str + "\">" + str + "</option>");
    }

    function applyOptions() {
        $("select").searchable({
            maxListSize: $("#maxListSize").val(),
            maxMultiMatch: $("#maxMultiMatch").val(),
            latency: $("#latency").val(),
            exactMatch: $("#exactMatch").get(0).checked,
            wildcards: $("#wildcards").get(0).checked,
            ignoreCase: $("#ignoreCase").get(0).checked
        });

        alert(
            "OPTIONS\n---------------------------\n" +
            "maxListSize: " + $("#maxListSize").val() + "\n" +
            "maxMultiMatch: " + $("#maxMultiMatch").val() + "\n" +
            "exactMatch: " + $("#exactMatch").get(0).checked + "\n"+
            "wildcards: " + $("#wildcards").get(0).checked + "\n" +
            "ignoreCase: " + $("#ignoreCase").get(0).checked + "\n" +
            "latency: " + $("#latency").val()
        );
    }
</script>
</code>```

After adding the searchable dropdown list plugin <select id='myselect' name='userName'> the dropdown list became searchable as expected, but the datepicker stopped working. I noticed that if I delete the declaration of the searchable dropdown list plugin from the html  the datepicker works again.

Is there any reason why these two plugins conflict? And any solution?

答:
Found the solution:

jQuery uses the $ sign as a shortcut for jQuery and this can cause conflicts with other scripts that also use the $ sign.

The solution comes from the jQuery noConflict() Method:

I replaced this:

```<code>$(function() {
    $(".datepicker").datepicker({dateFormat:'yy-mm-dd'});
    });
</code>```

With this:

```<code>$.noConflict();
jQuery(document).ready(function($){
$(function() {
    $(".datepicker").datepicker({dateFormat:'yy-mm-dd'});
    });
});
</code>```

For more details on noConflict method: noConflict Method

Body:
On a page I have a drop down list with <select> and  an <input> form for the date.

The dropdown list:

echo "";
        $sql = "SELECT DISTINCT userName FROM users";
        $result = mysqli_query($link, $sql);

        echo "<select id='myselect' name='userName'>";
        echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['userName'])) {
            echo "<option value='" . $row['userName'] . "'>" . $row['userName'] . "</option>";
            }
        }
        echo "</select>

The date  form:

        <input type='text' class='datepicker' name='entryDate'>

For the date input form as you can see  I have a jQuery datepicker plugin, declared as follows:

This worked just fine, but then I wanted to add a jQuery plugin to make the dropdown list searchable. I found this plugin and added it like this:

<link type="text/css" rel="stylesheet" href="../plugins/sh/shCore.css"/>
<link type="text/css" rel="stylesheet" href="../plugins/sh/shThemeDefault.css"/>

After adding the searchable dropdown list plugin <select id='myselect' name='userName'> the dropdown list became searchable as expected, but the datepicker stopped working. I noticed that if I delete the declaration of the searchable dropdown list plugin from the html  the datepicker works again.

Is there any reason why these two plugins conflict? And any solution?

Body:
Found the solution:

jQuery uses the $ sign as a shortcut for jQuery and this can cause conflicts with other scripts that also use the $ sign.

The solution comes from the jQuery noConflict() Method:

I replaced this:

$(function() {
    $(".datepicker").datepicker({dateFormat:'yy-mm-dd'});
    });

With this:

$.noConflict();
jQuery(document).ready(function($){
$(function() {
    $(".datepicker").datepicker({dateFormat:'yy-mm-dd'});
    });
});

For more details on noConflict method: noConflict Method


问:
Excel ActiveX Listbox not responding after making it invisible then visible
Can I have opinions please?

I have a panel of user setting options hosted in ActiveX controls. Users make a selection and click a button. This hides the panel and presents results. Another button deletes the results and makes visible again the panel of ActiveX objects

Hiding works, but when the ActiveX objects are made visible again Listbox ActiveX controls (not others) no longer function, as if I am in Design Mode. I get this problem in Excel 2013, it was working in Excel 2010.

I have seen similar issues solved with MS Office updates, but I don't have the exact symptoms they describe. I don't expect I can persuade my IT department to role out MSOffice updates, if necessary, workarounds are welcome.

Code snip-its below. If i comment this out this section of the hide sub the problem doesn't occur.

```<code>Sub HideFilters()

...

For Each shp In ActiveSheet.Shapes
    If Left(shp.Name, Len("AutoShape_Index_")) <> "AutoShape_Index_" Then
        If Left(shp.Name, Len("Gant_btn")) <> "Gant_btn" Then
            shp.Visible = False
        End If
    End If
Next

'''

End Sub

Sub ShowFilters()

...

For Each shp In ActiveSheet.Shapes
    If Left(shp.Name, Len("AutoShape_Index_")) <> "AutoShape_Index_" Then
        If Left(shp.Name, Len("Gant_btn")) <> "Gant_btn" Then
            shp.Visible = True
        End If
    End If
Next

...

End Sub
</code>```

答:
When I try the code below it unhides all Active-X Controls that their name doesn't start with "AutoShape_Index_" or "Gant_btn" , in my ActiveSheet (not recommended).

```<code>Option Explicit

Sub ShowFilters()

Dim Shp As Shape

For Each Shp In ActiveSheet.Shapes
    If Not Shp.Name Like "AutoShape_Index_*" And Not Shp.Name Like "Gant_btn*" Then
        Shp.Visible = True
    End If
Next

End Sub
</code>```

Body:
Can I have opinions please?

I have a panel of user setting options hosted in ActiveX controls. Users make a selection and click a button. This hides the panel and presents results. Another button deletes the results and makes visible again the panel of ActiveX objects

Hiding works, but when the ActiveX objects are made visible again Listbox ActiveX controls (not others) no longer function, as if I am in Design Mode. I get this problem in Excel 2013, it was working in Excel 2010.

I have seen similar issues solved with MS Office updates, but I don't have the exact symptoms they describe. I don't expect I can persuade my IT department to role out MSOffice updates, if necessary, workarounds are welcome.

Code snip-its below. If i comment this out this section of the hide sub the problem doesn't occur.

Sub HideFilters()

...

For Each shp In ActiveSheet.Shapes
    If Left(shp.Name, Len("AutoShape_Index_")) <> "AutoShape_Index_" Then
        If Left(shp.Name, Len("Gant_btn")) <> "Gant_btn" Then
            shp.Visible = False
        End If
    End If
Next

'''

End Sub

Sub ShowFilters()

...

For Each shp In ActiveSheet.Shapes
    If Left(shp.Name, Len("AutoShape_Index_")) <> "AutoShape_Index_" Then
        If Left(shp.Name, Len("Gant_btn")) <> "Gant_btn" Then
            shp.Visible = True
        End If
    End If
Next

...

End Sub

Body:
When I try the code below it unhides all Active-X Controls that their name doesn't start with "AutoShape_Index_" or "Gant_btn" , in my ActiveSheet (not recommended).

Option Explicit

Sub ShowFilters()

Dim Shp As Shape

For Each Shp In ActiveSheet.Shapes
    If Not Shp.Name Like "AutoShape_Index_*" And Not Shp.Name Like "Gant_btn*" Then
        Shp.Visible = True
    End If
Next

End Sub


问:
Can you better explain the semantics of TestNG's @BeforeTest annotation?
I read the relevant documentation and didn't understand it. See also this question.</p>

答:
To understand that, you must understand testng.xml. Now reread the same thing,

The annotated method will be run
  before any test method belonging to
  the classes inside the <test> tag is
  run.

It should be clear that this annotation will only work with the methods those belong to the classes defined under <test> tag in testng.xml.

ContentLicense: CC BY-SA 2.5


问:
Query Filter Django
I want to call nilai into a table in my template. This is my model:

```<code>class AlternatifJalur(models.Model):
    nama = models.CharField(max_length=100)
    def __str__(self):
        return self.nama

class KriteriaJalur(models.Model):
    TIPE_KRITERIA_CHOICES = (
        ('benefit', 'Benefit'),
        ('cost', 'Cost'),
    )
    nama = models.CharField(max_length=100)
    bobot = models.DecimalField(max_digits = 20, decimal_places = 2)
    keterangan = models.TextField()
    tipe = models.CharField(max_length=100, choices=TIPE_KRITERIA_CHOICES, default='Benefit')

    def __str__(self):
        return self.nama

class Matriks(models.Model):
    kriteria = models.ForeignKey(KriteriaJalur)
    alternatif = models.ForeignKey(AlternatifJalur)
    nilai = models.DecimalField(max_digits = 20, decimal_places = 2)

    def nilai_float(self):
        return float(self.nilai)
</code>```

This is my view :

```<code>def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()
    matriks = Matriks.objects.all()
    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})
</code>```

How can I call nilai from the Matriks class in my model so that kriteria in my Matriks class is equal to nama in my kriteria class and alternatif in my Matriks class is equal to nama in my alternatif class ?

答:
This is the table picture

in column 'Kriteria A' and field 'Jalur A', will be appear matrik.nilai where alternatif = 'Jalur A' and kriteria='Kriteria A'

@nik_m

Title: Query Filter Django

Body:
I want to call nilai into a table in my template. This is my model:

class AlternatifJalur(models.Model):
    nama = models.CharField(max_length=100)
    def __str__(self):
        return self.nama

class KriteriaJalur(models.Model):
    TIPE_KRITERIA_CHOICES = (
        ('benefit', 'Benefit'),
        ('cost', 'Cost'),
    )
    nama = models.CharField(max_length=100)
    bobot = models.DecimalField(max_digits = 20, decimal_places = 2)
    keterangan = models.TextField()
    tipe = models.CharField(max_length=100, choices=TIPE_KRITERIA_CHOICES, default='Benefit')

    def __str__(self):
        return self.nama

class Matriks(models.Model):
    kriteria = models.ForeignKey(KriteriaJalur)
    alternatif = models.ForeignKey(AlternatifJalur)
    nilai = models.DecimalField(max_digits = 20, decimal_places = 2)

    def nilai_float(self):
        return float(self.nilai)

This is my view :

def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()
    matriks = Matriks.objects.all()
    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})

How can I call nilai from the Matriks class in my model so that kriteria in my Matriks class is equal to nama in my kriteria class and alternatif in my Matriks class is equal to nama in my alternatif class ?


问:
Kubernetes Job Cleanup
From what I understand the Job object is supposed to reap pods after a certain amount of time.
But on my GKE cluster (Kubernetes 1.1.8) it seems that "kubectl get pods -a" can list pods from days ago.

All were created using the Jobs API.

I did notice that after delete the job with
    kubectl delete jobs
The pods were deleted too.

My main concern here is that I am going to run thousands and tens of thousands of pods on the cluster in batch jobs, and don't want to overload the internal backlog system.

答:
It looks like starting with Kubernetes 1.6 (and the v2alpha1 api version), if you're using cronjobs to create the jobs (that, in turn, create your pods), you'll be able to limit how many old jobs are kept.  Just add the following to your job spec:

```<code>successfulJobsHistoryLimit: X
failedJobsHistoryLimit: Y
</code>```

Where X and Y are the limits of how many previously run jobs the system should keep around (it keeps jobs around indefinitely by default [at least on version 1.5.])

Edit 2018-09-29:

For newer K8S versions, updated links with documentation for this are here:

CronJob - Job History Limits

CronJob API Spec

Title: Kubernetes Job Cleanup

Body:
It looks like starting with Kubernetes 1.6 (and the v2alpha1 api version), if you're using cronjobs to create the jobs (that, in turn, create your pods), you'll be able to limit how many old jobs are kept.  Just add the following to your job spec:

successfulJobsHistoryLimit: X
failedJobsHistoryLimit: Y

Where X and Y are the limits of how many previously run jobs the system should keep around (it keeps jobs around indefinitely by default [at least on version 1.5.])

Edit 2018-09-29:

For newer K8S versions, updated links with documentation for this are here:

CronJob - Job History Limits

CronJob API Spec

ContentLicense: CC BY-SA 4.0


问:
curl with data encode url in R
data-encode-url in R

```<code>curl "https://www.zopim.com/api/v2/chats/search" \
-G --data-urlencode "q=timestamp:[2016-02-02T16:00:00 TO *] \
-v -u {email_address}:{password}
</code>```

How to convert --data-urlencode this in R?

This is what I have so far: without the search part

```<code>  chats <<- getURL('https://www.zopim.com/api/v2/chats/', verbose = TRUE, userpwd = "username:pwd", httpauth = 1L)
</code>```

where and how to add

```<code>--data-urlencode "q=timestamp:[2016-02-02T16:00:00 TO *]
</code>```

in R?

答:
```<code>library(httr)

GET(
  "https://www.zopim.com/api/v2/chats/search",
  query=list(
    q="timestamp:[2016-02-02T16:00:00 TO *] AND rating:good"
  ),
  authenticate("you@example.com", "yourpassword"),
  verbose()
) -> result

content(result, as="parsed")
## $results
## list()
##
## $count
## [1] 0
##
## $prev_url
## NULL
##
## $next_url
## NULL
</code>```

Remove the verbose() in production.

Title: curl with data encode url in R

Body:
data-encode-url in R

curl "https://www.zopim.com/api/v2/chats/search" \
-G --data-urlencode "q=timestamp:[2016-02-02T16:00:00 TO *] \
-v -u {email_address}:{password}

How to convert --data-urlencode this in R?

This is what I have so far: without the search part

  chats <<- getURL('https://www.zopim.com/api/v2/chats/', verbose = TRUE, userpwd = "username:pwd", httpauth = 1L)

where and how to add

--data-urlencode "q=timestamp:[2016-02-02T16:00:00 TO *]

in R?

Body:
library(httr)

GET(
  "https://www.zopim.com/api/v2/chats/search",
  query=list(
    q="timestamp:[2016-02-02T16:00:00 TO *] AND rating:good"
  ),
  authenticate("you@example.com", "yourpassword"),
  verbose()
) -> result

content(result, as="parsed")
## $results
## list()
##
## $count
## [1] 0
##
## $prev_url
## NULL
##
## $next_url
## NULL

Remove the verbose() in production.


问:
Using curl POST with variables defined in bash script functions
When I echo I get this, which runs when I enter it into the terminal

```<code>curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data '{"account":{"email":"akdgdtk@test.com","screenName":"akdgdtk","type":"NIKE","passwordSettings":{"password":"Starwars1","passwordConfirm":"Starwars1"}},"firstName":"Test","lastName":"User","middleName":"ObiWan","locale":"en_US","registrationSiteId":"520","receiveEmail":"false","dateOfBirth":"1984-12-25","mobileNumber":"9175555555","gender":"male","fuelActivationDate":"2010-10-22","postalCode":"10022","country":"US","city":"Beverton","state":"OR","bio":"This is a test user","jpFirstNameKana":"unsure","jpLastNameKana":"ofthis","height":"80","weight":"175","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}' https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx
</code>```

But when run in the bash script file, I get this error

```<code>curl: (6) Could not resolve host: application; nodename nor servname provided, or not known
curl: (6) Could not resolve host: is; nodename nor servname provided, or not known
curl: (6) Could not resolve host: a; nodename nor servname provided, or not known
curl: (6) Could not resolve host: test; nodename nor servname provided, or not known
curl: (3) [globbing] unmatched close brace/bracket at pos 158
</code>```

this is the code in the file

```<code>curl -i \
-H '"'Accept: application/json'"' \
-H '"'Content-Type:application/json'"' \
-X POST --data "'"'{"account":{"email":"'$email'","screenName":"'$screenName'","type":"'$theType'","passwordSettings":{"password":"'$password'","passwordConfirm":"'$password'"}},"firstName":"'$firstName'","lastName":"'$lastName'","middleName":"'$middleName'","locale":"'$locale'","registrationSiteId":"'$registrationSiteId'","receiveEmail":"'$receiveEmail'","dateOfBirth":"'$dob'","mobileNumber":"'$mobileNumber'","gender":"'$gender'","fuelActivationDate":"'$fuelActivationDate'","postalCode":"'$postalCode'","country":"'$country'","city":"'$city'","state":"'$state'","bio":"'$bio'","jpFirstNameKana":"'$jpFirstNameKana'","jpLastNameKana":"'$jpLastNameKana'","height":"'$height'","weight":"'$weight'","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}'"'" "https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx"
</code>```

I assume there's an issue with my quotation marks, but I've played with them a lot and I've gotten similar errors.  All the variables are defined with different functions in the actual script

答:
Solution tested with https://httpbin.org/ and inline bash script

1. For variables without spaces in it i.e. 1:

Simply add ' before and after $variable when replacing desired
    string

```<code>for i in {1..3}; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"number":"'$i'"}' "https://httpbin.org/post"; \
done
</code>```

2. For input with spaces:

 Wrap variable with additional " i.e. "el a":

```<code>declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done
</code>```

Wow works :)

Body:
When I echo I get this, which runs when I enter it into the terminal

curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data '{"account":{"email":"akdgdtk@test.com","screenName":"akdgdtk","type":"NIKE","passwordSettings":{"password":"Starwars1","passwordConfirm":"Starwars1"}},"firstName":"Test","lastName":"User","middleName":"ObiWan","locale":"en_US","registrationSiteId":"520","receiveEmail":"false","dateOfBirth":"1984-12-25","mobileNumber":"9175555555","gender":"male","fuelActivationDate":"2010-10-22","postalCode":"10022","country":"US","city":"Beverton","state":"OR","bio":"This is a test user","jpFirstNameKana":"unsure","jpLastNameKana":"ofthis","height":"80","weight":"175","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}' https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx

But when run in the bash script file, I get this error

curl: (6) Could not resolve host: application; nodename nor servname provided, or not known
curl: (6) Could not resolve host: is; nodename nor servname provided, or not known
curl: (6) Could not resolve host: a; nodename nor servname provided, or not known
curl: (6) Could not resolve host: test; nodename nor servname provided, or not known
curl: (3) [globbing] unmatched close brace/bracket at pos 158

this is the code in the file

curl -i \
-H '"'Accept: application/json'"' \
-H '"'Content-Type:application/json'"' \
-X POST --data "'"'{"account":{"email":"'$email'","screenName":"'$screenName'","type":"'$theType'","passwordSettings":{"password":"'$password'","passwordConfirm":"'$password'"}},"firstName":"'$firstName'","lastName":"'$lastName'","middleName":"'$middleName'","locale":"'$locale'","registrationSiteId":"'$registrationSiteId'","receiveEmail":"'$receiveEmail'","dateOfBirth":"'$dob'","mobileNumber":"'$mobileNumber'","gender":"'$gender'","fuelActivationDate":"'$fuelActivationDate'","postalCode":"'$postalCode'","country":"'$country'","city":"'$city'","state":"'$state'","bio":"'$bio'","jpFirstNameKana":"'$jpFirstNameKana'","jpLastNameKana":"'$jpLastNameKana'","height":"'$height'","weight":"'$weight'","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}'"'" "https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx"

I assume there's an issue with my quotation marks, but I've played with them a lot and I've gotten similar errors.  All the variables are defined with different functions in the actual script

Body:
Solution tested with https://httpbin.org/ and inline bash script

1. For variables without spaces in it i.e. 1:

Simply add ' before and after $variable when replacing desired
    string

for i in {1..3}; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"number":"'$i'"}' "https://httpbin.org/post"; \
done

2. For input with spaces:

 Wrap variable with additional " i.e. "el a":

declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done

Wow works :)


问:
Segmentation fault when accessing array via pointer
I have a global array declared as

```<code>int Team1[12][8];
</code>```

When I call the function

```<code>int readLineupB(int teamNr){

      int (*teamToRead)[12][8];
      teamToRead = &Team1;

      for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            *teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 1;
}
</code>```

it fills the array until position [10],[3], then seemingly for [10],[4] I get a segmentation fault, and I cannot understand why.

答:
Another option is to forgo the pointer to 2-dimensional array, and just use pointer to (first of array of) one-dimensional array:</p>

```<code>int Team1[12][8];

int readLineupB(int teamNr){
    // declare teamToRead as a pointer to array of 8 ints
    int (*teamToRead)[8];

    // Team1 is of type int x[12][8] that readily decays
    // to int (*x)[8]
    teamToRead = Team1;

    for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            // no dereference here.
            teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 0;
}
</code>```

Body:
I have a global array declared as

int Team1[12][8];

When I call the function

int readLineupB(int teamNr){

      int (*teamToRead)[12][8];
      teamToRead = &Team1;

      for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            *teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 1;
}

it fills the array until position [10],[3], then seemingly for [10],[4] I get a segmentation fault, and I cannot understand why.

Body:
Another option is to forgo the pointer to 2-dimensional array, and just use pointer to (first of array of) one-dimensional array:

int Team1[12][8];

int readLineupB(int teamNr){
    // declare teamToRead as a pointer to array of 8 ints
    int (*teamToRead)[8];

    // Team1 is of type int x[12][8] that readily decays
    // to int (*x)[8]
    teamToRead = Team1;

    for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            // no dereference here.
            teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 0;
}


问:
string.compare and string for comparison
I have my code like this

```<code>private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }
</code>```

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

答:
try this:</p>

```<code>if (string.Compare((string) cmbOperations.SelectedItem,
        "NonForeignKeyTables", true) == 0) // 0 result means same
    GetNonForeignKeyTables();
</code>```

Body:
I have my code like this

private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

Body:
try this:

if (string.Compare((string) cmbOperations.SelectedItem,
        "NonForeignKeyTables", true) == 0) // 0 result means same
    GetNonForeignKeyTables();


问:
How to declare different functions in different conditions?

Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

```<code>// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}
</code>```

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.

答:
You could use a function expression and assign the needed function to a variable.</p>

```<code>var doSomething = condition ?
        function () { alert("Hi!"); } :
        function () { alert("Yo!"); };
</code>```

Body:
Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.

Body:
You could use a function expression and assign the needed function to a variable.

var doSomething = condition ?
        function () { alert("Hi!"); } :
        function () { alert("Yo!"); };


问:
Changing the request XML in Load Script
I have a soapui project for a big IT-System which offers hundreds of Webservice, only some of the webservice are in my project. Everytime I add a new WSDL to my project, I have to do a lot of monkey work to adjust the xml for the request (like adding placeholder for properties, removing comments, replace questionmarks....).

I thought I could easily write a "Load Script" for the project in which I register some Listener, and everytime a new request is added the script will fetch the xml-request from the new request-object, change it and save it back. But I failed, because I have no clue how to even get the xml from the request.

This is how far I got:

import com.eviware.soapui.SoapUI
import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.impl.wsdl.WsdlRequest
import com.eviware.soapui.impl.wsdl.WsdlContentPart
import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext
import com.eviware.soapui.support.XmlHolder

final logger = log
SoapUI.log.info("Load Script executet")
for(Interface i : project.getInterfaceList()){
    i.addInterfaceListener(new RequestAddListener())
}

project.addProjectListener(new ProjectListenerAdapter(){
    public void interfaceAdded(Interface i){
        SoapUI.log.info("Interface added: "+ i.getName())
        i.addInterfaceListener(new RequestAddListener())
    }
})

public class RequestAddListener extends InterfaceListenerAdapter {
    public void requestAdded(Request r) {
        if(r instanceof WsdlRequest){
            WsdlRequest request = (WsdlRequest) r
            SoapUI.log.info("Request added: "+request.getName())
            // here i want to retrieve the xml-request from the request-object,
            // do something with it, and set it back to the request-object.
        }
    }
}
```

I looked in every property of the WsdlRequest-Instance and could not find any XML. I tried to create a context (load Script does not provide a context instance) and somehow get the XmlHolder from it, but failed (Unexpected element: CDATA). All examples I found, where run in a TestCase/Step and I was not able to transfer them to the Load Script of the project.

Can someone help me?

Edit:

I want to change the request-data of new request (4. in the picture) to the example above (3. in the picture). I thought, I could solve it by using the load script of the project (2. in the picture). My approach was to register a InterfaceListener in every Interface and react to the creation of new Requests (method requestAdded). This works, but I did not found a way to retrieve the request-data from the request-object.

答:
Neither it is possible to access request in requestAdded() method, nor it is possible to assign a request by user.

It is learnt after debugging into SoapUI's code, it is not possible to read the request in the implementation of requestAdded method of interface InterfaceListener.

requestAdded() method is fired as soon as user click on New Request and at that time, the request content is empty / null.

Later, SoapUI will assign the request by creating a new one and then the request is being shown to the user.

However, you may try to write an individual groovy script to achieve the same once you create the requests.

Title: Changing the request XML in Load Script

Body:
I have a soapui project for a big IT-System which offers hundreds of Webservice, only some of the webservice are in my project. Everytime I add a new WSDL to my project, I have to do a lot of monkey work to adjust the xml for the request (like adding placeholder for properties, removing comments, replace questionmarks....).

I thought I could easily write a "Load Script" for the project in which I register some Listener, and everytime a new request is added the script will fetch the xml-request from the new request-object, change it and save it back. But I failed, because I have no clue how to even get the xml from the request.

This is how far I got:

import com.eviware.soapui.SoapUI
import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.impl.wsdl.WsdlRequest
import com.eviware.soapui.impl.wsdl.WsdlContentPart
import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext
import com.eviware.soapui.support.XmlHolder

final logger = log
SoapUI.log.info("Load Script executet")
for(Interface i : project.getInterfaceList()){
    i.addInterfaceListener(new RequestAddListener())
}

project.addProjectListener(new ProjectListenerAdapter(){
    public void interfaceAdded(Interface i){
        SoapUI.log.info("Interface added: "+ i.getName())
        i.addInterfaceListener(new RequestAddListener())
    }
})

public class RequestAddListener extends InterfaceListenerAdapter {
    public void requestAdded(Request r) {
        if(r instanceof WsdlRequest){
            WsdlRequest request = (WsdlRequest) r
            SoapUI.log.info("Request added: "+request.getName())
            // here i want to retrieve the xml-request from the request-object,
            // do something with it, and set it back to the request-object.
        }
    }
}

I looked in every property of the WsdlRequest-Instance and could not find any XML. I tried to create a context (load Script does not provide a context instance) and somehow get the XmlHolder from it, but failed (Unexpected element: CDATA). All examples I found, where run in a TestCase/Step and I was not able to transfer them to the Load Script of the project.

Can someone help me?

Edit:

I want to change the request-data of new request (4. in the picture) to the example above (3. in the picture). I thought, I could solve it by using the load script of the project (2. in the picture). My approach was to register a InterfaceListener in every Interface and react to the creation of new Requests (method requestAdded). This works, but I did not found a way to retrieve the request-data from the request-object.


问:
Keeping the script running when closing the window and opening a text editor in Python
As we all know April fools is coming so i tought i would write a nice script to prank someone, a harmless version of the well known and feared MEMZ Virus.

The Script i have currently:

```<code>import webbrowser
import time

def program():
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)

def main():
    pass

if __name__ == "__main__":
    main()
</code>```

What i want is to be able to open a text editor with text just like in the real virus.
A windows error box would be fine to. Also i dont want the prompt. so a way to close the prompt without ending the script would be nice.

Anyone got some ideas?

Thank you in advance.

Natan.

EDIT: My victim's Computer has Windows.

EDIT2:
I have updated the script:

```<code>import webbrowser
import ctypes
import time

MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_EXLAIM = 0x30
ICON_INFO = 0x40
ICON_STOP = 0x10
ICON_QUES = 0x20

def program():
    ctypes.windll.user32.MessageBoxW(0, "Your computer is fucked by the MEMZ Trojan, good luck trying to keep using it.", "GET REKT, DABBBB", MB_OK | ICON_INFO)
    time.sleep(2)
    ctypes.windll.user32.MessageBoxW(0, "BTW if you shut down your computer you wont be able to start it back up.", "Almost forgot....", MB_OK | ICON_INFO)
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)
    ctypes.windll.user32.MessageBoxW(0, "Still using this computer?", "Hell is that way", MB_OK | ICON_QUES)
    time.sleep(17)
    url = "https://www.gottabemobile.com/black-ops-3-cheats-hacks-things-to-know/"
    webbrowser.open(url, new=new)
    time.sleep(12)
    url = "https://thepiratebay.org/"
    webbrowser.open(url, new=new)
    time.sleep(32)
    url = "http://stackoverflow.com/questions/43114927/keeping-the-script-running-when-closing-the-window-and-opening-a-text-editor-in"
    webbrowser.open(url, new=new)
    ctypes.windll.user32.MessageBoxW(0, "Trololol. Fijne 1 april nog Justus! Groetjes Natan!", "April fools", MB_OK | ICON_INFO)

def main():
    program()

if __name__ == "__main__":
    main()
</code>```

答:
you can try in-built library ctypes to bring a pop-up on the screen.

```<code>import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
</code>```

Hope this helps.

you can actually use pythonw.exe file instead of python.exe
Try this link -  I haven't tried this thing but hopes it will help you for sure in hiding window console.

you have to simply change your python file extension from file.py to file.pyw
and its done No windows console will show up.

Body:
As we all know April fools is coming so i tought i would write a nice script to prank someone, a harmless version of the well known and feared MEMZ Virus.

The Script i have currently:

import webbrowser
import time

def program():
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)

def main():
    pass

if __name__ == "__main__":
    main()

What i want is to be able to open a text editor with text just like in the real virus.
A windows error box would be fine to. Also i dont want the prompt. so a way to close the prompt without ending the script would be nice.

Anyone got some ideas?

Thank you in advance.

Natan.

EDIT: My victim's Computer has Windows.

EDIT2:
I have updated the script:

import webbrowser
import ctypes
import time

MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_EXLAIM = 0x30
ICON_INFO = 0x40
ICON_STOP = 0x10
ICON_QUES = 0x20

def program():
    ctypes.windll.user32.MessageBoxW(0, "Your computer is fucked by the MEMZ Trojan, good luck trying to keep using it.", "GET REKT, DABBBB", MB_OK | ICON_INFO)
    time.sleep(2)
    ctypes.windll.user32.MessageBoxW(0, "BTW if you shut down your computer you wont be able to start it back up.", "Almost forgot....", MB_OK | ICON_INFO)
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)
    ctypes.windll.user32.MessageBoxW(0, "Still using this computer?", "Hell is that way", MB_OK | ICON_QUES)
    time.sleep(17)
    url = "https://www.gottabemobile.com/black-ops-3-cheats-hacks-things-to-know/"
    webbrowser.open(url, new=new)
    time.sleep(12)
    url = "https://thepiratebay.org/"
    webbrowser.open(url, new=new)
    time.sleep(32)
    url = "http://stackoverflow.com/questions/43114927/keeping-the-script-running-when-closing-the-window-and-opening-a-text-editor-in"
    webbrowser.open(url, new=new)
    ctypes.windll.user32.MessageBoxW(0, "Trololol. Fijne 1 april nog Justus! Groetjes Natan!", "April fools", MB_OK | ICON_INFO)

def main():
    program()

if __name__ == "__main__":
    main()

Body:
you can try in-built library ctypes to bring a pop-up on the screen.

import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Hope this helps.

you can actually use pythonw.exe file instead of python.exe
Try this link -  I haven't tried this thing but hopes it will help you for sure in hiding window console.

you have to simply change your python file extension from file.py to file.pyw
and its done No windows console will show up.


问:
reading json like variable in ansible
I'm new to ansible and I'm having a problem reading a value from json file in ansible role. my variable has a value like the following:

```<code>{
  "queue": {
    "first": {
      "car": "bmw",
      "year": "1990",
      "model": "x3",
      "color": "blue"
    },
    "second": {
      "car": "bmw",
      "year": "2000",
      "model": "318",
      "color": "red"
    }
  }
}
</code>```

I'm trying to print the color's value only to compare it with some other variable. I used with_dict to iterate over the json object (stored in variable called jsonVar) like the following:

```<code>- name: test loop
  with_dict: "{{jsonVar}}"
  shell:  |
        if echo "blue" | grep -q "${{item.value.color}}" ; then
           echo "success"
</code>```

so far there is no luck in getting the comparison of color's value from json to "blue" from the if statement. I was wondering if I'm doing something wrong?
thanks in advance!

答:
You can use the | json_query filter.

http://docs.ansible.com/ansible/playbooks_filters.html#json-query-filter

But make sure the file you are inputting is also in appropriate format,if not then you can use two filter, first one to convert into appropriate filter and second one to perform json query.

ex:- {{ variable_name | from_json | json_query('')}}

In you case, I think this would help:

```<code>tasks: print the color
set_fact:
  color1 : "{{ jsonVar | from_json | json_query('queue.[0].['color']')}}"
  color2 : "{{ jsonVar | from_json | json_query('queue.[1].['color']')}}"
</code>```

But make note of the requirements like Ansible version

Title: reading json like variable in ansible

Body:
I'm new to ansible and I'm having a problem reading a value from json file in ansible role. my variable has a value like the following:

{
  "queue": {
    "first": {
      "car": "bmw",
      "year": "1990",
      "model": "x3",
      "color": "blue"
    },
    "second": {
      "car": "bmw",
      "year": "2000",
      "model": "318",
      "color": "red"
    }
  }
}

I'm trying to print the color's value only to compare it with some other variable. I used with_dict to iterate over the json object (stored in variable called jsonVar) like the following:

- name: test loop
  with_dict: "{{jsonVar}}"
  shell:  |
        if echo "blue" | grep -q "${{item.value.color}}" ; then
           echo "success"

so far there is no luck in getting the comparison of color's value from json to "blue" from the if statement. I was wondering if I'm doing something wrong?
thanks in advance!

Body:
You can use the | json_query filter.

http://docs.ansible.com/ansible/playbooks_filters.html#json-query-filter

But make sure the file you are inputting is also in appropriate format,if not then you can use two filter, first one to convert into appropriate filter and second one to perform json query.

ex:- {{ variable_name | from_json | json_query('')}}

In you case, I think this would help:

tasks: print the color
set_fact:
  color1 : "{{ jsonVar | from_json | json_query('queue.[0].['color']')}}"
  color2 : "{{ jsonVar | from_json | json_query('queue.[1].['color']')}}"

But make note of the requirements like Ansible version


问:
How to fix a white gap after Bootstrap 4 Cards (CSS3 multi-columns bug)(Chrome IE )?
I have very annoying bug on Chrome and IE (On Fire Fox it looks fine). I am not really sure what element or elements are doing this.

About the bug:  If you scroll down, you can see where the Bootstrap cards end a big white gap between them and the footer.

URL where the bug is: I have to remove my URL (Stackoverflow rules...sorry guys)

I have been using Google Chrome Inspect to try to find where the problem is but I did not have luck. That is the reason why I am asking here because I can see where the problem is.

The only clues I have are:
-   The bug is not in any JS file or in any extern css file, I think there is something in my CSS is doing this.
-   It is not the position:relative or the overflow:hidden form the class dtl24, because I have tried to delete them and updated my CSS without them and the bug was still there.

Also, I would like to apologize to you. I have tried to create a snippet with the code but without the images, the bug not appreciable.

Do you know where is the bug and how I could fix it please?

Thanks

答:
This is a known issue with CSS3 multi-columns that can cause a gap at the bottom. There are only workarounds for this issue, and depend on the specific layout.

You can try using...

```<code>.card-columns .card {
    display: flex;
    page-break-inside: avoid;
    break-inside: avoid;
}
</code>```

But, you may need to ultimately use a large negative margin at the bottom of the container for Chrome / Webkit browsers:

```<code>.card-columns {
   -webkit-margin-after: -300px;
   overflow: hidden;
}
</code>```

Body:
This is a known issue with CSS3 multi-columns that can cause a gap at the bottom. There are only workarounds for this issue, and depend on the specific layout.

You can try using...

.card-columns .card {
    display: flex;
    page-break-inside: avoid;
    break-inside: avoid;
}

But, you may need to ultimately use a large negative margin at the bottom of the container for Chrome / Webkit browsers:

.card-columns {
   -webkit-margin-after: -300px;
   overflow: hidden;
}


问:
DevExpress XrChart curve prints to PDF but not on Print-Out
I have two line charts on a DevExpress xtrareport. For some reason, the curves are drawn fine on one but not the other.

If I print the report using PDF995 application, or using Microsoft XPS document Writer, both charts appear fine.
However, if I print the report directly to the printer (a TA/UTAX), the curves on one of the graphs don't appear at all.
This is a screenshot from the output of the XPS document.

But when it's sent directly to the printer, the curves don't appear on the left hand graph. Below is a scan of the same graphs printed to the printer.

I'm fairly positive it is related to the data in the data series because if I switch the binding so that the right-hand graph uses the current left-hand data, I get the same problem but with that graph. However, on examining the data, I can't find anything amiss.

The data comes from a list of Tuples (string, decimal, decimal):

The SeriesDataMember is bound to Item1

The ArgumentDataMember is bound to Item2

The ValueDataMembers Value is bound to Item3

And the report is printed using the DevExpress ReportPrintTool.Print() method.

Strangely, the graph on the left in the screenshot is printed fine, and that gets its data from a similar data structure.

What could be different between printing to an actual printer and printing to a PDF writer? (PDF995)

Edit

As per my comment, starting the curve at -0.01, -0.01 allows extra space below the origin and then the curve prints fine. This currently works as a workaround as the graph will never be printed in a fine enough detail to notice the difference between 0.01 and 0. But still... weird...

答:
is that curves visible on the real printer if you try to print result Microsoft XPS document file?
currently i think that your problem is in your printer : (</p>


问:
Pick random property and value from Javascript object
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

```<code>var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}
</code>```

Now I want to add more options for such as books, games.. so I've created an object for it:

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
</code>```

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

答:
So, start by writing a generic pick function that takes an array and returns an item. I'll leave the implementation of that to you.

Next you need to use Object.keys to get an array like ['watch', 'read', 'play'].

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
var keys = Object.keys(chooseOption);
var type = pick(keys);
</code>```

Then you can get the inner array by accessing the property by that key.

```<code>var items = chooseOption[type];
var item = pick(items);
</code>```

And finally, display the result.

```<code>console.log('You should ' + type + ' ' + item);
</code>```

Body:
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Body:
So, start by writing a generic pick function that takes an array and returns an item. I'll leave the implementation of that to you.

Next you need to use Object.keys to get an array like ['watch', 'read', 'play'].

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
var keys = Object.keys(chooseOption);
var type = pick(keys);

Then you can get the inner array by accessing the property by that key.

var items = chooseOption[type];
var item = pick(items);

And finally, display the result.

console.log('You should ' + type + ' ' + item);


问:
How to detect "Recent Apps" system button clicks (Honeycomb+)
I'm wondering what method this button calls.

My game always pauses/resumes correctly except for when I use this button, its seems like this button doesn't call the onPause() and onResume() methods of an Activity.
It works if I exit the game, go to another window(like the one on the picture) and then use this button to resume. But If I just press this button, when ingame, the game pauses but the thread dosnt resume like it does every other time, the game kind of just stands still on screen and flickers a bit.

Hard to explain but I hope I'm being sort of clear, if not, ask!

答:
The best way I have found is listent to Broadcast Action called "ACTION_CLOSE_SYSTEM_DIALOGS".From the Google docs:

Broadcast Action: This is broadcast when a user action should request a
temporary system dialog to dismiss.  Some examples of temporary system
dialogs are the notification window-shade and the recent tasks dialog.

Working code:

```<code>IntentFilter intentFilterACSD = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                    //do what you want here
            }
        }
    };
    this.registerReceiver(broadcastReceiver, intentFilterACSD);
</code>```

Body:
The best way I have found is listent to Broadcast Action called "ACTION_CLOSE_SYSTEM_DIALOGS".From the Google docs:

Broadcast Action: This is broadcast when a user action should request a
temporary system dialog to dismiss.  Some examples of temporary system
dialogs are the notification window-shade and the recent tasks dialog.

Working code:

IntentFilter intentFilterACSD = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                    //do what you want here
            }
        }
    };
    this.registerReceiver(broadcastReceiver, intentFilterACSD);


问:
Gem::Ext::BuildError: ERROR: Failed to build gem native extension on json 1.8.6 and sqlite3 1.3.13
I am created new application and then run in command line bundle show so show this error :-

```<code>Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies............................................
Using rake 12.0.0
Using i18n 0.8.1
Using minitest 4.7.5
Using multi_json 1.12.1
Using thread_safe 0.3.6
Using tzinfo 0.3.53
Using builder 3.1.4
Using erubis 2.7.0
Using rack 1.5.5
Using mime-types-data 3.2016.0521
Using activerecord-deprecated_finders 1.0.4
Using arel 4.0.2
Using bundler 1.11.2
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using thor 0.19.4
Using hike 1.2.3
Installing json 1.8.6 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /tmp/bundler20170330-4696-17s1gfujson-1.8.6/gems/json-1.8.6/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20170330-4696-1cm0oql.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170330-4696-17s1gfujson-1.8.6/gems/json-1.8.6 for inspection.
Results logged to /tmp/bundler20170330-4696-17s1gfujson-1.8.6/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out
Using tilt 1.4.1
Using rdoc 4.3.0
Using sass 3.2.19
Installing sqlite3 1.3.13 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/gems/sqlite3-1.3.13/ext/sqlite3
/usr/bin/ruby2.3 -r ./siteconf20170330-4696-1s2vax3.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/gems/sqlite3-1.3.13 for inspection.
Results logged to /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/extensions/x86_64-linux/2.3.0/sqlite3-1.3.13/gem_make.out
Using turbolinks-source 5.0.0
Using activesupport 4.0.13
Using rack-test 0.6.3
Using mime-types 3.1
Using coffee-script 2.4.1
Using uglifier 3.1.11
An error occurred while installing json (1.8.6), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.6'` succeeds before bundling.
</code>```

I am use this all version :-

```<code>Ruby version:- ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]
Rails version:- Rails 4.0.13
Gem version:- 2.5.1
Bundle version:- Bundler version 1.14.6
Mongo version:- MongoDB shell version: 2.4.14
</code>```

Please tell us! How to solve this problem? I am search so many solution but does not find out suitable solutions.

答:
as per github post here, have you tried running the following command to fix it:</p>

```<code>sudo apt-get install libgmp3-dev
</code>```

Body:
I am created new application and then run in command line bundle show so show this error :-

Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies............................................
Using rake 12.0.0
Using i18n 0.8.1
Using minitest 4.7.5
Using multi_json 1.12.1
Using thread_safe 0.3.6
Using tzinfo 0.3.53
Using builder 3.1.4
Using erubis 2.7.0
Using rack 1.5.5
Using mime-types-data 3.2016.0521
Using activerecord-deprecated_finders 1.0.4
Using arel 4.0.2
Using bundler 1.11.2
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using thor 0.19.4
Using hike 1.2.3
Installing json 1.8.6 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /tmp/bundler20170330-4696-17s1gfujson-1.8.6/gems/json-1.8.6/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20170330-4696-1cm0oql.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170330-4696-17s1gfujson-1.8.6/gems/json-1.8.6 for inspection.
Results logged to /tmp/bundler20170330-4696-17s1gfujson-1.8.6/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out
Using tilt 1.4.1
Using rdoc 4.3.0
Using sass 3.2.19
Installing sqlite3 1.3.13 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/gems/sqlite3-1.3.13/ext/sqlite3
/usr/bin/ruby2.3 -r ./siteconf20170330-4696-1s2vax3.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/gems/sqlite3-1.3.13 for inspection.
Results logged to /tmp/bundler20170330-4696-5gxxursqlite3-1.3.13/extensions/x86_64-linux/2.3.0/sqlite3-1.3.13/gem_make.out
Using turbolinks-source 5.0.0
Using activesupport 4.0.13
Using rack-test 0.6.3
Using mime-types 3.1
Using coffee-script 2.4.1
Using uglifier 3.1.11
An error occurred while installing json (1.8.6), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.6'` succeeds before bundling.

I am use this all version :-

Ruby version:- ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]
Rails version:- Rails 4.0.13
Gem version:- 2.5.1
Bundle version:- Bundler version 1.14.6
Mongo version:- MongoDB shell version: 2.4.14

Please tell us! How to solve this problem? I am search so many solution but does not find out suitable solutions.

Body:
as per github post here, have you tried running the following command to fix it:

sudo apt-get install libgmp3-dev


问:
How to group a column(Travel Fare) in ranges (0-100),(100-200) like wise
I have a SQL Table where there are Bookings records kept. I have to group the no. of bookings based on Fare ranges (0-100),(100-200) like wise. Fares are up to 3 decimal points. Please help</p>

答:
Does something like work for you?

Making some assumptions and a rudimentary table definition

```<code>DECLARE @Booking TABLE(
     Id         INT IDENTITY(1,1)
    ,TravelFare DECIMAL(10,3)
)
INSERT INTO @Booking
        ( TravelFare )
VALUES
        ( 5 ),( 17 ),( 43 ),( 115 ),( 135 ),( 167 ),( 221 ),( 278 ),( 325 ),( 354 ),( 387 )

SELECT
     COUNT(X.TravelFare)    'Count'
    ,X.TravelFareGroup
FROM
(
SELECT
     TravelFare
    ,CASE
        WHEN TravelFare BETWEEN 0 AND 100 THEN '0-100'
        WHEN TravelFare BETWEEN 101 AND 200 THEN '101-200'
        WHEN TravelFare BETWEEN 201 AND 300 THEN '201-300'
        WHEN TravelFare BETWEEN 301 AND 400 THEN '301-400'
     END 'TravelFareGroup'
FROM
    @Booking
) X
GROUP BY
    TravelFareGroup
</code>```

Body:
Does something like work for you?

Making some assumptions and a rudimentary table definition

DECLARE @Booking TABLE(
     Id         INT IDENTITY(1,1)
    ,TravelFare DECIMAL(10,3)
)
INSERT INTO @Booking
        ( TravelFare )
VALUES
        ( 5 ),( 17 ),( 43 ),( 115 ),( 135 ),( 167 ),( 221 ),( 278 ),( 325 ),( 354 ),( 387 )

SELECT
     COUNT(X.TravelFare)    'Count'
    ,X.TravelFareGroup
FROM
(
SELECT
     TravelFare
    ,CASE
        WHEN TravelFare BETWEEN 0 AND 100 THEN '0-100'
        WHEN TravelFare BETWEEN 101 AND 200 THEN '101-200'
        WHEN TravelFare BETWEEN 201 AND 300 THEN '201-300'
        WHEN TravelFare BETWEEN 301 AND 400 THEN '301-400'
     END 'TravelFareGroup'
FROM
    @Booking
) X
GROUP BY
    TravelFareGroup


问:
Liferay deployment in linux Server
i have installed liferay 7 in linux server. but when i try start the server it doesnt start properly shows up without css .

Is there any procedure to install liferay in linux server

Browser Console

Some files are accessing with url localhost

```<code>http://localhost:8383/o/classic-theme/css/aui.css?browserId=firefox&themeId=classic_WAR_classictheme&minifierType=css&languageId=en_US&b=7002&t=32

http://localhost:8383/o/mentions-web/css/mentions.css

/o url is not generating with hostname instead generates with localhost
</code>```

答:
After setting up the username password and db details kindly go to the page settings and try to change the theme or check their the option for csss.

or
add this property in portal-ext.properties file present in the tomcat/webapps/ROOT/WEB-INF/classes or you need to create portal-ext.properties file.

```<code>theme.css.fast.load=true
</code>```

Title: Liferay deployment in linux Server

Body:
i have installed liferay 7 in linux server. but when i try start the server it doesnt start properly shows up without css .

Is there any procedure to install liferay in linux server

Browser Console

Some files are accessing with url localhost

http://localhost:8383/o/classic-theme/css/aui.css?browserId=firefox&themeId=classic_WAR_classictheme&minifierType=css&languageId=en_US&b=7002&t=32

http://localhost:8383/o/mentions-web/css/mentions.css

/o url is not generating with hostname instead generates with localhost

Body:
After setting up the username password and db details kindly go to the page settings and try to change the theme or check their the option for csss.

or
add this property in portal-ext.properties file present in the tomcat/webapps/ROOT/WEB-INF/classes or you need to create portal-ext.properties file.

theme.css.fast.load=true


问:
How to join a comma after end of dict using python 3.4
Input: a = {"item1": {"item2": "300"}}{{"item1": {"item2": "300"}}

Output should be like: {"item1": {"item2": "300"}}, {{"item1": {"item2": "300"}}

答:
Are you sure this is what you wanted to write?

```<code>a = {"item1": {"item2": "300"}}{{"item1": {"item2": "300"}}
</code>```

Because, to create a dictionary, the curly brackets on that line aren't syntactically correct.

Unless you wanted a to be a string and want to insert a comma in that string?

Body:
Are you sure this is what you wanted to write?

a = {"item1": {"item2": "300"}}{{"item1": {"item2": "300"}}

Because, to create a dictionary, the curly brackets on that line aren't syntactically correct.

Unless you wanted a to be a string and want to insert a comma in that string?


问:
How can we set background color and tint color only for android using react navigation?
Am trying to change the background color of the tab bar only in android using "react navigation". Is it possible ?

I use the below tabBarOptions, but it changes the background color both in iOS and Android, but my requirement is to change the color only in Android and it should remain the default in iOS,

{   tabBarOptions: {
      style: {
      backgroundColor: '#2D61A9',   }   } }

Thanks in advance.

答:
You can use Platform see here to set platform os specific styles.

The following should work.

```<code>{
  tabBarOptions : {
    style: {
      Platform.select({
      android: {
        backgroundColor: '#2D61A9',
      },
    }
  }
}
</code>```

Body:
You can use Platform see here to set platform os specific styles.

The following should work.

{
  tabBarOptions : {
    style: {
      Platform.select({
      android: {
        backgroundColor: '#2D61A9',
      },
    }
  }
}


问:
Replace content present in the nested brackets
Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))

Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW

Tried so far

```<code>Output = Input.replace(/ *\([^)]*\)*/g, "");
</code>```

答:
If you need to remove nested parentheses, you may use a trick from Remove Nested Patterns with One Line of JavaScript.

var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = Input;
while (Output != (Output = Output.replace(/\s*\([^()]*\)/g, "")));
console.log(Output); ```
</div>
</div>
</p>
<p>Or, you could use a recursive function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function remove_nested_parens(s) {
    let new_s = s.replace(/\s*\([^()]*\)/g, "");
    return new_s == s ? s : remove_nested_parens(new_s);
}
console.log(remove_nested_parens("ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))"));</code>```

Here, \s*\([^()]*\) matches 0+ whitespaces, (, 0+ chars other than ( and ) and then a ), and the replace operation is repeated until the string does not change.

Body:
Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))

Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW

Tried so far

Output = Input.replace(/ *\([^)]*\)*/g, "");

Body:
If you need to remove nested parentheses, you may use a trick from Remove Nested Patterns with One Line of JavaScript.

var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = Input;
while (Output != (Output = Output.replace(/\s*\([^()]*\)/g, "")));
console.log(Output);

Or, you could use a recursive function:

function remove_nested_parens(s) {
    let new_s = s.replace(/\s*\([^()]*\)/g, "");
    return new_s == s ? s : remove_nested_parens(new_s);
}
console.log(remove_nested_parens("ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))"));

Here, \s*\([^()]*\) matches 0+ whitespaces, (, 0+ chars other than ( and ) and then a ), and the replace operation is repeated until the string does not change.


问:
"The resource cannot be found." error when there is a "dot" at the end of the url
I'm using ASP .NET MVC Beta and I get the HTTP 404 (The resource cannot be found) error when I use this url which has a "dot" at the end:

http://localhost:81/Title/Edit/Code1.

If I remove the dot at the end or the dot is somewhere in the middle I don't get the error.

I tried to debug but it I get the error from "System.Web.CachedPathData.GetConfigPathData(String configPath)" before ProcessRequest in MvcHandler.

Is "dot" not allowed at the end of a url? Or is there a way to fix the route definition to handle this url?

For an example: I have a table named Detail1 [Id(integer), Code(string), Description(string)] which has FK relationship with Master1 through it's Id column. Whenever I select a record of Master1, I also select it's Detail1 record to get it's Code field. In order to not to make this join everytime (since usually there isn't only one detail, there are more than one) I choose not to use Id column and I make Code PK of Detail1.

But when I get rid of Id and use Code as PK then my routes also start to work with Code field, like: Detail1\Edit\Code1

This Code can have anything in it or at the end, including DOT. There are cases where I can prohibit a DOT at the end but sometimes it's really meaningfull.

And I'have also seen this post that routes can be very flexible, so I didn't think mine is so weird.

So that's why I do something so non-standard. Any suggestions?

And also why it's so weird to have a DOT at the end of a url?

答:
Perhaps http://localhost:81/Title/Edit/Code1%2E would work.

I escaped the period with a hex ascii code.

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: recursive


问:
Is it possible to add a background image to a
 element on a JSP page? - Spring
I have been looking for an answer for this for a few days now and can not seem to find a solution. Below is the example I am trying to implement, however no image is displayed. The aim is to have a responsive image that covers the entire page.

```<code><div class="col-md-12 img-responsive"
style="background-image:url(<c:url value='/resources/img/abstract-ice.jpeg' />);">
</code>```

as far as I am aware this should work, I have resource mapping implemented and is working, I can tell this by navigating to the url and the image is displayed.

When placing this tag into the body element with the background attribute it displays the image but is not responsive and cuts the image as it pleases. I have tried styling this with bootstrap and using my own css, but anything I do makes no change/removes the image completely.

This url does also work with the  tag except then I can not overlay other elements with ease.

Ultimately my question is how can I get the div element to accept this url as a background image using pure css?

Any suggestions/prior experience would be welcomed.

HTML code

```<code><body background="">
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12 header_bar">
            <div class="col-md-6 text-left">
                <a href="#" class="nav_login">Home</a>
            </div>
            <div class="col-md-6 text-right">
                <a href="#" class="nav_login">log in</a>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12 img-responsive" style="background-image:url(<c:url value='/resources/img/abstract-ice.jpeg' />);">
        </div>

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

答:
Write a class to the div and write the css. set width and height for responsiveness. Remove the bootstrap classes "img-responsive".

i.e

HTML :

```<code><div class="yourclassname">
</code>```

CSS:

```<code>.yourclassname
{
background-image:<c:url value="/resources/img/abstract-ice.jpeg" />
width: 100%;
height: auto;
}
</code>```

Title: Is it possible to add a background image to a <div> element on a JSP page? - Spring

Body:
I have been looking for an answer for this for a few days now and can not seem to find a solution. Below is the example I am trying to implement, however no image is displayed. The aim is to have a responsive image that covers the entire page.

<div class="col-md-12 img-responsive"
style="background-image:url(<c:url value='/resources/img/abstract-ice.jpeg' />);">

as far as I am aware this should work, I have resource mapping implemented and is working, I can tell this by navigating to the url and the image is displayed.

When placing this tag into the body element with the background attribute it displays the image but is not responsive and cuts the image as it pleases. I have tried styling this with bootstrap and using my own css, but anything I do makes no change/removes the image completely.

This url does also work with the  tag except then I can not overlay other elements with ease.

Ultimately my question is how can I get the div element to accept this url as a background image using pure css?

Any suggestions/prior experience would be welcomed.

HTML code

                Home

                log in

        <div class="col-md-12 img-responsive" style="background-image:url(<c:url value='/resources/img/abstract-ice.jpeg' />);">

Body:
Write a class to the div and write the css. set width and height for responsiveness. Remove the bootstrap classes "img-responsive".

i.e

HTML :

<div class="yourclassname">

CSS:

.yourclassname
{
background-image:<c:url value="/resources/img/abstract-ice.jpeg" />
width: 100%;
height: auto;
}


问:
Html table with data from mysql
I'm making a form like this one:

```<code><?php
    echo '<tr>
    <td><strong>Kamp</strong></td>
    <td width="80px"><strong>1X2</strong></td>
    <td><strong>Resultat</strong></td></tr>';
    $no = 1;
    while ($row = mysqli_fetch_array($query))
    {
        echo '<tr>
            <td>'.$row['kamp'].'</td>
            <td><input type="radio" name="k1" id="k11" value="1" />1<input type="radio" name="k1" id="k1x" value="X" />X<input type="radio" name="k1" id="k12" value="2" />2</td>
            <td><input name="k1r" type="text" id="k1r" placeholder="X-X" /></td>
        </tr>

    ';
    $no++;

}?>
</code>```

And it echo a nice form with 3 rows from my database in the first . It is like a betting-game, so I have the mathes in my database. But as it is right now, the user will check the radiobuttons at 3 different mathes, but submit the same, if you understand. How can I make it 3 different inputs?

答:
I usually use counter in my loop</p>

```<code>$no = 1;
while ($row = mysqli_fetch_array($query))
{
    echo '<tr>
            <td>'.$row['kamp'].'</td>
            <td><input type="radio" name="k1_'.$no.'" id="k11_'.$no.'" value="1" />1<input type="radio" name="k1_'.$no.'" id="k1x_'.$no.'" value="X" />X<input type="radio" name="k1_'.$no.'" id="k12_'.$no.'" value="2" />2</td>
            <td><input name="k1r_'.$no.'" type="text" id="k1r_'.$no.'" placeholder="X-X" /></td>
          </tr>
';
$no++;
</code>```

Title: Html table with data from mysql

Body:
I'm making a form like this one:

<?php
    echo '

    Kamp
    1X2
    Resultat
';
    $no = 1;
    while ($row = mysqli_fetch_array($query))
    {
        echo '

            '.$row['kamp'].'
            <input type="radio" name="k1" id="k11" value="1" />1<input type="radio" name="k1" id="k1x" value="X" />X<input type="radio" name="k1" id="k12" value="2" />2
            <input name="k1r" type="text" id="k1r" placeholder="X-X" />

    ';
    $no++;

}?>

And it echo a nice form with 3 rows from my database in the first . It is like a betting-game, so I have the mathes in my database. But as it is right now, the user will check the radiobuttons at 3 different mathes, but submit the same, if you understand. How can I make it 3 different inputs?

Body:
I usually use counter in my loop

$no = 1;
while ($row = mysqli_fetch_array($query))
{
    echo '<tr>
            <td>'.$row['kamp'].'</td>
            <td><input type="radio" name="k1_'.$no.'" id="k11_'.$no.'" value="1" />1<input type="radio" name="k1_'.$no.'" id="k1x_'.$no.'" value="X" />X<input type="radio" name="k1_'.$no.'" id="k12_'.$no.'" value="2" />2</td>
            <td><input name="k1r_'.$no.'" type="text" id="k1r_'.$no.'" placeholder="X-X" /></td>
          </tr>
';
$no++;


问:
XSLT adding a tr at nth position while transforming the XML node with different child nodes
I am new to XSLT, and I am trying to transform the below XML. Note that the child nodes will be different

```<code><parent>
 <child1>A</child1>
 <child2>B</child2>
 <child3>C</child3>
 <child4>D</child4>
 <child5>E</child5>
 <child6>F</child6>
 <child7>G</child7>
</parent>
</code>```

I want transform the above as follows,when n is 3

```<code><tr><td>child1:A</td><td>child2:B</td><td>child3:C</td></tr>
<tr><td>child4:D</td><td>child5:E</td><td>child6:F</td></tr>
<tr><td>child7:G</td></tr>
</code>```

I tried as follows

```<code><xsl:template match="parent/*[position() mod 4 = 1]">
    <tr>
    <xsl:apply-templates mode="proc"
        select=".|following-sibling::parent/*[not(position() > 3)]"
    />
    </tr>
</xsl:template>
<xsl:template match="parent/*[not(position() mod 4 = 1)]"/>
 <xsl:template match="parent/*" mode="proc">
    <td class="label"><xsl:value-of select ="name(.)"/>:<xsl:value-of select ="."/></td>
 </xsl:template>
</code>```

答:
The problem is with this line...

```<code><xsl:apply-templates mode="proc"
                     select=".|following-sibling::parent/*[not(position() > 3)]" />
</code>```

You are in a template matching a child of the parent element (parent/*). This means the current node does not have a parent node as a sibling. Change the expression to this

```<code><xsl:apply-templates mode="proc"
                     select=".|following-sibling::*[not(position() > 3)]" />
</code>```

Body:
I am new to XSLT, and I am trying to transform the below XML. Note that the child nodes will be different

<parent>
 <child1>A</child1>
 <child2>B</child2>
 <child3>C</child3>
 <child4>D</child4>
 <child5>E</child5>
 <child6>F</child6>
 <child7>G</child7>
</parent>

I want transform the above as follows,when n is 3

child1:A	child2:B	child3:C

child4:D	child5:E	child6:F

child7:G

I tried as follows

<xsl:template match="parent/*[position() mod 4 = 1]">

    <xsl:apply-templates mode="proc"
        select=".|following-sibling::parent/*[not(position() > 3)]"
    />

</xsl:template>
<xsl:template match="parent/*[not(position() mod 4 = 1)]"/>
 <xsl:template match="parent/*" mode="proc">
    <xsl:value-of select ="name(.)"/>:<xsl:value-of select ="."/>
 </xsl:template>

Body:
The problem is with this line...

<xsl:apply-templates mode="proc"
                     select=".|following-sibling::parent/*[not(position() > 3)]" />

You are in a template matching a child of the parent element (parent/*). This means the current node does not have a parent node as a sibling. Change the expression to this

<xsl:apply-templates mode="proc"
                     select=".|following-sibling::*[not(position() > 3)]" />