text:
Q: Does C# 4.0 and a combination of optional parameters and overloads give you a warning about ambiguity? I've started reading Jon Skeet's early access version of his book, which contains sections on C# 4.0, and one thing struck me. Unfortunately I don't have Visual Studio 2010 available so I thought I'd just ask here instead and see if anyone knew the answer.
If I have the following code, a mixture of existing code, and new code:
public void SomeMethod(Int32 x, Int32 y) { ... }

public void SomeMethod(Int32 x, Int32 y, Int32 z = 0) { ... }

Will the compiler complain either at the definition site or the call site about possible ambiguity?
For instance, what will this piece of code actually do?
SomeClass sc = new SomeClass();
sc.SomeMethod(15, 23);

Will it compile? Will it call the one without the z parameter, or will it call the one with the z parameter?

A: This is covered in the "Overload Resolution" section of the chapter.
When the compiler has two otherwise-equal options to choose from, it will use an overload which doesn't need use any unsupplied optional parameters in preference to one that does, but it's a strict binary choice. If it has to choose between an overload with one unsupplied optional parameter and two, it will consider that to be an ambiguous situation.
To answer your follow-up comment, I don't know any way of forcing an overload with the optional parameter to be used without specifying it. You can't use either of these, for instance:
// Both invalid
sc.SomeMethod(15, 23, );
sc.SomeMethod(15, 23, z:)

If, however, your methods used different parameter names, you could do it then:
public void SomeMethod(Int32 x, Int32 y) { ... }
public void SomeMethod(Int32 a, Int32 b, Int32 c = 0) { ... }

sc.SomeMethod(a: 15, b: 23); // Calls second method

A: It will compile without warnings and will choose the first overload.
With the introduction of optional and named parameters, the overload resolution mechanism of C# has become really complicated. In this specific case, it makes sense however. As usual, the compiler will choose the most specific overload that matches the arguments.
I don't believe this specific case is much different from C# 1.0:
public void SomeMethod(Int32 x, Int32 y) { }
public void SomeMethod(Int32 x, Int32 y, params Int32[] z) { }

which works identically (in terms of overload resolution).
Follow up answer: I don't think so. I'm afraid you'll have to manually specify the default argument in the method call. However, if x or y parameter had a different name like:
public void SomeMethod(Int32 x, Int32 y) { }
public void SomeMethod(Int32 t, Int32 y, Int32 z = 0) { }

you could choose the second overload with:
obj.SomeMethod(t: 10, y: 20);


text:
Q: Improve Powershell Get-WinEvent Script Performance The following script takes 5-10 minutes per server to return the events. I am currently only querying the last 7 days of events.  The servers are all Windows Server 2012 R2 servers.  Is there a better way to write this that might improve its performance?  The highest summarized count for events so far has been 24,509 (sum of all event counts).  It seems like this shouldn't take over 5 minutes but maybe I'm expecting too much?
For reference:
$eventlogs = 'application, system'
$eventlevels = '1','2','3'
$startdate = get-date
$enddate = [DateTime]::Today.AddDays(-7)

Get-WinEvent -ComputerName $server -FilterHashTable @{LogName=$eventLogs; Level=$eventLevels; StartTime=$startDate; EndTime=$endDate} -ErrorAction SilentlyContinue `
| Group-Object LogName, ProviderName, ID, {$_LevelDisplayName}, Count `
| Select-Object @{N="Log"; E={$_.Group[0].LogName}}, `
@{N="Provider"; E={$_.Group[0].ProviderName}}, `
@{N="Error ID"; E={$_.Group[0].ID}}, `
@{N="Type"; E={$_.Group[0].LevelDisplayName}}, `
count, `
@{N="Message"; E={$_.Group[0].Message.Replace("`r",' ').Replace("`n",' ')}} `
| Sort-Object  "Type" `
| Export-Csv -notypeinformation -Path $file

redpajama_set_name: RedPajamaStackExchange


text:
Q: grails app terminates after some idle time – what triggers unexpected shutdown? I've got a Grails 2.4.3 app for internal use in my company.
Problem is, after some time when I had it running (grails dev run-app), it terminates  listening without prior notice:
INFO  [Thread-3]: Pausing ProtocolHandler ["http-bio-8080"]
INFO  [Thread-3]: Stopping service Tomcat
### Shutting down.
INFO  [Thread-3]: Stopping ProtocolHandler ["http-bio-8080"]
INFO  [Thread-3]: Destroying ProtocolHandler ["http-bio-8080"]

(The 3rd line is from the destroy() method in my BootStrap.groovy)
For datasource connections, there are keepalive strategies for pooled connections. I'd like the grails app to stay online, too.
How can I investigate on what causes the server to stop listening?
Is this a common issue and can it be solved by config?
Edit:
The root logger shows the following on DEBUG level:
DEBUG [http-bio-8080-exec-4]: Counting down[http-bio-8080-exec-4] latch=2
DEBUG [http-bio-8080-exec-1]: Error parsing HTTP request header
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
...
DEBUG [http-bio-8080-exec-1]: Socket: [org.apache.tomcat.util.net.SocketWrapper@5c0b659a:Socket[addr=/0:0:0:0:0:0:0:1,port=58705,localport=8080]], Status in: [OPEN_READ], State out: [CLOSED]
DEBUG [http-bio-8080-exec-1]: Counting down[http-bio-8080-exec-1] latch=1
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: Start expire sessions StandardManager at 1421320212649 sessioncount 0
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: End expire sessions StandardManager processingTime 0 expired sessions: 0
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: Start expire sessions StandardManager at 1421320272661 sessioncount 0
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: End expire sessions StandardManager processingTime 0 expired sessions: 0
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: Start expire sessions StandardManager at 1421320332673 sessioncount 0
DEBUG [ContainerBackgroundProcessor[StandardEngine[Tomcat]]]: End expire sessions StandardManager processingTime 0 expired sessions: 0
DEBUG [http-bio-8080-Acceptor-0]: Counting up[http-bio-8080-Acceptor-0] latch=1
DEBUG [http-bio-8080-exec-6]: Error parsing HTTP request header
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:196)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:519)
...
DEBUG [http-bio-8080-exec-6]: Socket: [org.apache.tomcat.util.net.SocketWrapper@674b5757:Socket[addr=/10.41.2.116,port=46215,localport=8080]], Status in: [OPEN_READ], State out: [CLOSED]
DEBUG [http-bio-8080-exec-6]: Counting down[http-bio-8080-exec-6] latch=1
DEBUG [Thread-3]: Setting state for [StandardServer[-1]] to [STOPPING_PREP]
DEBUG [Thread-3]: Setting state for [StandardServer[-1]] to [STOPPING]
DEBUG [Thread-3]: Setting state for [StandardService[Tomcat]] to [STOPPING_PREP]
INFO  [Thread-3]: Pausing ProtocolHandler ["http-bio-8080"]
DEBUG [Thread-3]: About to unlock socket for:localhost/127.0.0.1:8080
DEBUG [Thread-3]: Socket unlock completed for:localhost/127.0.0.1:8080
DEBUG [http-bio-8080-Acceptor-0]: Counting down[http-bio-8080-Acceptor-0] latch=0
INFO  [Thread-3]: Stopping service Tomcat
DEBUG [Thread-3]: Setting state for [StandardService[Tomcat]] to [STOPPING]
DEBUG [Thread-3]: Setting state for [StandardEngine[Tomcat]] to [STOPPING_PREP]
DEBUG [Thread-3]: Setting state for [StandardEngine[Tomcat]] to [STOPPING]
DEBUG [Thread-3]: Setting state for [Pipeline[StandardEngine[Tomcat]]] to [STOPPING_PREP]
DEBUG [Thread-3]: Setting state for [Pipeline[StandardEngine[Tomcat]]] to [STOPPING]
DEBUG [Thread-3]: Setting state for [org.apache.catalina.core.StandardEngineValve[Tomcat]] to [STOPPING_PREP]
DEBUG [Thread-3]: Setting state for [org.apache.catalina.core.StandardEngineValve[Tomcat]] to [STOPPING]
DEBUG [Thread-3]: Setting state for [org.apache.catalina.core.StandardEngineValve[Tomcat]] to [STOPPED]
DEBUG [Thread-3]: Setting state for [Pipeline[StandardEngine[Tomcat]]] to [STOPPED]
DEBUG [Tomcat-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost]] to [STOPPING_PREP]
DEBUG [Tomcat-startStop-2]: Unregister host [localhost] at domain [null] for connector [Connector[HTTP/1.1-8080]]
DEBUG [Tomcat-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost]] to [STOPPING]
DEBUG [Tomcat-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost]]] to [STOPPING_PREP]
DEBUG [Tomcat-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost]]] to [STOPPING]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.valves.ErrorReportValve[localhost]] to [STOPPING_PREP]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.valves.ErrorReportValve[localhost]] to [STOPPING]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.valves.ErrorReportValve[localhost]] to [STOPPED]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.core.StandardHostValve[localhost]] to [STOPPING_PREP]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.core.StandardHostValve[localhost]] to [STOPPING]
DEBUG [Tomcat-startStop-2]: Setting state for [org.apache.catalina.core.StandardHostValve[localhost]] to [STOPPED]
DEBUG [Tomcat-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost]]] to [STOPPED]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent]] to [STOPPING_PREP]
DEBUG [localhost-startStop-2]: Unregister Context [/workspent] for connector [Connector[HTTP/1.1-8080]]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent]] to [STOPPING]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]] to [STOPPING_PREP]
DEBUG [localhost-startStop-2]: Unregister Wrapper [grails-errorhandler] in Context [/workspent] for connector [Connector[HTTP/1.1-8080]]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]] to [STOPPING]
DEBUG [localhost-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]]] to [STOPPING_PREP]
DEBUG [localhost-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]]] to [STOPPING]
DEBUG [localhost-startStop-2]: Setting state for [org.apache.catalina.core.StandardWrapperValve[grails-errorhandler]] to [STOPPING_PREP]
DEBUG [localhost-startStop-2]: Setting state for [org.apache.catalina.core.StandardWrapperValve[grails-errorhandler]] to [STOPPING]
DEBUG [localhost-startStop-2]: Setting state for [org.apache.catalina.core.StandardWrapperValve[grails-errorhandler]] to [STOPPED]
DEBUG [localhost-startStop-2]: Setting state for [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]]] to [STOPPED]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails-errorhandler]] to [STOPPED]
DEBUG [localhost-startStop-2]: Setting state for [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/workspent].StandardWrapper[grails]] to [STOPPING_PREP]
DEBUG [localhost-startStop-2]: Unregister Wrapper [grails] in Context [/workspent] for connector [Connector[HTTP/1.1-8080]]
INFO  [localhost-startStop-2]: ### Shutting down. Current time is 2015-01-15T12:12:39.009+01:00
INFO  [localhost-startStop-2]: Destroying Spring FrameworkServlet 'grails'

A: Take a look in your stacktrace.log file, probably some error will be there.
As the docs says:

When exceptions occur, there can be an awful lot of noise in the
  stacktrace from Java and Groovy internals. Grails filters these
  typically irrelevant details and restricts traces to non-core
  Grails/Groovy class packages.
When this happens, the full trace is always logged to the StackTrace
  logger, which by default writes its output to a file called
  stacktrace.log

If you don't know where is your file, you can configure it through log4j: http://grails.org/doc/latest/guide/conf.html
In your Config.groovy:
error stdout: "StackTrace"
log4j = {
    appenders {
        rollingFile name: "stacktrace", maxFileSize: 1024,
                    file: "/var/tmp/logs/myApp-stacktrace.log"
    }
}


text:
Q: How to change a layout background image depending on Dark/Light theme? I've got two images. I want to do so: when user opens an app with a Light theme - the first image is being used as a background for layouts. When user opens the app with a Dark theme - the second image is being used as a background for layouts.
To solve this problem with text colors, we can just use styles.xml and colors-day/night.xml and one line of code: <item name="android:textColor">@color/textColor</item>
I've tried to the same with images and two styles files: <item name="android:background">@drawable/day</item>
But this feature applies background to each element on a screen, not only to the main layouts.
I know, that I can do it programatically by changing a background with if statements and layout.setBackgroundResource(R.drawable.day/night);
But maybe it can be done with XML as in the case of the text color?

A:
To solve this problem with text colors, we can just use styles.xml and
colors-day/night.xml and one line of code: @color/textColor

You need to do the same thing, but instead of res/values/colors.xml, it should be done on the drawable res/drawable/day
So, you'll have a drawable & drawable-night folders in the res directory each of which should have a unique version of the day image with the same name.
They should look like in Android Studio (Android preview):

And normally use the the attribute name="android:background">@drawable/day</item>


text:
Q: Can't get AJAX POST request formatted correctly No matter what I do, I keep getting 500 (Internal Server Errors) when attempting to perform a POST to https://rates.tradelanes.us/bankaccount/record/create. I believe its the format of my data, but when I compare what my output is to others trying the same thing--my data format is identical; others are not getting the 500 error, so it must be how my data is formatted. The only documentation I have with the API is https://rates.tradelanes.us/bankaccount/help/api--so not much more to go on.
Here is the error I'm getting.. If you wanted to see what a sample record looks like:
{"Id":1,"Memo":"Sample Record","Amount":10.00,"TransactionDate":"\/Date(1503500694627)\/","Account":1,"Transaction":0}

Here is my code:

$(document).ready(function() {
  var table_records = $("#table_records").dataTable({
    "processing": true,
    "ajax": {
      "url": "https://rates.tradelanes.us/bankaccount/records",
      dataSrc: ""
    },
    "columns": [{
      "data": "Id"
    }, {
      "data": "Memo"
    }, {
      "data": "Amount"
    }, {
      "data": "TransactionDate"
    }, {
      "data": "Account"
    }, {
      "data": "Transaction"
    }]
  });

  //Show popup for creating new record
  function show_lightbox() {
    $(".lightbox_bg").show();
    $(".lightbox_container").show();
  }

  //Hide popup for creating new record
  function hide_lightbox() {
    $(".lightbox_bg").hide();
    $(".lightbox_container").hide();
  }

  //Clicking the "Close" button or outside of the lightbox should close the lightbox
  $(document).on("click", ".lightbox_bg", function() {
    hide_lightbox();
  });
  $(document).on("click", ".lightbox_close", function() {
    hide_lightbox();
  });

  //Handle clicking the "Create" button
  $(document).on("click", "#createButton", function(e) {
    e.preventDefault();
    $(".lightbox_content h2").text("Create record");
    $("#form_create button").text("Create record");
    $("#form_create").attr("class", "form add");
    $("#form_create").attr("data-id", "");
    $("#form_create .field_container").removeClass("valid").removeClass("error");
    $("#form_create #id").val("");
    $("#form_create #memo").val("");
    $("#form_create #amount").val("");
    $("#form_create #transactiondate").val("");
    $("#form_create #account").val("");
    $("#form_create #transaction").val("");
    show_lightbox();
  });

  function getFormData($form) {
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i) {
      indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
  }

  //Handle form submission
  $(document).on("submit", "#form_create.add", function(e) {
    e.preventDefault();
    hide_lightbox();

    var $form = $("#form_create");
    var form_data = getFormData($form);
    console.log(form_data);

    var req = $.ajax({
      url: "https://rates.tradelanes.us/bankaccount/record/create",
      cache: false,
      data: form_data,
      dataType: "application/json",
      contentType: "application/json; charset=utf-8",
      type: "post"
    });

    req.done(function(out) {
      if (out.result == "success") {
        table_records.api().ajax.reload(function() {
          alert("Record added successfully");
        }, true);
      } else {
        alert("Record failed to be created");
      }
    });

    req.fail(function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR.statusText);
      console.log(textStatus);
      console.log(errorThrown);
    });
  });
});
html {
  font-size: 14px;
  overflow-y: scroll;
  overflow-x: auto;
}

body {
  background-color: #ddd;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1rem;
  text-align: left;
  color: #666;
}

/* General -------------------------------------------------------------------------------------- */

* {
  padding: 0;
  border: 0;
  outline: 0;
  margin: 0;
}

h1,
h2 {
  font-weight: normal;
  font-size: 1rem;
}

a {
  cursor: pointer;
  -webkit-transition: all 0.2s ease 0s;
  -moz-transition: all 0.2s ease 0s;
  -o-transition: all 0.2s ease 0s;
  transition: all 0.2s ease 0s;
}

ul {
  list-style-type: none;
}

table {
  border-collapse: collapse;
}

table th,
table td {
  font-weight: normal;
  text-align: left;
  vertical-align: middle;
}

label {
  cursor: pointer;
}

input,
button,
select {
  background-color: transparent;
  font-family: 'Oxygen', Arial, Helvetica, sans-serif;
  font-size: 1rem;
  color: #666;
}

button,
select {
  cursor: pointer;
}

button {
  -webkit-transition: all 0.2s ease 0s;
  -moz-transition: all 0.2s ease 0s;
  -o-transition: all 0.2s ease 0s;
  transition: all 0.2s ease 0s;
}

select {
  -webkit-appearance: none;
}

input[type=text],
input[type=number],
input[type=email],
input[type=url],
input[type=password],
input[type=date],
input[type=search],
input[type=tel] {
  -webkit-appearance: none;
}

input[type=number] {
  -moz-appearance: textfield;
}

input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input::-webkit-outer-spin-button {
  -webkit-appearance: none;
}

input[type=search] {
  -webkit-appearance: none;
  -webkit-border-radius: 0;
}

input[type=search]::-webkit-search-decoration,
input[type=search]::-webkit-search-cancel-button,
input[type=search]::-webkit-search-results-button,
input[type=search]::-webkit-search-results-decoration {
  display: none;
}

button::-moz-focus-inner,
input[type="button"]::-moz-focus-inner,
input[type="submit"]::-moz-focus-inner,
input[type="reset"]::-moz-focus-inner {
  padding: 0 !important;
  border: 0 none !important;
}

/* Page container ------------------------------------------------------------------------------- */

#page_container {
  width: 980px;
  padding: 40px 5px 55px 5px;
  margin: 0 auto 0 auto;
}

/* Header --------------------------------------------------------------------------------------- */

h1 {
  font-weight: 700;
  font-size: 2.2rem;
  color: black;
  font-family: monospace;
  margin: 0 0 25px 0;
}

button.button {
  height: 35px;
  display: inline-block;
  background-color: #999;
  font-weight: 700;
  text-transform: uppercase;
  color: #fff;
  padding: 0 15px 0 15px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0 0 25px 0;
}

button.button:hover,
button.button:active {
  background-color: #333;
}

/* Datatable ------------------------------------------------------------------------------------ */

.dataTables_wrapper {
  position: relative;
  padding: 50px 0 50px 0;
}

.dataTables_length {
  width: auto;
  height: 30px;
  position: absolute;
  top: 0;
  left: 0;
  padding: 0 110px 0 0;
}

.dataTables_length label {
  line-height: 30px;
  margin: 0;
}

.dataTables_length select {
  width: 100px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
  background-color: #fff;
  color: #666;
  padding: 0 50px 0 10px;
  border: 1px solid #ccc;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0;
}

.dataTables_length:after {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
  background-color: #999;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  font-size: 1.2rem;
  line-height: 30px;
  text-align: center;
  color: #fff;
  content: '\f107';
  pointer-events: none;
  -webkit-border-top-right-radius: 6px;
  -webkit-border-bottom-right-radius: 6px;
  -moz-border-radius-topright: 6px;
  -moz-border-radius-bottomright: 6px;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}

.dataTables_length select::-ms-expand {
  display: none;
}

.dataTables_filter {
  position: absolute;
  top: 0;
  right: 0;
}

.dataTables_filter label {
  line-height: 30px;
}

.dataTables_filter input {
  width: 200px;
  height: 30px;
  display: inline-block;
  background-color: #fff;
  line-height: 30px;
  color: #666;
  padding: 0 0 0 10px;
  border: 1px solid #ccc;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0 0 0 10px;
}

.dataTables_filter input:focus {
  background-color: #ffd;
}

.dataTables_paginate {
  position: absolute;
  bottom: 0;
  left: 0;
}

.dataTables_paginate a {
  width: 30px;
  height: 30px;
  float: left;
  background-color: #999;
  font-weight: normal;
  line-height: 29px;
  text-align: center;
  color: #fff;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0 10px 0 0;
}

.dataTables_paginate a.current,
.dataTables_paginate a:hover,
.dataTables_paginate a:active,
.dataTables_paginate a:focus {
  background-color: #333;
}

.dataTables_paginate a.previous,
.dataTables_paginate a.next {
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-size: 1.2rem;
  line-height: 30px;
}

.dataTables_paginate a.previous:before {
  content: '\f104';
}

.dataTables_paginate a.next:before {
  content: '\f105';
}

.dataTables_info {
  position: absolute;
  bottom: 0;
  right: 0;
  line-height: 30px;
}

table.datatable {
  width: 100% !important;
  line-height: 1.4rem;
}

table.datatable th,
table.datatable td {
  background-color: #fff;
  padding: 5px 10px 5px 10px;
  border: 1px solid #ccc;
}

table.datatable thead th {
  background-color: #999;
  font-weight: bold;
  text-transform: uppercase;
  white-space: nowrap;
  color: #fff;
  padding-top: 7px;
  padding-bottom: 8px;
}

table.datatable thead th.sorting,
table.datatable thead th.sorting_desc,
table.datatable thead th.sorting_asc {
  cursor: pointer;
}

table.datatable thead th.sorting:active,
table.datatable thead th.sorting_desc:active,
table.datatable thead th.sorting_asc:active {
  background-color: #333;
}

table.datatable tbody tr:nth-child(even) td {
  background-color: #eee;
}

table.datatable tbody tr:hover th,
table.datatable tbody tr:hover td {
  background-color: #ffd;
}

table.datatable tbody tr:hover td.dataTables_empty {
  background-color: #fff;
}

table.datatable tbody td.company_name {
  width: 100%;
}

table.datatable tbody td.integer {
  text-align: right;
  white-space: nowrap;
}

table.datatable tbody td.nowrap {
  white-space: nowrap;
}

table.datatable tbody td.functions .function_buttons {
  width: 70px;
  height: 30px;
  margin: 0 auto 0 auto;
}

table.datatable tbody td.functions .function_buttons li {
  float: left;
  padding: 0 10px 0 0;
}

table.datatable tbody td.functions .function_buttons li.function_delete {
  padding: 0;
}

table.datatable tbody td.functions .function_buttons a {
  width: 30px;
  height: 30px;
  display: inline-block;
  background-color: #999;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  line-height: 29px;
  text-align: center;
  color: #fff;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}

table.datatable tbody td.functions .function_buttons .function_edit a:before {
  font-size: 1.1rem;
  content: "\f040";
}

table.datatable tbody td.functions .function_buttons .function_delete a:before {
  font-size: 1.2rem;
  line-height: 30px;
  content: "\f1f8";
}

table.datatable tbody td.functions .function_buttons a:hover,
table.datatable tbody td.functions .function_buttons a:active,
table.datatable tbody td.functions .function_buttons a:focus {
  background-color: #333;
}

table.datatable tbody td.functions .function_buttons span {
  display: none;
}

/* Lightbox ------------------------------------------------------------------------------------- */

.lightbox_bg {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  background-color: #333;
  background-color: rgba(0, 0, 0, 0.85);
  cursor: pointer;
}

.lightbox_container {
  display: none;
  width: 80%;
  height: 90%;
  position: fixed;
  top: 5%;
  left: 10%;
  z-index: 200;
  background-color: #fff;
  color: #666;
  overflow-y: scroll;
  overflow-x: auto;
  padding: 50px 0 0 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}

.lightbox_close {
  width: 35px;
  height: 35px;
  position: absolute;
  top: 45px;
  right: 45px;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  font-size: 20px;
  line-height: 35px;
  text-align: center;
  color: #f70;
  cursor: pointer;
  border: 2px solid #f70;
  -webkit-border-radius: 35px;
  -moz-border-radius: 35px;
  border-radius: 35px;
}

.lightbox_close:before {
  content: '\f00d';
}

.lightbox_close:hover {
  color: #333;
  border-color: #333;
}

.lightbox_content {
  width: 642px;
  padding: 0 50px 0 50px;
}

.lightbox_content h2 {
  font-weight: 700;
  font-size: 2rem;
  line-height: 2rem;
  color: #f70;
  margin: 0 0 25px 0;
}

.lightbox_content .input_container {
  width: 600px;
  margin: 0 0 10px 0;
}

.lightbox_content .input_container:after {
  clear: both;
  height: 0;
  display: block;
  font-size: 0;
  line-height: 0;
  content: ' ';
}

.lightbox_content .input_container label {
  width: 200px;
  float: left;
  font-size: 1rem;
  line-height: 32px;
}

.lightbox_content .input_container label span.required {
  font-weight: bold;
  color: #f70;
}

.lightbox_content .input_container .field_container {
  width: 400px;
  float: right;
  position: relative;
}

.lightbox_content .input_container .field_container label.error {
  width: 400px;
  display: block;
  background-color: #fff1e6;
  line-height: 1.4rem;
  color: #333;
  padding: 5px 0 6px 10px;
  border: 1px solid #f70;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0 0 5px 0;
}

.lightbox_content .input_container .field_container label.error.valid {
  display: none !important;
}

.lightbox_content .input_container .field_container input {
  width: 400px;
  height: 32px;
  background-color: #f9f9f9;
  line-height: 30px;
  color: #666;
  padding: 0 0 0 10px;
  border: 1px solid #ccc;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}

.lightbox_content .input_container .field_container input:focus {
  background-color: #ffd;
  color: #000;
}

.lightbox_content .input_container .field_container.error:after,
.lightbox_content .input_container .field_container.valid:after {
  width: 32px;
  height: 32px;
  position: absolute;
  bottom: 0;
  right: -42px;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  font-size: 20px;
  line-height: 32px;
  text-align: center;
}

.lightbox_content .input_container .field_container.error:after {
  content: '\f00d';
  color: #c00;
}

.lightbox_content .input_container .field_container.valid:after {
  content: '\f00c';
  color: #090;
}

.lightbox_content .button_container {
  width: 600px;
  height: 35px;
  text-align: right;
  padding: 15px 0 50px 0;
}

.lightbox_content .button_container button {
  height: 35px;
  display: inline-block;
  background-color: #999;
  font-weight: 700;
  text-transform: uppercase;
  color: #fff;
  padding: 0 15px 0 15px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}

.lightbox_content .button_container button:hover {
  background-color: #333;
  color: #fff;
}

/* Message / noscript --------------------------------------------------------------------------- */

#message_container,
#noscript_container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #333;
  text-align: center;
  color: #fff;
}

#message_container {
  display: none;
}

#message,
#noscript {
  width: 980px;
  line-height: 20px;
  padding: 10px 5px 10px 6px;
  margin: 0 auto 0 auto;
}

#message p,
#noscript p {
  display: inline-block;
  position: relative;
  padding: 0 0 0 28px;
}

#message p:before,
#noscript p:before {
  width: 20px;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #f70;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  color: #fff;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
}

#message.success p:before,
#noscript.success p:before {
  content: '\f00c';
}

#message.error p:before,
#noscript.error p:before {
  content: '\f00d';
}

/* Loading message ------------------------------------------------------------------------------ */

#loading_container {
  width: 100%;
  height: 100%;
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #333;
  background-color: rgba(0, 0, 0, 0.85);
  text-align: center;
}

#loading_container2 {
  width: 100%;
  height: 100%;
  display: table;
}

#loading_container3 {
  display: table-cell;
  vertical-align: middle;
}

#loading_container4 {
  width: 350px;
  height: 250px;
  position: relative;
  background-color: #fff;
  font-size: 1.4rem;
  line-height: 1.4rem;
  color: #666;
  padding: 165px 0 0 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
  margin: 0 auto 0 auto;
}

#loading_container4:before {
  width: 100%;
  position: absolute;
  top: 80px;
  left: 0;
  font-family: 'FontAwesome', Arial, Helvetica, sans-serif;
  font-weight: normal;
  font-size: 4rem;
  line-height: 4rem;
  text-align: center;
  color: #f70;
  content: '\f013';
  -webkit-animation: spin 2s infinite linear;
  animation: spin 2s infinite linear;
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(359deg);
    transform: rotate(359deg);
  }
}

@keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(359deg);
    transform: rotate(359deg);
  }
}

Bank CRUD

    <button type="button" class="button" id="createButton">Create record</button>

          Id
          Memo
          Amount
          Transaction Date
          Account
          Transaction
          Functions

Create record

      <form class="form add" id="form_create" data-id="" novalidate>

          Id:

            <input type="number" id="id" min="0" class="text" name='"Id"' value="" required>

          Memo:

            <input type="text" id="memo" class="text" name='"Memo"' value="" required>

          Amount:

            <input type="number" id="amount" min="0" class="text" name='"Amount"' value="" required>

          Transaction Date:

            <input type="text" id="transactiondate" class="text" name='"TransactionDate"' value="" required>

          Account:

            <input type="number" id="account" min="0" class="text" name='"Account"' value="" required>

          Transaction:

            <input type="number" id="transaction" min="0" class="text" name='"Transaction"' value="" required>

          <button type="submit">Create record</button>

      </form>

A: The answer was to apparently remove all of the settings for the AJAX request. Who would have guessed?
So it should look like the following:
var req = $.ajax({
      url: "https://rates.tradelanes.us/bankaccount/record/create",
      dataType: "json",
      data: form_data,
      type: "POST"
});

A: You have to be sure that you are getting the form .
let form = $('.whatever').find('form');

and then pass the data as the serialized form
form.serialize()

var req = $.ajax({
      url: "https://rates.tradelanes.us/bankaccount/record/create",
      cache: false,
      data: form.serialize(),
      dataType: "application/json",
      contentType: "application/json; charset=utf-8",
      type: "post"
    });

    req.done(function(out) {
      if (out.result == "success") {
        table_records.api().ajax.reload(function() {
          alert("Record added successfully");
        }, true);
      } else {
        alert("Record failed to be created");
      }
    });


text:
Q: Accessing data from a ticket database, based on months in MS Access Dear stackoverflow members,
I am creating an access database for ticket selling prices.
Since the tickets prices changes in yearly, I want to create the database to access ticket prices base on Months.
But the problem is how can i query the database to retrieve ticket prices based on a particular month?
I have also attached a image of my sample database.

I have also uploaded the database in text format.
Company:
  -------------------------------------------
    |     CompanyID      |    CompanyName     |
    -------------------------------------------
    | A                  | AAA                |
    -------------------------------------------
    | B                  | BBB                |
    -------------------------------------------
    | C                  | CCC                |
    -------------------------------------------
    | D                  | DDD                |
    -------------------------------------------
    | .                  | ..                 |
    -------------------------------------------
    | .                  | ..                 |
    -------------------------------------------
    | .                  | ..                 |
    -------------------------------------------
    | Z                  | ZZZ                |
    -------------------------------------------

Ticket:
    ----------------------------------------------------------------------------------------------------------
|         ID         |     TicketType     |        2010        |        2011        |        2012        |
----------------------------------------------------------------------------------------------------------
| 001                | 3 months           |             $50.00 |             $55.00 |             $68.00 |
----------------------------------------------------------------------------------------------------------
| 002                | 2 Weeks            |             $10.00 |             $11.50 |             $13.10 |
----------------------------------------------------------------------------------------------------------
| 003                | Group ticket       |             $30.00 |             $32.00 |             $35.00 |
----------------------------------------------------------------------------------------------------------
| 004                | Night ticket       |              $7.00 |              $9.00 |             $11.00 |
----------------------------------------------------------------------------------------------------------
| 005                | 1 Day              |              $3.00 |              $5.00 |              $8.00 |
----------------------------------------------------------------------------------------------------------
| 006                | 1 Week             |              $8.00 |             $15.00 |             $12.00 |
----------------------------------------------------------------------------------------------------------
| 007                | 1 month            |             $19.00 |             $22.00 |             $25.00 |
----------------------------------------------------------------------------------------------------------
| 200                | Fun ticket         |             $11.00 |             $12.00 |             $14.00 |
----------------------------------------------------------------------------------------------------------
| AAA                | 001                |                    |            $100.00 |          $5,500.00 |
----------------------------------------------------------------------------------------------------------

The Problem is:  I want to access the ticket prices base on months.
For example, The price of TicketID: "001" in "March 2011".
With it, monthly account base on tickets sold on a particular months will be accounted.
The fields are listed in year and creating it in months would lead to massive data redundancy or troublesome for future updates.
Any help would be very much appreciated.
Thank you very much in advance.
Cheers!

A: The structure of your database is preventing you from doing so. The ticket table isn't even in First Normal Form. Currently, every new year you would need to add a new column to show the updated pricing. This is much more easily accomplished by adding rows, not columns.
You need to create another table called TicketID, which has ID and TicketType. Modify your Ticket table to have the following: ID, price, date_effective. This will allow you to record the changing pricing like this
    1,50,1/1/2010
    1,51,2/1/2010
    1,52,8/15/2010
    1,55,1/1/2011

This will allow you to change the price whenever you need without having to add an extra column. Because you are storing a date in the last column, you can use the built in Date functions within Access to create your query.


text:
Q: R: Correctly calling a variable that contains `i` I am working with the R programming language. I have the following code that creates 100 data sets (containing a fixed component and a random component):
a = rnorm(300,10,5)
b = rnorm(300,3,1)
c = rnorm(300,12,1)
e = "original"
d = data.frame(a,b,c,e)

results <- list()

for (i in 1:100){

a = rnorm(100,10,10)
b = rnorm(100,10,10)
c = rnorm(100,10,10)
e = "simulated"

d_i = data.frame(a,b,c,e)

data_i = rbind(d, d_i)
data_i$iteration = i
 results[[i]] <- data_i

}

results_df <- do.call(rbind.data.frame, results)

At the moment, these 100 datasets have all been placed in the same file ("results_df"). Now, I want to break the "results_df" file into each of these 100 datasets (using the "iteration" column as the index):
results_df$iteration = as.factor(results_df$iteration)
X<-split(results_df, results_df$iteration)

This "X" file seems to be a "list" with each of the 100 datasets listed as follows:

I can access each of these files by calling the "index" using i , e.g.
> head(X$`1`)
          a        b        c        e iteration
1  2.141495 3.984072 12.73344 original         1
2  8.769269 4.267464 11.32566 original         1
3  5.413573 2.823608 12.06713 original         1
4 11.710470 3.710500 12.20715 original         1
5 14.423155 2.944178 10.56673 original         1
6  6.886629 2.843195 12.43074 original         1
> head(X$`2`)
            a        b        c        e iteration
401  2.141495 3.984072 12.73344 original         2
402  8.769269 4.267464 11.32566 original         2
403  5.413573 2.823608 12.06713 original         2
404 11.710470 3.710500 12.20715 original         2
405 14.423155 2.944178 10.56673 original         2
406  6.886629 2.843195 12.43074 original         2
> head(X$`98`)
              a        b        c        e iteration
38801  2.141495 3.984072 12.73344 original        98
38802  8.769269 4.267464 11.32566 original        98
38803  5.413573 2.823608 12.06713 original        98
38804 11.710470 3.710500 12.20715 original        98
38805 14.423155 2.944178 10.56673 original        98
38806  6.886629 2.843195 12.43074 original        98

My Question: I now want to write another function which performs linear regression on each of these 100 datasets, saves the regression coefficients, and places them into a single file. I tried to write the code for this:
results_1 <- list()

for (i in 1:100){

model_i <- lm(a ~ b +c, data = X$`i`)
coeff_i = model_i$coefficients

 results_1[[i]] <- coeff_i

}

results_df_1 <- do.call(rbind.data.frame, results_1)

On first glance, this appears to have worked - but this is displaying all the regression coefficients as the same. This is impossible, seeing as the regression model was run 100 times on different datasets :
#for some reason, the column names have been corrupted

hist(results_df_1$c.14.5741211250235..14.5741211250235..14.5741211250235..14.5741211250235.., main = "first coeff")

 hist(results_df_1$c..0.105285805666629...0.105285805666629...0.105285805666629.., main = "second coeff")

 hist(results_df_1$c..0.236548691738492...0.236548691738492...0.236548691738492.., main = "third coeff")

Can someone please help me fix this problem? When you use the "split()" function in R, is this the correct way to "call" the "split components" in future commands ?
model_i <- lm(a ~ b +c, data = X$`i`)

Thanks!

A: I was able to fix this problem:
a = rnorm(300,10,5)
b = rnorm(300,3,1)
c = rnorm(300,12,1)
e = "original"
d = data.frame(a,b,c,e)

results <- list()

for (i in 1:100){

a = rnorm(100,10,10)
b = rnorm(100,10,10)
c = rnorm(100,10,10)
e = "simulated"

d_i = data.frame(a,b,c,e)

data_i = rbind(d, d_i)
data_i$iteration = i
 results[[i]] <- data_i

}

results_df <- do.call(rbind.data.frame, results)

X<-split(results_df, results_df$iteration)

#####

results_1 <- list()

for (i in 1:100){

#here was the problem
model_i <- lm(a ~ b +c, data = X[[i]])

coeff_i = model_i$coefficients

 results_1[[i]] <- model_i$coefficients

}

results_df_1 <- do.call(rbind.data.frame, results_1)

par(mfrow = c(1, 3))

hist(results_df_1[,1], main = "first coeff")
hist(results_df_1[,2], main = "second coeff")
hist(results_df_1[,3], main = "third coeff")


text:
Q: Modify Open Source Project Dates I have worked on a few open source projects for several years (albeit not continuously), and have moved hosts at various times during this period.
The Open Source section of my Careers profile shows projects as starting from the date I moved to the current host. Please could we be allowed to manually modify the starting date?
There's a similar question at Careers not allowing me to modify project times, but this focuses on the project's end date.


text:
Q: The browser is not receiving the JWT cookie after deploying the app on heroku I am working on an application with backend and frontend separately. After I deployed the app on Heroku I can't get the cookie when login using the front-end application (in Postman is working). During the development on localhost it was working.
I used on the backend the 'cors' middleware with the origin set to the deployed host for frontend app and credentials set to true
app.use(cors({
    origin: 'https://assistcar-client.herokuapp.com',
    credentials: true
}));
app.options('*', cors());

Here I'm sending the JWT cookie in the end of login controller
cookieOptions = {
        maxAge: process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60,
        httpOnly: true
    }

    if (req.secure === true || req.headers['x-forwarded-proto'] === 'https') cookieOptions.secure = true;

    res.cookie('jwt', token, cookieOptions);

    res.status(200).json({
        status: 'success',
        token
    });

Also when trying to fetch from the frontend I set the credentials to 'include' (as I saw in the other posts here on StackOverflow), but it's not working, the cookie is not received by the browser after login (and the response is ok)
const response = await fetch('https://assistcar-server.herokuapp.com/api/v1/users/login', {
            method: 'POST',
            credentials: 'include',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(bodyData)
        });

        return await response.json();

Thanks for your help!


text:
Q: How to scan storage devices for recovering deleted files? I have seen apps like DiskDigger and Hexamob Recovery, which scan storage devices and allow you to recover deleted files. I was wondering if this can be done via the Android SDK, or does it require use of something else like Android NDK? Either way, can someone point me in the right direction on how this can be done? I would like to make my own implementation.
Note: This question is similar in nature to Android: deleted file(s) and message(s) recovery, but more general about what API should be used.

A: Android is running on linux, and as such, you would have to use the posix libs or the standard C ones. This is independent from android, except that you need to use NDK to integrate that functionality in your app. AFAIK, there's no droid-specific api to do that. Here's a thread that might get you going.


text:
Q: State management with useContext and useReducer and fetching data with useEffect I have a React app that manages its global state with useContext and useReducer. My BookListcomponent needs to fetch books from a server when it mounts. If fetching the books was successful they should be stored into global state.
My approach looks as follows
function BookList() {
    const [state, dispatch] = useContext(BookContext);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        BookService
            .fetchBooks()
            .then(resp => {
                setLoading(false);
                dispatch({
                    type: FETCH_BOOKS,
                    books: resp.data
                });
            });
    }, []);

    return (

            {loading
                ? "Loading ..."
                : state.books.map(book => (

{`${book.title} - $${book.price}`}
))
            }

    );
}

This works but produces the warning

React Hook useEffect has a missing dependency: 'dispatch'. Either ...

Do I have to add dispatch to the dependency array to ged rid of the warning or is there a better way?

A: The warning is not very relevant here since the doc suggests omitting dispatch from the list of dependencies of useEffect, but you can safely put it in the dependency array because its identity is always stable.
the doc says:

React guarantees that dispatch function identity is stable and won't change on re-renders.
This is why it's safe to omit from the useEffect or useCallback dependency list.


text:
Q: Capturing a "new window open" event I have an IE plugin that contains links. They open in a new window. I want to modify the behaviour so that the links open in a div. I can't make changes to the way the plugin operates so I was thinking to so something like capture the url in the new window and then close the window. Is there a way to monitor for something like a "new window open" event preferably with JavaScript?
Any pointers appreciated.

A: Try this:
<!DOCTYPE html>

Your browser does not support iframes.

    [X]


text:
Q: xpdo - insert multidimensional arrays into db-table - up to 5 rows at once I have a form in which the user can add up to 5 counters with different values, beides a lot of different other values via inputs and selects.
Most of the data shall be written to different existing database-tables, which is so far working fine for each table.
So far I used an existing script that is able to add one row to the different existing database-tables, after the form got submitted.
One of the tables is called "zaehler_test", which needs to get inserted one row for each counter from the $_POST-values the user can add in the form. This edited script is able to do that:
 $sql_str = $xpdo->prepare("INSERT INTO zaehler_test (id, k_id, z_id, zaehlertyp, befestigung, messung, wandlerfaktor, eigentumwandler, zaehlerart, spannungsebene, zugang, anmerkungen) VALUES (:id, :k_id, :z_id, :zaehlertyp, :befestigung, :messung, :wandlerfaktor, :eigentumwandler, :zaehlerart, :spannungsebene, :zugang, :anmerkungen)");

  $sql_str->bindParam (":id", $id);
  $sql_str->bindParam (":k_id", $id);
  $sql_str->bindParam (":z_id", $_POST['zaehlernummer']);
  $sql_str->bindParam (":zaehlertyp", $_POST['zaehlertyp']);
  $sql_str->bindParam (":befestigung", $_POST['befestigung']);
  $sql_str->bindParam (":messung", $_POST['messung']);
  $sql_str->bindParam (":wandlerfaktor", $_POST['wandlerfaktor']);
  $sql_str->bindParam (":eigentumwandler", $_POST['eigentumwandler']);
  $sql_str->bindParam (":zaehlerart", $_POST['zaehlerart']);
  $sql_str->bindParam (":spannungsebene", $_POST['spannungsebene']);
  $sql_str->bindParam (":zugang", $_POST['zugang']);
  $sql_str->bindParam (":anmerkungen", $_POST['anmerkungen']);

  try{
      $sql_str->execute();
  }

The table "zaehler_test" looks like this:
+----+------+------+------------+-------------+---------+---------------+-----------------+------------+----------------+--------+-------------+
| id | k_id | z_id | zaehlertyp | befestigung | messung | wandlerfaktor | eigentumwandler | zaehlerart | spannungsebene | zugang | anmerkungen |
+----+------+------+------------+-------------+---------+---------------+-----------------+------------+----------------+--------+-------------+
| 1  | 1234 | 1234 |     1      |      2      |    3    |      25       |        4        |     2      |     0          |   1    |      3      |
+----+------+------+------------+-------------+---------+---------------+-----------------+------------+----------------+--------+-------------+

So this works fine so far. But now I need to get the data from the other possible counters the user might have added in the form.
I first tried to insert the data one by one for each counter by simply dupicating the script and editing the related $_POST-variables, but this did not work.
After a lot of research I stumbled upon a script, with which it might be able to insert all data at once to the db-table, but it uses arrays for doing so.
So now after the form gets submitted I created several arrays from the posted values.
The arrays look like this:
Array "zaehler1"
Array
(
    [id] => db6aac9dbe239c0e0095afee9d74cab4_879012
    [k_id] => db6aac9dbe239c0e0095afee9d74cab4_879012
    [z_id] => 111
    [zaehlertyp] => 1
    [befestigung] => 1
    [messung] => 1
    [wandlerfaktor] =>
    [eigentumwandler] => 0
    [zaehlerart] => 1
    [spannungsebene] => 1
    [zugang] => 2
    [anmerkungen] =>
)

Array "zaehler2"
Array
(
    [id] => db6aac9dbe239c0e0095afee9d74cab4_879012
    [k_id] => db6aac9dbe239c0e0095afee9d74cab4_879012
    [z_id] => 222
    [zaehlertyp] => 2
    [befestigung] => 1
    [messung] => 1
    [wandlerfaktor] =>
    [eigentumwandler] => 0
    [zaehlerart] => 1
    [spannungsebene] => 1
    [zugang] => 2
    [anmerkungen] =>
)

Array 3 to 5 look the same, all can have different (key-)values (the numerics).
The script I found at the earlier mentioned link looks like this:
// multiple queries
$stmt = $pdo->prepare('INSERT INTO table SET memberID=:memberID, programID=:programID, date_added=NOW()');
$data = array(155, 165, 175, 185);
foreach($data as $d) {
    $stmt->execute(array(':memberID' => $memberid, ':programID' => $d));
}

I tried to adapt it to my needs and wanted first to try it with the first array only and also only with a few data, but I failed. This is what I've got so far:
// multiple queries
$stmt = $xpdo->prepare('INSERT INTO zaehler_test SET id=:id, k_id=:k_id, z_id=:z_id');
$data = $zaehler1;
foreach($data as $d) {
    $stmt->execute(array(':id' => $id, ':k_id' => $id, ':z_id' => $d));
}

By using this script I get 12 rows added (one for each array-key), which is obviously wrong. I expected to get one row added with the related values to each key. After that I wanted to try how to get this to work with those up to 5 arrays I mentioned above.
Can someone please guide me to the right direction, I'm kinda lost after several hours of trying and research.
Thank you for your time!

A:
Modx - xPDO is our name for open eXtensions to PDO. It's a light-weight ORB
  (object-relational bridge) library built directly on PDO. It
  implements the very simple, but effective Active Record pattern for
  data access

Try this:
//express each set of values in to a separate array
$data = array(
      [155, 165, 175],
      [155, 165, 175]
   );
$stmt = $xpdo->prepare('INSERT INTO zaehler_test SET id=?, k_id=?, z_id=?');
foreach($data as $d) {
    $stmt->execute($d);
}


text:
Q: Trouble getting POST to work with swift I am trying to send data from my app to a MySql database. I successfully connect to the database, through my php script, but only blank entries are recorded. ie name = "".
I think I am encoding the data incorrectly but I am not sure.
    let name = "test"
    let url = NSURL(string: posturl)
    var request = NSMutableURLRequest(URL: url!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    var postString: NSString = "name=\(name)"

This is where I believe I am making some mistake, but honestly I'm not sure. I am not very familiar with swift/iOS development at all!
    var data: NSData = postString.dataUsingEncoding(NSASCIIStringEncoding)!
    request.HTTPBody = data

Also, I was wondering if this is necessary. I saw it used in examples but am uncertain if it's of use.
    var conString: NSString = NSString(format:"%u", data.length)
    request.setValue(conString as String, forHTTPHeaderField: "Content-Length")

Finally, I make the connection
    var conn =  NSURLConnection(request: request, delegate: self)
    conn!.start()

A: NSASCIIStringEncoding should be NSUTF8StringEncoding and try to make it Asynchronous for better performance
 let posturl: String = "YOUR URL HERE"
 var url: NSURL = NSURL(string: posturl)!
 var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
 request1.HTTPMethod = "POST"
 var postString = "name=\(name)" // Key and Value
 let data = postString.dataUsingEncoding(NSUTF8StringEncoding)
 request1.timeoutInterval = 60
 request1.HTTPBody=data
 request1.HTTPShouldHandleCookies=false
 let queue:NSOperationQueue = NSOperationQueue()
 NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
       var err: NSError
       var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")
 })


text:
Q: Convert a vector of u8 bytes into a rust_decimal I am loading data from another language. Numbers can be very large and they are serialized as a byte array of u8s.
These are loaded into rust as a vec of u8s:
vec![1, 0, 0]
This represents 100. I also have a u32 to represent the cale.
I'm trying to load this into a rust_decimal, but am stuck.
measure_value.value -> a vec of u8
measure_value.scale -> a u32
let r_dec = rust_Decimal::????

A: This is the implementation I have so far, but it feels inelegant!

pub fn proto_to_decimal(input: &DecimalValueProto) -> Result<Decimal, String> {
    let mut num = 0;
    let mut power: i32 = (input.value.len() - 1)
        .try_into()
        .map_err(|_| "Failed to convert proto to decimal")?; //casting down from usize to i32 is failable

    for digit in input.value.iter() {
        let expansion: i128 = if power == 0 { expansion = *digit as i128 } else { expansion = (*digit as i128) * 10_i128.pow(power as u32) as i128 }
        num += expansion;
        power -= 1;
    }
    Ok(Decimal::from_i128_with_scale(num as i128, input.scale))
}


text:
Q: dbt + jinja Cannot cast column value to int I need Dynamic loop in dbt based on a column of the row
select id,loop_count,
{% set row_loop_cnt  %}
loop_count
{% endset %}
{% for i in range(loop_count) %}
    //creating a list
{% endfor %}
created_list as column_name
from table_name

I am getting 'str object cannot be interpreted as an integer'  error
I tried multiple way of casting like
loop_count::int 'redshift'
loop_count | int  'Jinja'
But no luck could you please help me here

A: Macros are compiled (templated) before the query is run. That means that the data in your database doesn't run through the jinja templater. When you {% set row_loop_cnt = "loop_count"%} you're just passing a string with the value loop_count into jinja, not the data from the field with that name.
From your query, I assume that the table_name table contains a field called loop_count, and that field's data includes an integer that you would like to use to repeat a value in another column.
In most databases, you can do this with SQL, and not involve jinja at all. It's possible to use the run_query macro to pull data into the jinja context, but this is slow and error-prone, and not really applicable in a situation where each row of your data wants to reference a different value.
Assuming the simplest possible implementation of // creating a list, I would write this query as:
select id, loop_count, repeat(value_col || ',', loop_count) as created_list
from table_name


text:
Q: Error setting java class as object in MainActivity android studio -- cannot resolve symbol "" I'm a beginner and I have been following several tutorials in order to parse JSON.  I am just about to compile and try to run for the first time but when I tried to make an object of my java class and have the process run when the button "click" is triggered, I get an error stating " Cannot resolve symbol "fetchData" "

package com.example.h.arbitrage;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button click;
    public static TextView data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        click = findViewById(R.id.button);
        data = findViewById(R.id.fetcheddata);

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData process = new fetchData();
                ((fetchData) process).execute();

            }
        });
    }
}

I'm also including the code for fetchData.java in case there's something in there that's causing this.
I've looked all over for the answer and it might be very obvious but I don't even have the terminology to properly research this...

import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;

import com.example.h.arbitrage.MainActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class fetchData extends AsyncTask<Void,Void,Void> {
    String data = "";

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line ="";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        MainActivity.data.setText(this.data);

    }
}

Thanks in advance for any help.


text:
Q: WLAN LED randomly blinking when there is no traffic I've got a Linksys WUSB54GC WLAN USB interface (Ralink chipset) and I'm running Debian GNU/Linux 6.0. The LED very often randomly blinks although there is no traffic in the network. I checked this with Wireshark. Sometimes, but rarely, the LED stops blinking.
The issue is present in Ubuntu and Fedora too. It was not present in Debian Lenny with Linux 2.6.28. I checked an old live cd with ubuntu 8.10 with kernel 2.6.27 and it was also OK. So I guess that's an issue with Linux kernel and its wireless driver or firmware.
Has anybody observed a similar thing? Does anybody know how to help this annoying blinking?
Thanks.

A: Wireless NICs using WPA(2) regularly renew their keys with the access point.
On top of that, no one really know why or what causes those lights to blink.  There is no established standard for when a light on those things should blink.  For all we know, as the voltage goes up, the blinking gets faster.  It is arbitrary and I would not put use the blinking light as an authority on whether network traffic exists.


text:
Q: How to ban google app engine? Someone is using google app engine to crawl through my site. Is there any way to ban the google app engine to prevent this? I don't want to let user cache the data from my site.
Is there a complete ip which google app engine uses? That will help developers be able to stop being from stolen from.

A: You can check the User Agent of the request for AppEngine-Google and deny those requests. More info about the request header can be found here:
https://developers.google.com/appengine/docs/python/urlfetch/overview#Request_Headers


text:
Q: Update variable outside of Ajax Call I have a variable settingId that determine if I will do a POST or a PUT Ajax Call:
            var settingId =  form.data('setting');
        if ((typeof settingId === "undefined")){
            method = 'POST';
            url = '{{ url("/tournaments") }}' + '/' + tournamentId + '/categories/' + categoryId + '/settings';
        }else{
            method = 'PUT';
            url = '{{ url("/tournaments") }}' + '/' + tournamentId + '/categories/' + categoryId + '/settings/' + settingId ;
        }

It works great, but when I do a POST, I need to update this variable value, so that this same test gives me a PUT, and I can't do it.
Right now, I do it like that but obviously, it is not the right way:
form.data['setting'] = data.settingId;

My Form:
<form method="POST" action="http://laravel.dev/tournaments/3/categories/2/settings/11" accept-charset="UTF-8" class="form-settings" data-tournament="3" data-category="2" data-setting="11">

...

JS:
$('.save_category').on('click', function (e) {
        e.preventDefault();
        var inputData = $('.save_category').serialize();
        var form = $(this).parents('form:first');

        var tournamentId =   form.data('tournament');
        var categoryId =   form.data('category');
        var settingId =  form.data('setting');

        console.log(tournamentId);
        console.log(categoryId);
        console.log(settingId);

        $(this).find('i').removeClass();
        $(this).find('i').addClass('icon-spinner spinner position-left');
        $(this).prop( "disabled", true );
        var panel = $(this).closest('.panel');
        var method = null;
        var url = null;

        if ((typeof settingId === "undefined")){
            method = 'POST';
            url = '{{ url("/tournaments") }}' + '/' + tournamentId + '/categories/' + categoryId + '/settings';
        }else{
            method = 'PUT';
            url = '{{ url("/tournaments") }}' + '/' + tournamentId + '/categories/' + categoryId + '/settings/' + settingId ;
        }
        $.ajax(
                {
                    type: method,
                    url: url,
                    data: inputData,
                    success: function (data) {
                        if (data != null && data.status == 'success') {
                            noty({
                                layout: 'topRight',
                                type: 'success',
                                width: 200,
                                dismissQueue: true,
                                timeout: 3000,
                                text: data.msg
                            });
                            // Change warning icon to success
                            panel.find('.status-icon').removeClass().addClass('glyphicon glyphicon-ok text-success status-icon');
                            console.log(data);
                            form.data['setting'] = data.settingId;

                        } else {
                            noty({
                                layout: 'topRight',
                                type: 'error',
                                width: 200,
                                dismissQueue: true,
                                timeout: 3000,
                                text: data.msg
                            });
                        }
                        $('.save_category').prop( "disabled", false );
                        $('.save_category').find('i').removeClass('icon-spinner spinner position-left');

                    },
                    error: function (data) {
                        noty({
                            layout: 'topRight',
                            type: 'error',
                            width: 200,
                            dismissQueue: true,
                            timeout: 3000,
                            text: data.msg
                        });
                        $('.save_category').prop( "disabled", false );
                        $('.save_category').find('i').removeClass('icon-spinner spinner position-left');
                    }

                }
        )

    });

Any Idea????

A: Just do it with jQuery:
$('form .form-settings').attr('data-setting', data.settingId);

A: Try
$(form).data( 'setting' , data.settingId );


text:
Q: How do I encode the secret for the 'create-passenger-name-record-sample-nodejs' Sabre API example? I'm trying to run the 'create-passenger-name-record-sample-nodejs' example code. It requires a secret and PCC as shown below:
  endpoint: 'https://api.test.sabre.com',
  secret: process.env.SWS_API_SECRET || '',
  pcc: process.env.SWS_API_PCC || '',
};

According to the documentation, the secret above is a base64 encoding of 'V1:userid:group:domain'.
I have created an account but it is not clear to me where to obtain the pieces necessary to construct the concatenated string above and also where to obtain the PCC.
Is anyone able to provide some guidance?
Thanks.

A: _Username and password should be provided by your account executive if you have a Sabre subscription. If you do not have a Sabre subscription, you should be able to obtain sample credentials to test in test environments. You can find your test credentials under "Applications" when you click on "My account". The procedure to encode a token, if needed, is located at https://developer.sabre.com/guides/travel-agency/developer-guides/rest-apis-token-credentials.

A: The solution is to base64 encode the ClientID. Then base64 encode the ClientSecret. Then join those results with a ':' and base64 encode the joined string. This then is used as the value of the 'secret' field in the JSON snippet above.


text:
Q: Pad a C++ structure to a power of two I'm working on some C++ code for an embedded system.  The I/O interface the code uses requires that the size of each message (in bytes) is a power of two.  Right now, the code does something like this (in several places):
#pragma pack(1)
struct Message
{
   struct internal_
   {
      unsigned long member1;
      unsigned long member2;
      unsigned long member3;
      /* more members */
   } internal;
   char pad[64-sizeof(internal_)];
};
#pragma pack()

I'm trying to compile the code on a 64-bit Fedora for the first time, where long is 64-bits.  In this case, sizeof(internal_) is greater than 64, the array size expression underflows, and the compiler complains that the array is too large.
Ideally, I'd like to be able to write a macro that will take the size of the structure and evaluate at compile time the required size of the padding array in order to round the size of the structure out to a power of two.
I've looked at the Bit Twiddling Hacks page, but I don't know if any of the techniques there can really be implemented in a macro to be evaluated at compile time.
Any other solutions to this problem?  Or should I perpetuate the problem and just change the magical 64 to a magical 128?

A: Why not use a union?
union Message
{
    struct internal_
    {
        unsigned long member1;
        /* more members */
    };
    char[64];
};

or better yet use anonymous structs
union Message
{
    struct
    {
        unsigned long member1;
        /* more members */
    };
    char[64];
};

So you can access members like this: Message.member1;
Edit: obviously this doesn't solve your greater than 64 problem, but provides a cleaner way of padding.

A: Probably the most obvious way would be to just use the ternary operator:
#define LOG2_CONST(n) ((n) <= 1 ? 0 :
                      ((n) <= 2 ? 1 :
                      ((n) <= 4 ? 2 :
                      /* ... */
                      ))))))))))))))))))))))))))))))
#define PADDED_STRUCT(ResultName, BaseName) \
  typedef union { BaseName data; char pad[1 << LOG2_CONST(sizeof(BaseName))]; } ResultName

A: How about just writing a small wrapper around the send and receive message function that handle any size message and they just allocate a larger buffer ( next power of 2 ) and memclear it, copy the struct to the beginning and send it along.

A: One way of working around the problem would be to replace the hardcoded 64 with a multiple of size(long), turning the padding into something like this:
char pad[4*sizeof(unsigned long) - sizeof(internal_)];

It's ugly but it should be portable to 64-bit.
That said, an API that requires the message size to be a power of 2 sounds a bit odd and like a design issue. Requiring the size being an even number makes sense as on some processors to pay quite a penalty for accessing data on odd addresses but your #pragma pack almost makes that inevitable.

A: You're already using #pragma pack, I don't know what compiler(s) your using specifically, but you should see if they support arguments for pack that control the alignment/padding and then you can just get rid of the padding field altogether. I know MSVC's version of pragma pack supports this, as does GCC's.

A: You can macroize this as follows (for 32-bit architecture):
#define align_step(N, shift) ((N) | ((N) >> shift))
#define align_up(N) (align_step(align_step(align_step(align_step(align_step((N)-1, 1), 2), 4), 8), 16) + 1)
#define alignment_padding(N) (align_up((N)) - (N))

Then you can apply that using the union trick or some other means. In your example:
#pragma pack(1)
struct Message
{
   struct internal_
   {
      unsigned long member1;
      unsigned long member2;
      unsigned long member3;
      /* more members */
   } internal;
   char pad[alignment_padding(sizeof(internal_))];
};
#pragma pack()

A: Use a template metaprogram. (Edited in response to comment).
#include <iostream>
#include <ostream>
using namespace std;

template <int N>
struct P
{
    enum { val = P<N/2>::val * 2 };
};

template <>
struct P<0>
{
    enum { val = 1 };
};

template <class T>
struct PadSize
{
    enum { val = P<sizeof (T) - 1>::val - sizeof (T) };
};

template <class T, int N>
struct PossiblyPadded
{
    T       payload;
    char    pad[N];
};

template <class T>
struct PossiblyPadded<T, 0>
{
    T       payload;
};

template <class T>
struct Holder : public PossiblyPadded<T, PadSize<T>::val>
{
};

int main()
{
    typedef char Arr[6];

    Holder<Arr> holder;
    cout << sizeof holder.payload << endl;

    // Next line fails to compile if sizeof (Arr) is a power of 2
    // but holder.payload always exists
    cout << sizeof holder.pad << endl;
}

A: You can get a compile-time constant for the size of the structure rounded up to a power of two using templates :
template<int N, int C = 1>
struct Recurse
{
    enum {result = Recurse<N/2, C*2>::result};
};

template<int C>
struct Recurse<0, C>
{
    enum {result = C};
};

template<typename T>
struct Calc
{
    enum {size = Recurse<sizeof(Test)-1>::result};
};

struct Test
{
    int a;
    double b;
    double c;
};

int main()
{
    std::cout << sizeof(Test) << " -> " << Calc<Test>::size << std::endl;
    return 0;
}

The padding value should then be easy.

A: union Message
{
    struct
    {
        unsigned long member1;
        unsigned long member2; //...
    };
    char pad[1 << 5]; //change 5 to whatever size you need...
};

Would be a little cleaner.

A: I like Niki's answer, especially the part with anonymous structs.
One thing that answer didn't solve was the greater-than-64-bytes problem, but that can be solved by conditionally declaring a char[128] struct member if sizeof(long)==8 and declaring char[64] otherwise.

A: And yet another template solution (robbing hugely from fizzer):
#include <iostream>
#include <ostream>
using namespace std;

template <int TSize, int PSize = 1, bool = false>
struct PadSize
{
  static const int val =
    ( PadSize <    TSize, (PSize*2), (TSize <= (PSize*2)  )    > :: val );
};

template < int TSize, int PSize>
struct PadSize <TSize, PSize, true>  // As soon as TSize is <= to PSize
{
  static const int val = PSize;
};

int main()
{
    typedef char Arr[8];
    char pad[ PadSize <sizeof(Arr)>::val  ];

    cout << sizeof pad << endl;
}

My approach is simply to keep doubling the padding size until it's at least as big as the type size.

A: Basics
Basing myself on Fizzer's answer, but with a more modern (C++17) style, and what I consider to be a nicer interface, allowing you to pad any struct/class in the following way:
#include "padded.h"

struct UnpaddedStruct
{
    unsigned char unaligned_data[5];
};

using PaddedStruct = Padded<UnpaddedStruct>;

sizeof(UnpaddedStruct) is 5, as expected.
sizeof(PaddedStruct) is 8, as wanted.
The biggest difference here is that there's no special data members (aside from possibly padding), nor do you have to write your classes in any particular way to add padding. You simply use the Padded struct for alignment, and otherwise access your struct in the exact same way you would without padding.
Here's a ready-made file you should be able to include as a header to allow
for that functionality:
#ifndef PADDED_H
#define PADDED_H
/**
 * padded.h - Padding to align types with powers of two.
 */
#include <cstddef>
#include <cstdint>
#include <limits>

/**
 * pad_size_of<T>() - Get the size required to align T to a power of two.
 * @tparam T: The type to get alignment values for.
 *
 * Return: The amount of padding required to align T to a power of two.
 */
template <typename T>
constexpr size_t pad_size_of()
{
    // Edge case. The highest number which is representable for any size type
    // is going to be one less than the number we want to align it to.
    const size_t max_of = std::numeric_limits<size_t>::max();
    if constexpr(sizeof(T) > max_of / 2) {
            return max_of - sizeof(T) + 1;
    }
    // We want to find the power of two that can fit AT LEAST sizeof(T).
    size_t power_of_two = 1;
    // There's definitely some better way to do this, but this is the most
    // straight forward way to do what it's supposed to do. It's a constexpr
    // function, so there should be no runtime overhead anyway.
    while (power_of_two < sizeof(T)) {
        power_of_two *= 2;
    }
    // Finally, our padding size is simply the difference between the two.
    return power_of_two - sizeof(T);
}

/**
 * struct Padded<T, Size> - A struct including padding for alignment.
 * @tparam T: The class to add padding to.
 * @tparam Size: The amount of padding to add to the class.
 *
 * Simple struct which can be inherited to add padding to any class. Will
 * default to figuring out the amount of padding required to align a class to
 * a power of two, then use that.
 */
template <typename T, size_t Size = pad_size_of<T>()>
struct Padded : public T
{
    /// Simple array of bytes large enough to align the class to powers of two.
    uint8_t padding[Size]{};
};

// Specialization of the above template for the base case, where no padding is
// required for alignment, so none is included.
template <typename T>
struct Padded<T, 0> : public T {};
#endif // PADDED_H

Details
For the especially interested, let's explain what's going on here.
First, I know some people dislike comments/docstrings finding them to be noisy, so let's start with the plain code with no comments:
#include <limits>

template <typename T>
constexpr size_t pad_size_of()
{
    const size_t max_of = std::numeric_limits<size_t>::max();
    if constexpr(sizeof(T) > max_of / 2) {
            return max_of - sizeof(T) + 1;
    }
    size_t power_of_two = 1;
    while (power_of_two < sizeof(T)) {
        power_of_two *= 2;
    }
    return power_of_two - sizeof(T);
}

template <typename T, size_t Size = pad_size_of<T>()>
struct Padded : public T
{
    uint8_t padding[Size]{};
};

template <typename T>
struct Padded<T, 0> : public T {};

The first bit of "magic" here is the constexpr function:
template <typename T>
constexpr size_t pad_size_of()

constexpr functions can be evaluated at compile-time, which means we can use them to figure out, e.g. class properties. We don't have to abuse structs and enums to do whatever, we simply write what we mean.
A constexpr function call may be omitted by the compiler, instead using the result of the function call directly, rather than calling it at runtime. This means there should be no binary bloat or anything, it's just a simple function the compiler can use to figure out how much padding we need.
We then define our Padded struct as a template class:
template <typename T, size_t Size = pad_size_of<T>()>
struct Padded : public T

It takes two template arguments, one being the class you want to add padding to, and the other being the amount of padding you want to add to it. It defaults to figuring that out automatically for you based on the size of the class, with the help of our pad_size_of function, so that's usually not something you have to think about. You can think about it, if you want to e.g. align to a multiple of sizeof(int) rather than a power of two, but power of two should be reasonable in most cases.
Finally, we have a specialization of our Padded struct, namely:
template <typename T>
struct Padded<T, 0> : public T {};

This is the other "magical" bit. If a struct does not require padding, it will not have padding. Simple as. This allows you to e.g. add data members to the underlying struct without having to worry about updating any padding values or whatever. If no overhead is required, there will be no overhead.
Full Example
#include <cstdint>
#include <iostream>
#include "padded.h"

/**
 * struct UnpaddedStruct - Some arbitrary struct with no padding.
 */
struct UnpaddedStruct
{
    /// Whatever unaligned data you want.
    uint8_t data[5];
};

/**
 * struct Struct - An UnpaddedStruct with extra padding.
 */
using Struct = Padded<UnpaddedStruct>;

int main(int argc, char *argv[])
{
    Struct s{'a', 'b', 'c', '\0'};
    std::cout
            << "UNPADDED: " << sizeof(UnpaddedStruct)
            << ", PADDED: " << sizeof(Struct)
            << ", CONTENT: " << s.data
            << std::endl;
    return 0;
}

Output
UNPADDED: 5, PADDED: 8, CONTENT: abc


text:
Q: vgaarb: this pci device is not a vga device : driver message I sometimes get this
 vgaarb: this pci device is not a vga device in dmesg. The screen flashes a lot at boot, and at times I can booted into tty.
Then I can ctrl+alt+f7 to get a desktop environment.
Output of dmesg: http://paste.ubuntu.com/23381803/
Any guesses guys? similar problems https://chakralinux.org/bugtracker/index.php?do=details&task_id=1332 https://bbs.archlinux.org/viewtopic.php?id=216155
Other details:

*

*Output of lspci and /var/log/Xorg.0.log
http://paste.ubuntu.com/23381786/ .

*Output of lshw http://paste.ubuntu.com/23381790/
VGA card:
$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Sky Lake Integrated Graphics (rev 07)

OS and kernel:
 ~  lsb_release -a
No LSB modules are available.
Distributor ID: neon
Description:    KDE neon User Edition 5.8
Release:        16.04
Codename:       xenial
 ~  uname -a
Linux neon 4.4.0-45-generic #66-Ubuntu SMP Wed Oct 19 14:12:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Since this might be related to nvidia:
~  dpkg -l | grep nvidia
ii  nvidia-361                                      361.42-0ubuntu2                            amd64        NVIDIA binary driver - version 361.42
ii  nvidia-opencl-icd-361                           361.42-0ubuntu2                            amd64        NVIDIA OpenCL ICD
ii  nvidia-prime                                    0.8.2                                      amd64        Tools to enable NVIDIA's Prime
ii  nvidia-settings                                 361.42-0ubuntu1                            amd64        Tool for configuring the NVIDIA graphics driver

EDIT:
Running a few more times, sometimes it also shows me a segfault which may explain:
Error: 111.183169] sddm[980]: segfault at 40 ip 0000000000000040 sp 00007fff1f7f8b78 error 14 in sddm[400000+6f000]

Output of dmesg: http://paste.ubuntu.com/23386861/
Output of cat /var/log/Xorg.0.log: http://paste.ubuntu.com/23386867/


text:
Q: API Request passing ID fetched from mongodb I´m a Java Dev so I need help from NodeJS guys!
Task: create a script that retrieves '_id', 'document', and 'corporateName' from MongoDB, then take the retrieved '_id', and pass it as a parameter to an API request. The last part should be taking 'document', 'corporateName' + 'client_id', 'client_secret' and export it into a single csv file.
It might be a very simple script! Therefore I´ve done this till now:
const {MongoClient} = require('mongodb');
const uri = "mongodb+srv://<privateInfo>/";
const client = new MongoClient(uri);

async function run() {
try {
 const database = client.db("merchant-profile");
 const ecs = database.collection("merchant_wallet");
 const api = `https://<prodAPI>/v1/merchant/wallet/${id}/oauth2`;
 const ecOpt = {_id: 1, document: 1, corporateName: 1};
 const credOpt = {client_id: 1, client_secret: 1};
 const ec = ecs.find({}).project(ecOpt);
 let id = ec.forEach(id => cred._id);
 const cred = api.find({}).project(credOpt);

 await cred.forEach(console.dir);
} finally {
 await client.close();
}
}
run().catch(console.dir);

I´m trying to understand how can I take '_id' fetched in 'ec' and pass it as a param to the 'cred' call.
This would already be awesome!
If you could help me out with the CSV issue as well it would be perfect.
So I don´t want just the answer, but understand how to do this.
Thank you all in advance!

A: This is the way I found to do it:
const { default: axios } = require("axios");
const { MongoClient } = require("mongodb");

const uri = "mongodb+srv://admin:sLKJdsdRp4LrsVtLsnkR@pp-core-prd.fy3aq.mongodb.net/";
const client = new MongoClient(uri);

async function run() {
  try {
    const database =  client.db("merchant-profile");
    const ecs =  database.collection("merchant_wallet");
    const data = [];
    await ecs.find({}).forEach(async function teste(response) {
      const id = response._id;
      const api = `https://api.pedepronto.com.br/v1/merchant/wallet/${id}/oauth2`;

      try{
        const res = await axios.get(api);
        data.push({client_secret: res.data[0].client_secret, client_id: res.data[0].client_id})
      }catch(e){
        console.log(e);
      }
    })
} finally {

    await client.close();

}

}

run().catch(console.dir);

It iterates over the find method and appends the fetched id to the uri.


text:
Q: Deleting elements from a list if they do not follow 'if' 'or' statements I am trying to get rid of unwanted variables in a list. I need to have two condition: one is if making sure the values in my array are smaller than a variable A, and the other is making sure they are not equal to another variable B.
This code dose not work:
original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
new_Ar = [s for s in original_Ar if (s != 2) or (s < 10)]

print (new_Ar)

while if I split it into two statements (instead of the or statement) - they do work:
original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
print ([s for s in original_Ar if (s != 2)])
print ([s for s in original_Ar if (s < 10)])

Any idea how can I do that in one line?

A: You have your boolean logic mixed up. You want to include all values that are not equal to 2 and are smaller than 10:
new_Ar = [s for s in original_Ar if s != 2 and s < 10]
#           *both* conditions must be true ^^^

Otherwise, you'd include s = 2, because it is smaller than ten, and you'd include s = 11 and s = 12, because both are not equal to two!


text:
Q: Parametrized surface and implicit surface Let $f$ be a function from a subset of $\mathbb{R}^2$ to $\mathbb{R}^3$. The graph of $f$ generally defines a surface. Can we find a function $F : A \subset \mathbb{R}^3 \to \mathbb{R}$ such that the parametrized surface defined by $f$ is exactly the surface $F(x,y,z)=0$ ?
One can assume regularity hypotheses if necessary.

A: Useful keyword: elimination theory.
Let's look at this one dimension down. Then you have $x=X(t)$ and $y=Y(t)$ as your parametrization. You can also write this as $X(t)-x=0$ and $Y(t)-y=0$. Now if $X$ and $Y$ are polynomials in $t$, then you can combine both equations and eliminate $t$ in the process. One way of doing so would be computing the resultant of the two left hand sides. The resultant is zero if both terms have a common zero, i.e. if there exists a $t$ satisfying both equations. Thus using the resultant of $X(t)-x$ and $Y(t)-y$ with respect to the variable $t$ will give you a suitable $F$.
In higher dimension you can do something similar. You have three equations in two variables, i.e. $X(t,u)-x=Y(t,u)-y=Z(t,u)-z=0$. You can combine pairs of these to eliminate one variable, obtaining two equations in one variable just as above. Actually you'd get a third equation from the third possible pair, but that will be adding no information. Then combine the resulting equations to eliminate the second variable. There is a chance of this process adding spurious solutions, where the two equations from the first step can only be satisfied by two different choices for the first variable. So you might want to factor the resulting implicit description to see whether it contains components not covered by the parametric form. Or you could use Gröbner bases instead of resultants, but I have less experience doing that.
If $X,Y,Z$ are not polynomials but rational functions (i.e. polynomial divided by polynomial), you might get a suitable implicit form by bringing the whole left hand side to a common denominator and then considering the full numerator. If your functions are not even rational, things will become more complicated as you likely left the well understood scope of algebraic surfaces.


text:
Q: How to get the username for a custom link I want to create a link that will change based on the user clicking the link.
The User will be signed in and be accessing their "storefront". I want to have the link be a link to their specific storefront
for example
www.mywebsite.myweb/storefront/USERNAME
where username would change based on the user clicking
I'm fairly new to this so please explain like I know nothing
Thanks!
Ben

A: $current_user = get_userdata( get_current_user_id() );
echo 'http://www.mywebsite.myweb/storefront/' . $current_user->user_login;


text:
Q: change the layout of shiny app I built a shiny app that tells you how much days are left untill it's your birthday. But visually I want the text to be in one row while it's currently like this:

I guess this should be easy but I am new to shiny and don't really get it.
This is my code:
        library(shiny)
ui <- (shinyUI(fluidPage(
  sidebarPanel(
    strong("Wann wurdest du geboren?"),
    selectInput("a1",label="Tag", choices=(c(1:31))),
    selectInput("a2",label="Monat", choices=(c(1:12))),
    selectInput("a3",label="Jahr", choices=(c(1940:year(Sys.time())))),

    mainPanel(
      verbatimTextOutput('a_out'),

      # UI output
        uiOutput("b1")
 )
))))

server <- shinyServer(function(input, output) {
  data <- reactive({
  Geburtsdatum <- paste0(input$a1,".", input$a2, ".", input$a3)
  Uhrzeit <- "00:00:01"
  Geb <- paste(Geburtsdatum, Uhrzeit)
  geburt <- strptime(c(Geb), format = "%d.%m.%Y %H:%M:%S", tz = "CET")
  geburtstag <- geburt
  year(geburtstag) <- year(Sys.time())
  gebu <- geburtstag - Sys.time()
  if(gebu < 0){year(geburtstag) <- year(Sys.time())+1}
  gebu <- geburtstag - Sys.time()
  Alter <- ceiling((Sys.time() - geburt)/365)
  runden <- function(Wert){
    trunc(Wert)
  }
  decimalpl <- function(Wert){
    Wert-trunc(Wert)
  }
  list(a = (trunc(gebu)),
       b = (runden(decimalpl(gebu)*24)),
       c = (runden(decimalpl(decimalpl(gebu)*24)*60)),
       d = (runden(decimalpl(decimalpl(decimalpl(gebu)*24)*60)*60)),
       e = (paste(Alter,".", sep="")))
  })
  output$b1 <- renderUI({
    strong(paste("Noch", data()$a, "Tage,",
                 data()$b, "Stunden,",
                 data()$c, "Minuten, und",
                 data()$d, "Sekunden bis zu deinem",
                 data()$e, "Geburtstag!"))
  })
  })

shinyApp(ui = ui, server = server)

Thank you really much!
P.S.: could I collorize the backgorund and the text, too? Or include an image?

A: as for the styling of your app, here is an example that gives a hint on how to colour your text, background and add images.
I hope this helps.
library(shiny)

ui <- shinyUI(
  fluidPage(
    sidebarPanel(style = "background-color: orange;",
      strong("Wann wurdest du geboren?"),
      selectInput("a1",label="Tag", choices=(c(1:31))),
      selectInput("a2",label="Monat", choices=(c(1:12))),
      selectInput("a3",label="Jahr", choices=(c(1940:year(Sys.time()))))
    ),
    mainPanel(
      #verbatimTextOutput('a_out'),
      tags$img(src = "http://media.kuechengoetter.de/media/735/13553229675100/geburtstag-kuechengoetter.jpg", style = "z-index: -1; position: fixed;"),
      # UI output
      uiOutput("b1", style = "color: blue;")
    )
))

server <- shinyServer(function(input, output) {
  data <- reactive({
    Geburtsdatum <- paste0(input$a1,".", input$a2, ".", input$a3)
    Uhrzeit <- "00:00:01"
    Geb <- paste(Geburtsdatum, Uhrzeit)
    geburt <- strptime(c(Geb), format = "%d.%m.%Y %H:%M:%S", tz = "CET")
    geburtstag <- geburt
    year(geburtstag) <- year(Sys.time())
    gebu <- geburtstag - Sys.time()
    if(gebu < 0){year(geburtstag) <- year(Sys.time())+1}
    gebu <- geburtstag - Sys.time()
    Alter <- ceiling((Sys.time() - geburt)/365)
    runden <- function(Wert){
      trunc(Wert)
    }
    decimalpl <- function(Wert){
      Wert-trunc(Wert)
    }
    list(a = (trunc(gebu)),
         b = (runden(decimalpl(gebu)*24)),
         c = (runden(decimalpl(decimalpl(gebu)*24)*60)),
         d = (runden(decimalpl(decimalpl(decimalpl(gebu)*24)*60)*60)),
         e = (paste(Alter,".", sep="")))
  })
  output$b1 <- renderUI({
    strong(paste("Noch", data()$a, "Tage,",
                 data()$b, "Stunden,",
                 data()$c, "Minuten, und",
                 data()$d, "Sekunden bis zu deinem",
                 data()$e, "Geburtstag!"))
  })
})

shinyApp(ui = ui, server = server)


text:
Q: How to set Constraint using Visual Formate Language for xib file I created xib file for custom navigation controller, in that xib file i have 3 UIButtons and 1 UILabel.
At runtime i will assign this xib file as navigation controller.
i need to set constraint using VFL(Visual Format Language) in ViewController.
   let tempView = Bundle.main.loadNibNamed("CustomNavigation", owner: self, options: nil)?.first as! CustomNavigationView
    self.view.addSubview(tempView)

    tempView.backgroundColor = UIColor.lightGray
    //tempView.frame = CGRect(x: 0, y: 0, width:width, height: 64)

    let backBtn = tempView.back as UIButton
    let naviTitle = tempView.naviTitle as UILabel
    let bell = tempView.bell as UIButton
    let order = tempView.order as UIButton

I need to set constraint for backBtn, naviTitle, bell, order. i set constraint like this
let views = ["backBtn": backBtn,
                 "naviTitle": naviTitle,
                 "order": order] as [String : AnyObject]

    let iconVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-20-[backBtn(60)]",
       options: [],
        metrics: nil,
        views: views)
    allConstraints += iconVerticalConstraints

    let nameLabelVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-23-[naviTitle]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += nameLabelVerticalConstraints

    let skipButtonVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-20-[order]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += skipButtonVerticalConstraints

    let welcomeHorizontalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "H:|[backBtn]-5-[naviTitle]-5-[order]|",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += welcomeHorizontalConstraints

    let topRowHorizontalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "H:|-15-[backBtn(60)]-[naviTitle]-[order]-15-|",
       options: [.alignAllCenterY],
        metrics: nil,
        views: views)
    allConstraints += topRowHorizontalConstraints

   NSLayoutConstraint.activate(allConstraints)

But it won't work

A: At first I guess you have to disable autoresizing mask
backBtn.translatesAutoresizingMaskIntoConstraints = false
naviTitle.translatesAutoresizingMaskIntoConstraints = false
bell.translatesAutoresizingMaskIntoConstraints = false
order.translatesAutoresizingMaskIntoConstraints = false

Then repair your constraints as those can't be satisfied at same time
"H:|[backBtn]-5-[naviTitle]-5-[order]|"
"H:|-15-[backBtn(60)]-[naviTitle]-[order]-15-|"

Your backBtn distance from superview can't be 0 and 15 at the same time, same for rest of those constraints.


text:
Q: Error while creating foreign relation in knex - table creation race condition I'm new to knex and haven't touched RDBMS in years (been in NoSQL land), so bear with me here.
I've got two migration files, one for tracks and one for users (tracks are owned by users). Below are the relevant files:
migrations/20190919103115_users.js
exports.up = function(knex) {
  return knex.schema.createTable('users', table => {
    table.increments('id');
    table.string('email', 50);
    table.string('first_name', 50);
    table.string('last_name', 50);
  }
};

exports.down = function(knex) {
  return knex.schema.dropTable('users');
};

migrations/20190406112728_tracks.js
exports.up = function(knex) {
  return knex.schema.createTable('tracks', table => {
    table.increments('id');
    table.string('name', 140).notNullable();
    table.integer('owner_id').notNullable();
    table
      .foreign('owner_id')
      .references('id')
      .inTable('users')
      .onDelete('CASCADE');
    table.json('metadata');
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('tracks');
};

When I run yarn knex migrate:up, I get:
migration file "20190406112728_tracks.js" failed
migration failed with error: alter table "tracks" add constraint "tracks_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete CASCADE - relation "users" does not exist

I find the official Knex documentation to be pretty lacking (it's more of a reference than anything else) and can't figure out what I'm missing. Obviously I need some way for users to be created before tracks, but don't know how.
EDIT:
It seems this is how it's done: https://github.com/tgriesser/knex/issues/938#issuecomment-131491877
But it seems wrong to just put the entire set of tables in a single migration file. I thought the point was to create one migration file per table?

A: Migration files are sorted by name before execution, so looks like your tracks file name has an earlier date, therefore it runs before creation of users.
just run npx knex migrate:make create_users, and then npx knex migrate:make create_tracks.
it will generate new files with the proper timestamp, copy your code to the new files, delete the old ones :]


text:
Q: Search items in a list, what is good to use? It is not really a issue, im just wondering I have a list with alot of names and a search function bounded to it. It is all done in jquery and just put every element on display none when it is not matched with the input
It works perfect but I am not really sure this is the 'cleanest' way to do this, cause every element gets updated with a bunch of css styles everytime.
Is it worth to try out angular or some similar solution to achieve it or a complete overkill for such a small task?
Updated:!
My current code:
    var value = $input.val(),
        $persons = $teamCatagory.find('li');

    $persons.hide();

    var found = $persons
        .filter(function () {
            $persons.hide();
            return $(this).text()
                .match(new RegExp(value, "gi"))
        })
        .show()
        .length > 0;

    if(value.length === 0 ) {
        $persons.show().removeAttr('style');
    }

    if (!found) {
        $persons.hide();
        console.log("found nothing");
    }
};