text:
Q: How to Import p7s certificate chain into keystore? I've used these commands to create my csr
keytool -genkey -alias server -keyalg RSA -keysize 2048 -keystore domain.jks -dname "CN=*.domain.com,OU=Software Development, O=Company Name, L=Asuncion, ST=Central, C=PY"
keytool -certreq -alias server -keyalg RSA -sigalg SHA256withRSA -file domain.csr -keystore domain.jks

Then I've got my certificate signed
Web Server CERTIFICATE
-----------------
-----BEGIN CERTIFICATE-----
MIIFZjCCBE6gAwIBAgIQeg8KZmYMVuy/9w/yfpEWozANBgkqhkiG9w0BAQsFADBC
MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMS
UmFwaWRTU0wgU0hBMjU2IENBMB4XDTE2MDMwNzAwMDAwMFoXDTE3MDQwNjIzNTk1
OVowFjEUMBIGA1UEAwwLKi5zZWdweS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQCk2tfnkEN7n6Qtg7wt4lbFHyBN0UW19aSjwme5/zXbLp5S0TUN
MSwxilEGFumUE700oAyT0uQBakV9m/qwrljDdZNgrR2+4VSJfMTL+fRSNQh//pls
TFV8sc6czPxnSKeT8ufsCFF50aadRnK2+GdLC5Vpfhlwfknpu7d3RI5aMFwWzSfG
YNsqShm7sJtYnwA1y3o9eG2XiDuNt6Y5+5lHEafwGxwg8gaL5MpY5wNPDNfr6sYp
YOkJi/JdgRlLnEZn2nTawJRhkODb64vZ5arteN06fBMJjw+yrhfFqt/MEwy2Odiv
WOrWgi1ODft3QHO8jd2JCX4j/apBTEm/acmtAgMBAAGjggKCMIICfjAhBgNVHREE
GjAYggsqLnNlZ3B5LmNvbYIJc2VncHkuY29tMAkGA1UdEwQCMAAwKwYDVR0fBCQw
IjAgoB6gHIYaaHR0cDovL2dwLnN5bWNiLmNvbS9ncC5jcmwwbwYDVR0gBGgwZjBk
BgZngQwBAgEwWjAqBggrBgEFBQcCARYeaHR0cHM6Ly93d3cucmFwaWRzc2wuY29t
L2xlZ2FsMCwGCCsGAQUFBwICMCAMHmh0dHBzOi8vd3d3LnJhcGlkc3NsLmNvbS9s
ZWdhbDAfBgNVHSMEGDAWgBSXwidQnsLJ7AyIMsh8reKmAU/abzAOBgNVHQ8BAf8E
BAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMFcGCCsGAQUFBwEB
BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL2dwLnN5bWNkLmNvbTAmBggrBgEFBQcw
AoYaaHR0cDovL2dwLnN5bWNiLmNvbS9ncC5jcnQwggEFBgorBgEEAdZ5AgQCBIH2
BIHzAPEAdgDd6x0reg1PpiCLga2BaHB+Lo6dAdVciI09EcTNtuy+zAAAAVNS3iEc
AAAEAwBHMEUCIQCWspEnkaLlNJNpPVDU1M0QnErjVSPI1pOQNGcXjpG03wIgCbjt
I9hCpywde6agjJyn7+nJ/TT0Bk35SLqkkYWwfm0AdwCkuQmQtBhYFIe7E6LMZ3AK
PDWYBPkb37jjd80OyA3cEAAAAVNS3iFaAAAEAwBIMEYCIQDB0lAOazP3u9pYPwEc
6VDu+PloTiKoju2Up9ANeR9qowIhAPcUsiayPGVWMuLwb842w9oCkiASjWlGj9CL
Gbadpg3AMA0GCSqGSIb3DQEBCwUAA4IBAQCuujNCOo8z69IYcQFEJkbXwcUJDEWZ
9rP7IbOY1/P9GicK//lR/RMpoZqCujsMVOrq3baAdOb27n08sD7qi9uPeCNcpAeK
EeKEXrppcG9qD6zy+yx1K6GZW4GY0iSJ5U0+ad26t0ShkH0hzPmvNv5rHe8LEAU1
sxwTuKBhyf41+6MCMbdpex0Id17IWqUpb7ZSNq2n1ilJyEeuO5gQ64XXctc6MWzF
NfhcYcaL9kSS1ENRXvLcotbuLCUg/zu1WThUm3a/6QvpWRMUCcqyBehVVNa69Av0
aq4cMMrjJ9Qtt1tZN0dXNXsZPP9rPyv+KAY3Fa15M9rHZAgfBSuNjeGG
-----END CERTIFICATE-----

INTERMEDIATE CA:
---------------------------------------
-----BEGIN CERTIFICATE-----
MIIETTCCAzWgAwIBAgIDAjpxMA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK
Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMTMxMjExMjM0
NTUxWhcNMjIwNTIwMjM0NTUxWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j
LjEbMBkGA1UEAxMSUmFwaWRTU0wgU0hBMjU2IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAu1jBEgEul9h9GKrIwuWF4hdsYC7JjTEFORoGmFbdVNcRjFlbPbFUrkshhTIWX1SG5tmx
2GCJa1i+ctqgAEJ2sSdZTM3jutRc2aZ/uyt11UZEvexAXFm33Vmf8Wr3BvzWLxmKlRK6msrVMNI4
/Bk7WxU7NtBDTdFlodSLwWBBs9ZwF8w5wJwMoD23ESJOztmpetIqYpygC04q18NhWoXdXBC5VD0t
A/hJ8LySt7ecMcfpuKqCCwW5Mc0IW7siC/acjopVHHZDdvDibvDfqCl158ikh4tq8bsIyTYYZe5Q
Q7hdctUoOeFTPiUs2itP3YqeUFDgb5rE1RkmiQF1cwmbOwIDAQABo4IBSjCCAUYwHwYDVR0jBBgw
FoAUwHqYaI2J+6sFZAwRfap9ZbjKzE4wHQYDVR0OBBYEFJfCJ1CewsnsDIgyyHyt4qYBT9pvMBIG
A1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6
Ly9nMS5zeW1jYi5jb20vY3Jscy9ndGdsb2JhbC5jcmwwLwYIKwYBBQUHAQEEIzAhMB8GCCsGAQUF
BzABhhNodHRwOi8vZzIuc3ltY2IuY29tMEwGA1UdIARFMEMwQQYKYIZIAYb4RQEHNjAzMDEGCCsG
AQUFBwIBFiVodHRwOi8vd3d3Lmdlb3RydXN0LmNvbS9yZXNvdXJjZXMvY3BzMCkGA1UdEQQiMCCk
HjAcMRowGAYDVQQDExFTeW1hbnRlY1BLSS0xLTU2OTANBgkqhkiG9w0BAQsFAAOCAQEANevhiyBW
lLp6vXmp9uP+bji0MsGj21hWID59xzqxZ2nVeRQb9vrsYPJ5zQoMYIp0TKOTKqDwUX/N6fmS/Zar
RfViPT9gRlATPSATGC6URq7VIf5Dockj/lPEvxrYrDrK3maXI67T30pNcx9vMaJRBBZqAOv5jUOB
8FChH6bKOvMoPF9RrNcKRXdLDlJiG9g4UaCSLT+Qbsh+QJ8gRhVd4FB84XavXu0R0y8TubglpK9Y
Ca81tGJUheNI3rzSkHp6pIQNo0LyUcDUrVNlXWz4Px8G8k/Ll6BKWcZ40egDuYVtLLrhX7atKz4l
ecWLVtXjCYDqwSfC2Q7sRwrp0Mr82A==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT
MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0
aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw
WjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UE
AxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9m
OSm9BXiLnTjoBbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIu
T8rxh0PBFpVXLVDviS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6c
JmTM386DGXHKTubU1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmR
Cw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5asz
PeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo4HwMIHtMB8GA1UdIwQYMBaAFEjm
aPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrM
TjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA6BgNVHR8EMzAxMC+g
LaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxzL3NlY3VyZWNhLmNybDBO
BgNVHSAERzBFMEMGBFUdIAAwOzA5BggrBgEFBQcCARYtaHR0cHM6Ly93d3cuZ2Vv
dHJ1c3QuY29tL3Jlc291cmNlcy9yZXBvc2l0b3J5MA0GCSqGSIb3DQEBBQUAA4GB
AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL
NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W
b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S
-----END CERTIFICATE-----

I also received a p7s file (domain.com.p7s)
I've tried in many different ways to import it properly into the keystore but I get the error that shows in this page https://thedomain.com/ > ERR_CERT_AUTHORITY_INVALID
What is the command to import this chain ? this is not the first time I am doing this but this time I just can't get it to work.

A: You have to import the signed certificate chain using the same alias you used to generate the keypair and CSR, and without the -trustcacerts option.
Basically something like this
keytool -import -alias server -file domain.p7s -keystore domain.jks


text: Q: AWS GLUE: Job bookmark forces job to exit/throw an error when one of the sources doesn't have updated data I am creating an AWS glue job. I need to use multiple sources and utilize job bookmark functionality on all the sources to load data incrementally. When one of the sources doesn't have updated data/file, the job fails. Is there any way or workaround in aws glue to handle this scenario

redpajama_set_name: RedPajamaStackExchange


text:
Q: $_GET multiple options create link Im using the $_GET[variable from link] - way to pass the options the user selected on my webpage, for example the post per page or the post-oder.
I was thinking to write a simple variable which would give me out the options the user selected so I could use it in my header-redirects:
if ((isset($_GET['id'])) AND($_GET['id'] != 0 )) {
    $topic_id = (int)$_GET['id'];
    $header = 'Location: topic.php?id='.$topic_id;
}
        else {
        header('Location: error.php');
        die();
        }
if ((!isset ($_GET['page'])) OR ((int)$_GET['page'] == NULL)) {
header('Location: topic.php?id='.$topic_id.'&page=1');
die();
}
else {
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ? (int)$_GET['page'] : 1;
$header = $header.'&page='.$page;
}
    if(isset($_GET['order']) AND $_GET['order'] != NULL)  {
    $order = $_GET['order'];
    $header = $header.'&order='.$order;
     }

and so on.
So I got now the options the user selected, but if I want to change one of them for a special redirect, I would need to write a string-replace-function. My question is: Is there a better way to handle many $_GET options and/or missing options? Is there any good practice? Sorry if this is a simple question.

A: With your example code, each query-string parameter you access through $_GET, such as $_GET['page'], you directly append to a $header variable, such as $header = '&page=' . $_GET['page'];.
Since each key looks like it has "rules", such as the id can't be 0, looping through a list of keys would be do-able, however, you'd also need to keep a list of rules to evaluate and it wouldn't be worth it (unless you had a lot of keys, then I could see a good benefit).
Instead, you could re-order and clean-up your code to build the full query-string and then worry about actually redirecting:
if (!isset($_GET['id']) || ((int)$_GET['id'] == 0)) {
    // invalid id; no need to process further.
    header('Location: error.php');
    die();
}

// set the ID
$queryString = 'id=' . (int)$_GET['id'];

// process the current page
$queryString .= '&page=' . ((empty($_GET['page']) || ((int)$_GET['page'] <= 0)) ? 1 : $_GET['page']);

// set the order, if available
if (!empty($_GET['order'])) {
    $queryString .= '&order=' . $_GET['order'];
}

// redirect
header('Location: topic.php?' . $queryString);
die();

While this still requires manual work for each key, it's easier to manage (in my opinion) and the actual URL/redirect is handled in only a single place. This is also a method I would use on smaller projects, ones that aren't expected to change (much) or have a dynamic/growing list of parts.
If the above method is too tedious (which can easily become the case when you have too many query-string parameters/rules), creating a list of keys and their rules would become the preferred method. Here's a quick thrown-together (and not tested) sample of this method:
// define the list of "keys" and their "rules"
$keys = array(
    'id'    => array('required' => true, 'min' => 1),
    'page'  => array('required' => false, 'min' => 1, 'default' => 1),
    'order' => array('required' => false)
);

$query = '';
foreach ($keys as $key => $rules) {
    // get the value of the key from the query-string, if set
    $value = (empty($_GET[$key]) ? null : $_GET[$key]);

    // determine if the value is valid or not
    $valid = (empty($value) || (isset($rules['min']) && ((int)$value < $rules['min']))) ? false : true;

    if ($rules['required'] && !$valid) {
        // required key but invalid value =[
        header('Location: error.php');
        die();
    } else if (!$rules['required'] && !$valid) {
        if (!empty($rules['default'])) {
            // the key is not set but has a default value
            $value = $rules['default'];
        } else {
            // the key is not required, is not set, and has no default value; skip it
            continue;
        }
    }

    // append the key/value to the query
    $query .= (($query != '') ? '&' : '') . $key . '=' . $value;
}

header('Location: topic.php?' . $query);
die();

The above is a skeleton of a key/rule-based system. The rules are very minimal and define if a key is required and what it's minimum value is (if a min is set, it assumes it's an integer and casts it via (int)). If the key is required and not set, or not a valid value, it immediately fails and redirects to error.php. If the key is not required and the value is invalid but there is a default value set, it will use that value; otherwise it will skip that key. After all value-processing is done, it appends the key/value to the query and continues on it's way.
I say that it is a "skeleton" system because it only defines two rules, min and required. You could build upon this to add additional rules such as max to set the highest value, or in_list to define a list of valid values (such as for order, you could have 'in_list' => array('asc', 'desc') and then check it with in_array($value, $rules['in_list'])). It has potential, but is only limited to your needs!


text:
Q: How to trigger custom logic after TeamCity job failed/was stopped? I need to trigger custom logic (e.g. shell script) once the TC job fails. How can I do that?

A: I already found that. It can be achieved by adding a build step that will be executed even if any of the previous steps failed or were stopped.


text:
Q: Socket.io reverting to XHR / JSONP polling for no apparent reason I think Socket.IO should choose The best method to find connection with the server
 in the series ,

  Websocket ,
  FlashSocket
  and then JSONP

but my server which is running socket.io 0.7.7 on the top of node 0.4.9 (on windows compiled with cygwin) goes to XHR/JsonP polling without any apparent reason. I have checked on all ports from 80 - 89 just to make sure , and the problem remains the same all the time.
I also checked for console logs in both the sides.
Firebug Gives No error just shows me the XHR get requests instead.
and On the Server Console it gives me :
   info - socket.io started
   debug - client authorised  // i dunno why this is occuring though
   info - handshake autorised 154845454664764
   setting request Get/socket.io/1/xhr-polling/154845454664764
   debug - setting poll timeout

.
.
. and so on
Any reason in mind guys ??

A: You may be using a version of Firefox that has WebSockets disabled.

Warning: Among other things, a key reason WebSockets is currently
  disabled by default in Firefox 4 and 5 is the discovery of a security
  issue in the protocol's design. Using WebSockets in those versions of
  Firefox in a production environment is not recommended at this time.
  If you still wish to experiment with WebSockets, you may do so by
  opening about:config and setting the network.websocket.enabled
  preference to true. You will also need to set the
  network.websocket.override-security-block preference to true in order
  to allow initializing a WebSocket connection.

A: Firefox does have websockets disabled. Standard socket.io does not have flashsocket so you have to add it to your configuration =>
io.set('transports', [                     // enable all transports (optional if you want flashsocket)
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
]);

Then it should work just fine.

debug - client authorised  // i dunno why this is occuring though

socket.io can do authorization.


text:
Q: Right to Left Alignment for UITableView I am working on an arabic app for iphone 3.0.
i was wondering if there is a way that i can convert the UITableViewCell to be right-to-left.
I want everything to be in the opposite direction.
Any thoughts?

A: Hmm.. It's really interesting) I have no solution, but few suggestions. First of all, you can try to use CGAffineTransformInvert to mirror your table. If it wil be useless, you can customize your tableView cells(make an UIImageView at the left side and UILabel with UITextAlignmentRight at the right). This is about your table. If you want to go to another view, you can just change your table view with UIViewAnimationTransitionFlipFromLeft animation instead of using UINavigationController. It's not a pretty solution, but it may do the trick) Good luck)

A: Creating your own UITableViewCell subclass is not that hard to do and is probably the first thing you'll want to do to get a custom look.  All you'll need is a custom XIB file and a bit of modified code in your cellForRowAtIndexPath function:
NSString *CellIdentifier = @"IndividualContractWithResult";
UITableViewCell *cell;

...

cell = [thisTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    // TODO: improve code by avoiding the view controller creation
    UIViewController *vc = [[UIViewController alloc] initWithNibName:@"IndividualContractWithResult" bundle:nil];
    cell = (IndividualContractWithResult_Cell *) vc.view;
    [vc release];
}


text:
Q: C# listview checked box I am trying to get the index of a listview item that has just being checked and update a database based on the item that was just checked not considering other items that were checked before
I am trying to use the checkbox to indicate a user wants a notification or not, so when a user checks the checkbox, i want to use the index of the item and set notification for that item to true but i can only get all the checkeditems indexes at once.
Any help please.
I was able to call the itemcheck event function but it considers items checked initially as well as items checked by user.
I managed to separate the items checked initially using a boolean function "Item_checked by user"
 ` private static bool checked_by_user;
    private void courseworks_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (checked_by_user == true)
        { //do something
        }
        else ;//do nothing

    }`

Now, I want to be able to take the bar_ref_id of only the line that was just checked, My list view is created from a database as below
foreach (var item2 in CW_query2)//for each CW
            {
                if (item.Status == true)
                {
                    ListViewItem items = new ListViewItem(new[] {//adds items into list view, per column
                    item2.Module_Code, item2.Title, item2.Due_Date.ToString("dd/MM/yy"),"Submitted",item.Bar_Ref_ID
                });
                    courseworks.Items.Add(items);
                }
                else
                {
                    ListViewItem items = new ListViewItem(new[] {//adds items into list view, per column
                    item2.Module_Code, item2.Title, item2.Due_Date.ToString("dd/MM/yy"),"Not-Submitted",item.Bar_Ref_ID
                });
                    courseworks.Items.Add(items);

                }

I hope my added info helps.
Thanks in advance

A: If you're already getting the subscriptions from the database and setting the Checked property for each item according to the the user's subscription, wouldn't it be easiest to use the checkboxes' CheckedChanged Event? It's hard to tell what your implementation might be, but you should be able to have one function for when the box is unchecked (removing a subscription), and another function for when the box is checked (adding a subscription).
If you are able to provide some code, I might be able to be more specific.
More Specific
In your ItemChecked event, .NET exposes the object sender and ItemCheckEventArgs e as the parameters of the event. Inside that function, you can look at the sender to get the ListViewItem that has been checked/unchecked, and you can look in e to retrieve the index of that item in the ListView (in case you can use the index to easily change data in your database). Here's a brief example I'm going to almost steal straight from Microsoft:
private void ListView1_ItemCheck1(object sender, ItemCheckEventArgs e)
{
    ListViewItem item = (ListViewItem)sender

    if (e.CurrentValue==CheckState.Unchecked)
    {
        Unsubscribe(e.Index, currentUserID);
          /*You can pass the Index of the ListViewItem that caused the event
          to a method that will update your database (I would find it easier
          to program a function that takes the current user's ID as a parameter)*/

        Unsubscribe(item.Name, currentUserID);
          /*OR this might be a better way for you to reference what subscription
          should be cancelled (again, in addition to a UserID)*/
    }
    else if((e.CurrentValue==CheckState.Checked))
    {
        Subscribe(e.Index, currentUserID);
    }
}

private void Unsubscribe(int index, int userID)
{
    //unsubscribe the referenced userID from the subscription at index
}

private void Unsubscribe(string subscriptionName, int userID)
{
    //unsubscribe the referenced userID from the subscription called subscriptionName
}

I am unable to provide a more specific example for your second bit of code, because I'm not quite certain what it's doing. It looks like you might be doing something more complicated than the code example above can handle, but perhaps the code will assist you.


text:
Q: Merge 2 transparent PNG images with PHP GD library I am trying to combine two transparent PNG images. The second PNG image should have 50% opacity.
The issue:
If the second PNG covers only the non-transparent pixels of the first PNG, then everything is fine.
If the second PNG has areas which cover the transparent pixels of the first PNG, then these areas become black.
The code:
<?php

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    $cut = imagecreatetruecolor($src_w, $src_h);
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}

$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150

$merged_image = imagecreatetruecolor(300, 300);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300);
imagecopymerge_alpha($merged_image, $image2, 0, 0, 0, 0, 150, 150, 50);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
imagepng($merged_image);

?>

A: How about if you try this instead?  It works for me.
<?php

$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150
$merged_image = imagecreatetruecolor(300, 300);

// DEFINE MAGENTA AS THE TRANSPARENCY COLOR AND FILL THE IMAGE FIRST
$transparentColor = imagecolorallocate($merged_image, 255, 0, 255);
imagecolortransparent($merged_image, $transparentColor);
imagefill($merged_image, 0, 0, $transparentColor);

imagesavealpha($merged_image, true);

imagealphablending($image1, false);
imagecopyresampled($merged_image, $image1, 0, 0, 0, 0, 300, 300, 300, 300);
imagealphablending($image1, true);
imagedestroy($image1); // FREE UP SOME MEMORY

imagealphablending($image2, false);
imagecopyresampled($merged_image, $image2, 0, 0, 0, 0, 300, 300, 150, 150);
imagealphablending($image2, true);
imagedestroy($image2); // FREE UP SOME MEMORY

imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
imagepng($merged_image);

?>

It took me a lot of experimenting in this.  I hope this helps you or someone else who may stumble upon this.


text:
Q: SailsJS Installable Hook not executing the beforeCreate override I tried adding an installable hook sails-hook-myoverride that looks like this:
let carryOn = (values, proceed, previous) => _.isFunction(previous) ? previous(values, proceed) : proceed();
module.exports = function (sails) {
  return {
    initialize: function (cb) {
      sails.after(['hook:orm:loaded'], function () {
        _.each(sails.models, (model) => {
          let previousBeforeUpdate = model.beforeUpdate;
          model.beforeUpdate = function (values, proceed) {
            console.log("myoverride::beforeUpdate", values);
            return carryOn(values, proceed, previousBeforeUpdate);
          };

          let previousBeforeCreate = model.beforeCreate;
          model.beforeCreate = function (values, proceed) {
            console.log("myoverride::beforeCreate", values);
            return carryOn(values, proceed, previousBeforeCreate);
          };
        });

        cb();
      });
    }
  }
};

Then in my Test model I added both beforeUpdate and beforeCreate methods:
  beforeUpdate: function (values, cb) {
    console.log('Test::beforeUpdate');
    cb();
  },

  beforeCreate: function (values, cb) {
    console.log('Test::beforeCreate');
    cb();
  }

And then I called POST on http://localhost:1337/test to test it.
Surprisingly, sails printed only Test::beforeCreate and not myoverride::beforeCreate as well, as I was hoping it would.
Google did not help and neither did Sails documentation :(
I'm completely lost at the moment...

A: OK, apparently, using sails.after(['hook:sockets:loaded'], function () { works for some reason...


text:
Q: How to handle raw data where a column may contain more than 1 entry per row? I have some data I would like to export (happens to be from Ruby, but that's unimportant) into a generic format for further analysis. Unfortunately, some records/lines/data entries may contain greater than 1 value (or 0, for that matter) for a given column.
For example, a person may be wearing sunglasses AND a hat. There are multiple columns like this.
I'm not sure how to handle collections of data that ideally could fall under the same column in a generic format (I need to import this data into other software, ideally including Excel).
The only simple, generic method I can think of is to have a column for each potential piece of data and treat it as a boolean. But I'd rather not, since then I would end up with over 300 columns. And then I'd also have to include a secondary CSV file that specified which columns belong to which categories.

A: If you want to output that data to a csv file, you could group the data into one field using a different separator:
John,sunglasses|hat,other,fields

Or using the same separator, but then the field needs to be quoted (and quotes already inside the field would need to be escaped with another quote):
John,"sunglasses,hat",other,fields

Or, if the number of other fields is not large, you could use a row for each value:
John,sunglasses
John,hat

Or you could use xml:
<record>
    <name>John</name>
    <options>
        <option>sunglasses</option>
        <option>hat</option>
    </options>
</record>

It all depends on how you want to process the exported data.


text:
Q: automatizar una tarea con autoit Soy nuevo utilizando autoit, pero necesito automatizar una tarea con este programa.
necesito analizar una formula que ya esta en una celda en excel y si esa formula tiene una g remplazarla por una h
esta es la formula.
=CONTAR.SI.CONJUNTO('Sct Desarrollo Economico'!$G$6:$G$29;"QUIMICO";'Sct
 Desarrollo Economico'!$T$6:$T$29;"No aceptable o aceptable con control
 especifico")

no se que codigo utilizar para decirle que me lea ese texto y si encuentra una g que lo cambia por una h.

A: Puedes utilizar 1 expresion regular para localizar 1 caracter cualquiera dentro de 1 cadena (en este caso la letra g).
Busca StringRegExp en la ayuda de autoit y veras como solucionarlo.


text:
Q: showing and hiding content on different screen sizes I have used a collapsible button which shows only on mobile and tablet screen. But when the "Show Less" button on mobile is tapped, the content on desktop also hides which I do not want. How do I fix that?

function myFunction() {
    var x = document.getElementById("myDIV");
    console.log(x.style.display);
    if (x.style.display === "none" || !x.style.display) {
      x.style.display = "block";
      document.getElementById("moreButton").innerText = "Show Less";
    } else {
      x.style.display = "none";
      var a = document.getElementById("servicenav");
      document.getElementById("moreButton").innerText = "Show More";
      a.click();
    }
  }
  window.onresize = function(event) {
    if(event.currentTarget.outerWidth >= 1026){
        console.info("showing");
        $("myDIV").show();
    }else{
        console.info("hiding");
        $("#myDIV").hide();
    }

}
<div id="myDIV">
 <button class="get-started-btn morebutton" id="moreButton" onclick="myFunction()">Show More</button>
</div>


text:
Q: Does adding another video card hugely reduce the strain on the first? I've been playing a game which is resource-intensive as it is, but I've since discovered that it causes my video card (which has three monitors connected) to exceed temperatures of 70'C. The framerate when it reaches this temperature is not intolerable but I worry about my card being damaged.
If I added a second video card, thereby reducing the load on the first, plugged only the game monitor into one of them and leaving the other two monitors in the other, that should theoretically allow the first video card to focus entirely on the game without having to support two extra screens of desktop.
What concerns me about this is that one of the video cards will be blowing air at the other one. Is this likely to cause any problem?

A: If you only have 1 gaming screen and 2 desktops, 2 plain desktops will not significantly burden the GPU.
The real issue is how under powered you current GPU is for this game.  If you have trouble reaching 30fps, and you CROSSFIRE or SLI then both cards will run at max in an effort to give you 60fps.
Most monitors only support 60hz, and if you have vsync ON then the GPU will not make any effort to generate frames higher than that.  Depending on game settings it could also use the additional GPU to increase the quality of the images displayed.
In short, it could lower your primary GPUs load, but it could just max both out in order to increase frames or image quality.  In addition some games don't support CROSSFIRE and/or SLI so there won't be any benefit in those conditions.
If you add a second video card in non CROSSFIRE/SLI at most it will reduce the burden by 10%, and the game will expand and consume that 10%.

A: I would say probably invest in a better cooling system instead, if the quality of the game isn't bad, and your not getting terrible frame rates then maxing out the video card wouldn't hurt it any more than normal wear an tear, and cooling it would stop it from over heating like you said it was doing.


text:
Q: Spot erroneous row data frame I have a data frame like this
 head(data)
              V1      V2  V3 V4    V5  V6    V7
1 458263182005000000 1941 2 14 -73.90 38.60 US009239
2 451063182005000002 1941 2 14 -74.00 36.90 US009239
3 447463182005000000 1941 2 14 -74.00 35.40 US009239
4 443863182105000000 1941 2 15 -74.00 34.00 US009239
5 436663182105000001 1941 2 15 -74.00 32.60 US009239
6 433063182105000000 1941 2 15 -73.80 31.70 US009239

but when I do
data <- read.table("data.dat",header=F,sep=";")

I get this error
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  could not allocate memory (2048 Mb) in C function 'R_AllocStringBuffer'

How can I determine in which row something is going wrong (e.g. the format is different)?
Many thanks

A: R says can not allocate memory. So you can check how large is the dataset and your computer memory.

A: despite this is an old question...
I think R_AllocStringBuffer
 does not have to do with the overall memory of your computer. Which is also the optionen in this thread:
R could not allocate memory on ff procedure. How come?
Maybe check the delimiter "," or ";". It seems to create a huge string...


text:
Q: Outputting from a dictionary of class objects to a worksheet range I am working with sets of timesheet data - where people record their time against clients and they give a free text narrative to describe the work they did.
When it comes to billing for the time, a report is produced which has many lines of data, each line containing things like hours, employee and the narrative they wrote.  When billing for the time, similar lines of time need to be grouped together into a standard description which the client understands.  So a key task of this work is to assign Billing Categories to the lines to group like lines together, and then report on them.
I have build an Excel tool to help with all sorts of aspects of this work, but a major enhancement I am working on is for the tool to build itself a referential 'database' of Narratives and Billing Categories.  It will then use this referencing to predict the Billing Category that could be assigned to new lines of timeline data in future, saving the person doing the billing a lot of time assigning the standard Billing Categories themselves.
So to do this, I thought it best to create a class object called 'Narrative' with properties which store the info I need - such as Billing Category, frequency of matches etc.  I am then reading in historic data of previous assignments of Billing Categories to Narratives and storing those items in Objects which are collected together in a dictionary object.
I have decided on this approach because the use of a dictionary is convenient because of things like the ability to check if a Narrative already exists - if it does then the new instance being read in does not get added to the dictionary.
This works OK, but I want to be able to output the items stored within the Narrative Objects held in the Dictionary to a worksheet range.  Below is the code I use for this :
Sub OutputDict()

Dim counter As Long
counter = 1

Dim strKey

For Each strKey In dict_Narratives.Keys()

Worksheets("Output").Range("A" & counter).Value = dict_Narratives.Item(strKey).Narrative
Worksheets("Output").Range("B" & counter).Value =     dict_Narratives.Item(strKey).BillCat
Worksheets("Output").Range("C" & counter).Value =     dict_Narratives.Item(strKey).DateIndex
Worksheets("Output").Range("D" & counter).Value =     dict_Narratives.Item(strKey).Frequency
counter = counter + 1

Next

End Sub

This code works, but unfortunately takes a stupid amount of time to output the data!  Is there a more efficient way to do this - perhaps putting the dictionary of data into an array object or something, and then dumping the array out in bulk to a defined range?  Maybe this could work faster because it isn't iterating cell by cell like my code above is doing?  I have no idea how to get the object properties within the dictionary into an array though.  Any help much appreciated!
EDIT - HERE IS THE ANSWER...
I didn't have much luck looking at the page that was linked to where apparently there was a duplicate of my question, but having read around I have sussed out a solution.  I needed to loop through my dictionary and add the items to arrays.  Then spitting them out to a range on a worksheet.  This is infinitely quicker than looping through cells for doing the outputs.  My code for doing this is :
Sub KeysToSpreadSheet()

Dim strKey
Dim vArrNarrative As Variant
Dim vArrBillCat As Variant
Dim vArrDateIndex As Variant
Dim vArrFrequency As Variant

ReDim vArrNarrative(1 To 1) As String
ReDim vArrBillCat(1 To 1) As String
ReDim vArrDateIndex(1 To 1) As String
ReDim vArrFrequency(1 To 1) As String

For Each strKey In dict_Narratives.Keys()

vArrNarrative(UBound(vArrNarrative)) = dict_Narratives(strKey).Narrative
ReDim Preserve vArrNarrative(1 To UBound(vArrNarrative) + 1) As String

vArrBillCat(UBound(vArrBillCat)) = dict_Narratives(strKey).BillCat
ReDim Preserve vArrBillCat(1 To UBound(vArrBillCat) + 1) As String

vArrDateIndex(UBound(vArrDateIndex)) = dict_Narratives(strKey).DateIndex
ReDim Preserve vArrDateIndex(1 To UBound(vArrDateIndex) + 1) As String

vArrFrequency(UBound(vArrFrequency)) = dict_Narratives(strKey).Frequency
ReDim Preserve vArrFrequency(1 To UBound(vArrFrequency) + 1) As String

Next

Sheets("Sheet1").Range("B2:B" & UBound(vArrNarrative) - 1) = Application.Transpose(vArrNarrative)
Sheets("Sheet1").Range("C2:C" & UBound(vArrBillCat) - 1) = Application.Transpose(vArrBillCat)
Sheets("Sheet1").Range("D2:D" & UBound(vArrDateIndex) - 1) =     Application.Transpose(vArrDateIndex)
Sheets("Sheet1").Range("E2:E" & UBound(vArrFrequency) - 1) =     Application.Transpose(vArrFrequency)

End Sub


text:
Q: Disable csTransPie for a specific element I use the library csTransPie.
How to disable the transformation for a specific element as an <input type="file">?

A: Towards the end of the file csTransPie.js (the unminified version), you'll find $.fn.cTP = function() { ... inside which you'll find:
$(':checkbox',this).cTPCheckBox();
$(':radio',this).cTPRadio();
$(':file',this).cTPFile();
$('select',this).cTPSelect();

Change this to:
$('.styleme:checkbox',this).cTPCheckBox();
$('.styleme:radio',this).cTPRadio();
$('.styleme:file',this).cTPFile();
$('select.styleme',this).cTPSelect();

And add the class styleme for all the elements you want styled by csTransPie. That should do it.

A: Add your item after the page is loaded:
HTML

jQuery


text:
Q: What is the proper way to start a driver on boot? I have succeded (full story here) on installing some ethernet card that, according to the docs, must be manually started:
# modprobe e1000bp

I would like this driver startup to be performed on boot time.
What is the proper method to achieve this?
I thought about adding the command to /etc/rc.local, but for PPTP or OpenVPN connections there are another methods that are supposed to be more clean, so I was wondering if the same could be told for the drivers startup.

A: On Debian and derivatives (Ubuntu, Mint, elementary, …), modules listed in /etc/modules (one per line, and you can specify arguments) are loaded at boot time.
On systemd-based systems, modules listed in /etc/modules-load.d/*.conf (one per line) are loaded at boot time.
However you don't normally need to load a module explicitly. For most hardware, Linux will automatically detect the hardware and load the appropriate module. Linux finds the right module through a database stored in /lib/modules/VERSION/modules.alias which is populated from declarations in the module's source code. This answer explains the full process.
Put the .ko file that you compiled somewhere under /lib/modules/VERSION/ (you need to do that anyway to get modprobe to find it) and run depmod -a as root. This will update the modules.aliases database. After that, the module will be loaded automatically during startup, when the kernel detects the hardware (or rather when the module loading process starts, since the hardware is detected early during boot time).
If your hardware is also supported by a module that's provided by your distribution, but the distribution's driver is buggy, then I don't think there's an easy way to force one of the modules to be used. In this case, you should add the module you compiled to /etc/modules and blacklist the standard module by adding a line blacklist MODULE_NAME to /etc/modprobe.conf.

A: I'd be putting the driver into the /etc/modules (Debian, Ubuntu, Mint, etc.) or /etc/modules.conf (Fedora, RHEL, CentOS, Arch Linux, etc.) file.


text:
Q: GitHub Projects Beta - How to get the data from a view in the API My company is using the new GitHub projects beta and we're really enjoying the experience, but we're facing a problem and it is how to export the data from a specific view (or even all the data) with all the custom columns that we have.

The ideal solution for us is to get this same data as JSON using the API.
Using https://api.github.com/orgs/.../issues does not work because the issues does not have the custom columns that we create inside the project, and https://api.github.com/orgs/.../projects does not have the data of the issues.
Any idea or work-around to get this data easily using APIs?

A: After reading the feedback post on GitHub, it's not possible to do it with API, just GraphQL, at least for now.
So my problem was solved with this useful code.
To get the first 100 project from your organization and their ID:
query{
    organization(login: "MY_ORG") {
      projectsNext(first: 20) {
        nodes {
          id
          title
        }
      }
    }
  }

To get the first 100 issues and drafts from a specific project:
{
  node(id: "My_Project_ID") {
    ... on ProjectNext {
      items(first: 100, after: null) {
        edges {
          cursor
        }
        nodes {
          content {
            ... on Issue {
              title
              assignees(first: 1) {
                nodes {
                  login
                }
              }
              milestone {
                title
              }
              labels(first: 5) {
                nodes {
                  name
                }
              }
              repository{
                name
              }
            }
          }
          fieldValues(first: 15) {
            nodes {
              value
              projectField {
                name
                settings
              }
            }
          }
        }
      }
    }
  }
}

Those codes can be easily tested in THIS LINK


text:
Q: Is there a way to implement custom in app upgrade in windows phone 7? I have a few Windows phone 7 app developed with Windows phone 7.1 SDK. Currently, I'm showing ads in all those free apps. I would like to provide an option to remove ads from the app and allow user to buy the app when they click on it. I know there are such in-app purchase api for windows phone 8. Does anyone know anything about similar api in wp7 or to implement similar thing for windows phone 7 in a custom way?
I see 9gag app by Rudy Huyn (http://www.windowsphone.com/en-us/store/app/9gag/91000c5c-9943-43b8-aa65-7609d91057ef) does it but I'm not sure how he does it. When I click remove ads in this app it take me to the paid version of the app. But there are no separate two apps in the store, like we do - one app as normal and another as Pro.
Any help?

A: You can publish a trial app. This way users can download it for free and then buy if they like it.
Here you can fin tutorial for creating trial apps - http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff967558(v=vs.105).aspx .
´
Now I can also show you how to take the user to the Store to see the app's listing with the Buy button:
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
marketplaceDetailTask.Show();

Please note, that this will work only with published app, not in debugging (the listing is not yet there in Store). Also - there are more useful tasks like MarketplaceReviewTask, you can take a look at it too.
UPDATE:
We figured a second way to do this while maintaining the free status of the app in store. Basically you need to publish a free app and a private paid app. Now using MarketplaceDetailTask you can point the user to the paid app by supplying it's GUID:
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();

marketplaceDetailTask.ContentIdentifier = "PAID-APPS-GUID";
marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;

marketplaceDetailTask.Show();

That said, you need to publish the paid one first to find out it's Store GUID that you can then insert into the public free one.


text:
Q: How do I change the 'created' stamp timezone dynamically in CakePHP I can change the PHP time zone, but the database is still stamped with the server time. How can I change this so it shows the correct time zone? It's dynamic based on which item a user is loaded in to - so I need to be able to change at runtime.

A: For CakePHP 3.x, please open config/bootstrap.php file. Make search for date_default_timezone_set. Set it as you want. I set it as date_default_timezone_set('Asia/Dhaka'); for my time zone. You can get your time zone from http://php.net/manual/en/timezones.php
If it's not working, please also open config/app.php file. Make search for timezone. In your Datasources connection set 'timezone'=>'Asia/Dhaka'


text:
Q: List iterator not incrementable? - Run-Time Error I was trying to fit list creation in a class, but ran into this run-time error called:

Debug Assertion Failed! Expression: list iterator not incrementable

I can't figure out what the problem is. Here's the code:
// Core.cpp //

#include "Core.h"

class List {
private:
    int Size;
    int Values;
    list<int> Data;
    list<int>::iterator IT;
public:
    List(int S, int V) {Size = S; Values = V;}
    void MakeList();
    void TargetElement(int Element);
    void ChangeElement(int Value);
    void DisplayList();
};

void List::MakeList() {
    list<int> Data(Size, Values);
    list<int>::iterator IT = Data.begin();
}

void List::TargetElement(int Element) {
    advance(IT, Element);
}

void List::ChangeElement(int Value) {
    list<int>::iterator INSERT = Data.begin();
    Data.insert(INSERT, Value);
}

void List::DisplayList() {
    list<int>::iterator OUTPUT;
    for(OUTPUT = Data.begin(); OUTPUT != Data.end(); OUTPUT++) {
        //cout << *OUTPUT << endl;
    }
}

int main() {

    List Container(10, 0);
    Container.MakeList();
    Container.TargetElement(3);
    Container.ChangeElement(20);
    Container.DisplayList();

    cin.get();
    return 0;
}

Any suggestions on how I could fix this issue?
EDIT: I looked everywhere for an answer and I still can't seem to find the solution. Debugging and finding the break-point didn't help either.

A: IT is invalid within TargetElement() because IT it is an iterator obtained from the local variable Data within MakeList() as Data is redeclared:
void List::MakeList() {
    list<int> Data(Size, Values);          // 'Data' is destructed when
    list<int>::iterator IT = Data.begin(); // this method returns.
}

I am unsure why MakeList() even exists, perform the initialization within the constructor:
List(int S, int V) : Size(S), Values(V), Data(S, V) {}

and remove MakeList(). If you choose this approach note that Size and Values can be removed from the class as they are not required outside of construction.

A: For starters, this makes a local list<int> called Data, then a local iterator called IT assigned to its first element. This has not doing anything to your member variables Data and IT whatsoever.
void List::MakeList() {
    list<int> Data(Size, Values);
    list<int>::iterator IT = Data.begin();
}

Should likely be:
void List::MakeList() {
    Data.resize(Size, Values);
    IT = Data.begin();
}

Run with that and see where it takes you.

A: The problem is here:
void List::MakeList() {
    list<int> Data(Size, Values);
    list<int>::iterator IT = Data.begin();
}

This doesn't initialize the Data and IT members of the class, it just creates local variables called Data and IT which disappear once MakeList returns. To initialize those members, change the constructor to:
List(int S, int V) : Data(S, V), IT(Data.begin()), Size(S), Values(V)
{
}

By the way, you don't need the Size member because std::list already stores its size (you can get it by calling std::list::size).

A: void List::MakeList() {
    list<int> Data(Size, Values);
    list<int>::iterator IT = Data.begin();
}

This is creating two local variables that shadow the member variables of your class. You are getting the runtime error because the IT member variable of your class is never set to an iterator of an actual list object. What you want is to merge MakeList and your constructor. This is what constructors are for.


text:
Q: Storing checkbox value in mysql database if checked I have checkbox and radiobox in my user settings form. If a user checks a box, I want to save its value into the mysql database. Later, I'll also need to retrieve it according to user selection. How can I do this?

A: First you'll need a section in your table for the user
radio_checked ( a bool would work, have a function when you read it back that 1 = yes and 0 = no. )
you will you use the POST_ function to post the information to the database as well so a sample code would look like this
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>

 <?php

 $con=mysqli_connect("localhost","$username","$password","$my_db");

  if $_POST['sex'] {
        $gender = $_POST[sex]
        }

 mysqli_query($con,"INSERT INTO Persons(gender) VALUES ('$_POST[sex]')");

?>

From there you will make a function that selects and calls the row and sets the value of your information and test the fields that you need


text:
Q: How can I get a summary of my cvs conflicts when doing a cvs update on the command line? Is there an easy way to get a conflict summary after running a cvs update?
I work on a large project and after doing some work I need to do an update.  The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.
The solution needs to work from the command line.
If my normal output is:
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt

I want my new output to be:
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt

Conflict Summary:
C src/file3.txt

I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.

A: Given the specification, it seems that you need a minor adaptation of Martin York's solution (because that only shows the conflicts and not the normal log information).  Something like this - which might be called 'cvsupd':
tmp=${TMPDIR:-/tmp}/cvsupd.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
cvs update "$@" | tee $tmp
if grep -s '^C' $tmp
then
    echo
    echo Conflict Summary:
    grep '^C' $tmp
fi
rm -f $tmp
trap 0
exit 0

The trap commands ensure that the log file is not left around.  It catches the normal signals - HUP, INT, QUIT, PIPE and TERM (respectively) and 0 traps any other exit from the shell.

A: I don't have cvs handy what is the exact format of the output of cvs update
I seem to remember C <filename>
If so you could use:

cvs update | tee log | grep "^C"

The full output of cvs is saved into log for use at another point.
Then we grep for all lines beginning with 'C'
Hope that helps.


text:
Q: Control a youtube video in WebView Programmatically I am loading a youtube video in a webview and it works fine, what i wan't is to be able to control the video (i.e start , stop etc.) programmatically.
I tried a few things and it didn't work
 String playVideo= "";
 myWebView = (WebView) findViewById( R.id.Webview );
 myWebView.getSettings().setJavaScriptEnabled(true);
 myWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
 myWebView.loadData(playVideo, "text/html", "utf-8");
 myWebView.loadUrl("javascript:playVideo()");

A: You can look at how I'm doing it in this library: android-youtube-player.
You can start by looking at the WebView class.
The idea of calling  webview.loadUrl("javascript:playVideo()"); is correct. But you need to wait for the IFrame library to be loaded and ready.

A: AFAIK, developer can't control that.
Even if developer control that by finding html element by getElementById method and click it, it'll be blocked if Google change the html structure.
I recommend the way is being provided by Google officially.
https://developers.google.com/youtube/android/player/


text:
Q: which file extensions are dedicated to an application in OSX Is there a way to find out which file extensions are dedicated to an app?I don't mean dedicating in with "always open file with app" from finder dialog. I mean the other way round. Start with the app and find out which extensions are dedicated to it.
Thanks for a hint.


text:
Q: how can I animate a circle over the curve? I'm trying to put the circle over the curve but the operation generates an error, and I don't found how avoid this problem.
\documentclass[]{standalone}
\usepackage{animate}
\usepackage{tikz}

\begin{document}

\begin{animateinline}[poster=first,controls]{10}
    \multiframe{25}{imdeg=0+1}{
        \begin{tikzpicture}[line cap=round,line width=3pt]
        \clip (-3,-3) rectangle (3,3);
        \path [fill=red] (0,0) circle (3pt);
        \path [fill=white] (0,0) circle (2pt); % círculo do ponteiro
        \draw[line width=1.2pt,color=blue,smooth,samples=100,domain=-5:5]   plot(\x,{(\x)^(2.0)});
        \draw[] (-5+\imdeg*0.4,(-5+\imdeg*0.4)^2) circle (2pt);
        \end{tikzpicture}
    }
\end{animateinline}
\end{document}

The problem is in (-5+\imdeg*0.4)^2, if the curve is y=x, then I'll use (-5+\imdeg*0.4) without the ^2 and works perfectly, but when I put ^2 .....ERROR!!!
Thanks for the help.

A: You have error in writing of the following coordinate:
\draw[] (-5+\imdeg*0.4,(-5+\imdeg*0.4)^2) circle (2pt);

Correct is:
\draw[] (-5+\imdeg*0.4,{(-5+\imdeg*0.4)^2}) circle (2pt);

If you like to nest paranthesis (...) inside of some coordinates, you had to enclose them with curtly braces. Complete code
\documentclass[]{standalone}
\usepackage{animate}
\usepackage{tikz}

\begin{document}

\begin{animateinline}[poster=first,controls]{10}
    \multiframe{25}{imdeg=0+1}{
        \begin{tikzpicture}[line cap=round,line width=3pt]
        \clip (-3,-3) rectangle (3,3);
        \path [fill=red] (0,0) circle (3pt);
        \path [fill=white] (0,0) circle (2pt); % círculo do ponteiro
        \draw[line width=1.2pt,color=blue,smooth,samples=100,domain=-5:5]   plot(\x,{(\x)^(2.0)});
        \draw[] (-5+\imdeg*0.4,{(-5+\imdeg*0.4)^2}) circle (2pt);
        \end{tikzpicture}
    }
\end{animateinline}
\end{document}

now works fine:


text:
Q: Source .bash_rc when running su in script I'm writing a script that supposed to be ran with sudo permissions.
But then I need to execute a command from an another user sourcing it's .bash_rc where there are some env variables are overloaded and then use it in a command.
For example. I need to print the PATH variable for the user:
sudo -s -u ${USER_NAME} source ~/.bash_rc; echo $PATH

But instead it prints PATH for a user running the script.
I've also tried a lot of other options (with su or passing a rcfile) but none of them seems to work.
How could I deal with it?

A: You've got a sudo command that sources a script. You've also got a command that prints $PATH. The two are otherwise unrelated.
Perhaps you meant this:
sudo -u "${USER_NAME}" bash -c 'source ~/.bash_rc; echo $PATH'

The -s can't be used with a compound command, but it could be used with a script containing the two (or more) commands:
cat >/opt/bin/show_me_the_path <<'X'
#!/bin/bash
source ~/.bash_rc
echo $PATH
X
chmod a+x /opt/bin/show_me_the_path

sudo -u "${USER_NAME}" -s /opt/bin/show_me_the_path

But even that doesn't really make much sense because the script mandates its own shell (/bin/bash). All in all it's probably better to rethink the -s flag.

A: You could execute it as:
sudo su - ${USER_NAME} -c 'source ~/.bash_rc; echo $PATH'

An example of it running. The user "zippy" has a ~/.bash_rc file. Note this is in addition to the standard ~/.bashrc file. The user executing the command, "bschuck" does not. The ~zippy/.bash_rc file contains:
#!/bin/bash
# .bash_rc
PATH=$PATH:/this/is/a/dummy/path

Executing this command works:
bschuck@valhalla:~$ sudo su - zippy -c 'source ~/.bash_rc; echo $PATH'
/home/zippy/bin:/home/zippy/.local/bin:\
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin:\
/this/is/a/dummy/path

Yet this command does not keep the new PATH sourced from the ~zippy/.bash_rc file:
bschuck@valhalla:~$ sudo -i -u zippy bash -c 'source ~/.bash_rc; echo $PATH'
/home/zippy/bin:/home/zippy/.local/bin:/usr/local/sbin:\
/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:\
/snap/bin

If you need to run multiple commands, it's best to put them in a script as I suggested yesterday in a comment to my answer.


text:
Q: Power sequencing with LDO without enable pin What is the right way to provide a power sequence using LDO (or any other power source) without the enable pin?
I'm using DAC7718 from Texas Instruments and it require a quit complex power sequencing:

For proper power-on initialization of the device, IOVDD and the digital pins must be applied before or at the same
  time as DVDD. If possible, it is preferred that IOVDD and DVDD can be connected together in order to simplify the
  supply sequencing requirements. Pull-up resistors should go to either supply. AVDD should be applied after the
  digital supplies (IOVDD and DVDD) and digital initialization pins (LDAC, CLR, RST, CS, and RSTSEL). AVSS can
  be applied at the same time as or after AVDD. The REF-x pins must be applied last.

Hence I need to:

*

*apply IOVDD and DVDD togheter

*apply AVDD and AVSS

*apply REF-x

In my circuit IOVDD and DVDD are +3.3V and come from a MCP1703; AVDD is +12V and comes from an AC/DC converter (TUHS15F12); AVSS is -12V and come from an ICL7660; REF-x is 2.5V and come from REF3025.
The simplest way I'm thinking at is to use some mosfet controlled by the MCU:

*

*IOVDD and DVDD go straight to the DAC7718

*AVDD is fed by a PMOS

*AVSS is fed by a NMOS

*REX-x is fed by a PMOS

of course I will need some interfacing/level translation to control those mosfet from a 3.3V.
Is this approach correct?


text:
Q: How to match up data from two spreadsheets using specific format I am wondering if someone can help me figure out how to match up data from two sheets, in a specific format. Here is an example of the data I need matched up, including an example showing expected output.
Note that UniqueToGroup_IDs are unique to only the specific Group_ID listed. As you can see, both of the sample Group_IDs I listed contain a UniqueToGroup_ID value of XSTN, which will return two different result IDs; 2306765 for Group_ID 16453, and 8272773 for Group_ID 8156705.
I can (painfully) do this semi-manually, by a combination of Text To Columns, adding the Group_ID to the UniqueToGroup_ID and NotUniqueToGroup_ID, and VLOOKUP -- but it takes forever and I need to do this often.
I haven't tried to write any VBA yet, because I'm not sure how to approach this problem. I am not terribly experienced with coding.
See example here (Dropbox)
Thank you in advance, for any advice.

A: You can build a two column cross reference with a dictionary.
Option Explicit

Sub ertgyhj()

    Dim i As Long, ii As String, gi As Long, ugi As String, nuid As Long, r As String
    Dim a As Long, itm As String, tmp As String, arr As Variant, xref As Object, results As Object
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet

    Set ws1 = Worksheets("original data")
    Set ws2 = Worksheets("data to match")
    Set ws3 = Worksheets("sample result")
    Set xref = CreateObject("scripting.dictionary")
    Set results = CreateObject("scripting.dictionary")

    'build two column cross reference dictionary
    With ws2

        For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
            itm = Join(Array(.Cells(i, "A").Value2, .Cells(i, "B").Value2), Chr(124))
            xref.Item(itm) = .Cells(i, "C").Value2
        Next i

    End With

    'put column header labels into results
    results.Item("image_id") = "result"

    'collect results
    With ws1

        'loop through rows
        For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row

            ii = .Cells(i, "A").Value2
            gi = .Cells(i, "B").Value2
            ugi = .Cells(i, "C").Value2
            tmp = vbNullString

            arr = Split(ugi, Chr(124))

            'loop through UniqueToGroup_ID and find matches
            For a = LBound(arr) To UBound(arr)
                itm = Join(Array(gi, arr(a)), Chr(124))
                If xref.exists(itm) Then
                    tmp = IIf(CBool(Len(tmp)), tmp & Chr(124), vbNullString) & xref.Item(itm)
                End If
            Next a

            'store concatenated result with image id
            results.Item(ii) = tmp

        Next i

    End With

    'post results
    With ws3

        .Cells(1, "A").Resize(results.Count, 1) = Application.Transpose(results.keys)
        .Cells(1, "B").Resize(results.Count, 1) = Application.Transpose(results.items)

    End With

End Sub

A: Crazy Lookup
Links
Workbook Download how-to-match-up-data-from-two-spreadsheets-using-specific-format_54299649.xls
The Code
Sub CrazyLookup()

    Const cSheet1 As String = "Original Data"   ' 1st Source Worksheet Name
    Const cSheet2 As String = "Data To Match"   ' 2nd Source Worksheet Name
    Const cSheet3 As String = "Sample Result"   ' Target Worksheet Name
    Const cFirstR As Long = 2                   ' First Row Number
    Const cFirstC As Variant = "A"              ' First Column Letter/Number
    Const cLastC As Variant = "C"               ' Source Worksheet's Last Column
    Const cNoC As Long = 2            ' Number of Columns of Target Array/Range
    Const cDel As String = "|"                  ' Split/Join Delimiter

    Dim vnt1 As Variant   ' 1st Source Array
    Dim vnt2 As Variant   ' 2nd Source Array
    Dim vnt3 As Variant   ' Target Array
    Dim vntU As Variant   ' Unique Array
    Dim lastR1 As Long    ' Last Row Number of 1st Source Range
    Dim lastR2 As Long    ' Last Row Number of 2nd Source Range
    Dim i As Long         ' 1st Source Array Row Counter
    Dim j As Long         ' Unique Array Row Counter
    Dim k As Long         ' 2nd Source Array Row Counter

    Application.ScreenUpdating = False
    On Error GoTo ProcedureExit

    ' Write 1st Source Range to 1st Source Array.
    With ThisWorkbook.Worksheets(cSheet1)
        lastR1 = .Columns(.Cells(1, cFirstC).Column) _
                .Find("*", , -4123, , 2, 2).Row
        vnt1 = .Range(.Cells(cFirstR, cFirstC), .Cells(lastR1, cLastC))
    End With
    ' Write 2nd Source Range to 2nd Source Array.
    With ThisWorkbook.Worksheets(cSheet2)
        lastR2 = .Columns(.Cells(1, cFirstC).Column) _
                .Find("*", , -4123, , 2, 2).Row
        vnt2 = .Range(.Cells(cFirstR, cFirstC), .Cells(lastR2, cLastC))
    End With

    ' Resize Target Array TO 1st Source Array's rows count and TO
    ' Number of Columns of Target Array.
    ReDim vnt3(1 To UBound(vnt1), 1 To cNoC)

    ' Write First Source Array's First Column to Target Array's first column.
    For i = 1 To UBound(vnt1)
        vnt3(i, 1) = vnt1(i, 1)
    Next

    ' Write
    For i = 1 To UBound(vnt1) ' Loop through rows of 1st Source Array.
        ' Split 1st Source Array's row in 3rd column to Unique Array.
        vntU = Split(vnt1(i, 3), cDel)
        For j = 0 To UBound(vntU) ' Loop through rows of Unique Array.
            For k = 1 To UBound(vnt2) ' Loop through rows of 2nd Source Array.
                ' Match 1st Source Array's row in 2nd column TO 2nd Source
                ' Array's row in first column AND Unique Array's row TO
                ' 2nd Source Array's row in 2nd column.
                If vnt1(i, 2) = vnt2(k, 1) And vntU(j) = vnt2(k, 2) Then
                    ' Write from 2nd Source Array's row in 3rd column to
                    ' Unique Array's row.
                    vntU(j) = vnt2(k, 3)
                    Exit For ' Stop searching.
                End If
            Next
            ' Check if match was not found.
            If k > UBound(vnt2) Then vntU(j) = "NotFound"
        Next
        ' Join Unique Array's rows to Target Array's row in second column.
        vnt3(i, 2) = Join(vntU, cDel)
    Next

    With ThisWorkbook.Worksheets(cSheet3)
        ' Clear contents of Target Range columns (excl. Headers).
        .Range(.Cells(cFirstR, cFirstC), .Cells(.Rows.Count, _
                .Cells(1, cFirstC).Column + cNoC - 1)).ClearContents
        ' Copy Target Array to Target Range.
        .Cells(cFirstR, cFirstC).Resize(UBound(vnt3), UBound(vnt3, 2)) = vnt3
    End With

ProcedureExit:
    Application.ScreenUpdating = True

End Sub

A: I built a workbook that I think can solve your problem. Let me know if this helps!
https://www.dropbox.com/s/3h6mja0xtwucbr5/20180121-Matching.xlsm?dl=0


text:
Q: VBA script to set background color if cell is not empty Just started with VBA in Excel 2016..
I'm trying to figure out a script to give non empty cells a background color
This is what I got:
If Range("a3:g8").Value = "" Then
  Interior.Color = RGB(222, 244, 180)
End If

But it's not working. What am I doing wrong?

A: You can define the cells into a single variable and loop through. See below code
Dim rng As Range, cell As Range
Set rng = Range("a3:g8")

For Each cell In rng
    If cell.Value = "" Then
        cell.Interior.Color = RGB(222, 244, 180)

    End If
Next

A: To target blank cells,
With Range("a3:g8")
    .FormatConditions.Delete
    with .FormatConditions.Add(Type:=xlExpression, Formula1:="=A3=TEXT(,)")
        .Interior.Color = RGB(222, 244, 180)
    end with
End With

To target non empty cells,
With Range("a3:g8")
    .FormatConditions.Delete
    with .FormatConditions.Add(Type:=xlExpression, Formula1:="=A3<>=TEXT(,)")
        .Interior.Color = RGB(222, 244, 180)
    end with
End With

A: What you are trying to do is compare the value of entire range with "" which will throw a type mismatch error. You will have to check the value of each cell one by one or try the below code which uses a simple excel formula:
 If WorksheetFunction.CountA(Range("A3:G8")) = 0 Then
       Range("A3:G8").Interior.Color = RGB(222, 244, 180)
 Else
       MsgBox "Range has some value"
 End If


text:
Q: htaccess - Redirect parent folder PHP script I have this web api project which is developed by other company. The file structure is:
/project
  ---/app
      ---/ApiEndpoint.php
  ---/public
      ---/index.php
The DocumentRoot is pointing to /project/public. The index.php is working (http://myapi.com/), however when I try to browse into the api endpoint http://myapi.com/api/endpoint I got 404 error.
How do I configure the .htaccess to rewrite this condition?
/project/public/.htaccess config
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^?]*)$ /index.php?path=$1 [NC,L,QSA]
</IfModule>

A: The current configuration is there to make sure every request go to index.php (that is probably dispatching requests in some way) except for the files that actually are in the public directory (probably needed for static files like images, and such).
If you wrote a php yourself to be directly called by http://myapi.com/api/endpoint, you should put it in /project/app/public/api/endpoint/index.php.
BUT I suspect you should study that application more and understand the current dispatching method, before doing that.


text:
Q: Computations involving the real projective plane Let $H$ be the complement of two open disks in the projective plane $\mathbb{R}P^2$. Determine all connected surfaces that arise as $3-$fold covers of $H$.
I think two such 3-fold covers are $\mathbb{R}P^2$ itself and  $S^2$. But how do I find the rest? Is there any general method that I can apply>


text:
Q: Tuples vs. Anonymous Types vs. Expando object. (in regards to LINQ queries) I am a beginner who finally started understanding anonymous types.
(see old post What is the return type for a anonymous linq query select? What is the best way to send this data back?)
So in LINQ queries you form the type of return value you want within the linq query right? It seems the way to do this is anonymous type right?
Can someone explain to me if and when I could use a Tuple/Expando object instead? They all seem very simliar?

A: Tuples and Expando objects are not normally used in LINQ. They're both quite different than anonymous types.
Anonymous types are commonly used to "shape" LINQ queries; for example, you can define a type that has a string Name property and an int Age property.
Tuples are types that only act as "pair" or "triplet" kinds of structures. For example a Tuple<string, int> can be defined, but the names of the properties are named Item1 and Item2, not Name and Age. Tuples are not normally used to shape LINQ queries because these property names make the code less clear.
ExpandoObject is totally different. It allows you to add properties at runtime to an existing object.

A: You don't state the context of your question, so I'll answer both LinqToObjects and LinqToSql.
In LinqToObjects, suppose you have a List<Customer> source.
  //Straight projection.
  //no new instances are created when query is evaluated.
IEnumerable<Customer> result =
  from c in source where c.Name == "Bob"
  select c;

  //Different Type projection
  //a new instance of CustomerName is created
  // for each element in the result when the query is evaluated.
IEnumerable<CustomerName> result =
  from c in source where c.Name == "Bob"
  select new CustomerName() {Name = c.Name};

  //Anonymous Type Projection
  //a new instance of an anonymous type is created
  // for each element in the result when the query is evaluated.
  //You don't have access to the type's name
  // since the compiler names the type,
  // so you must use var to talk about the type of the result.
var result =
  from c in source where c.Name == "Bob"
  select new {Name = "Bob"};

  //Tuple Projection (same as Different Type Projection)
  //a new instance of Tuple is created
  // for each element in the result when the query is evaluated.
IEnumerable<Tuple<string, int>> result =
  from c in source where c.Name == "Bob"
  select new Tuple<string, int>(){First = c.Name, Second = c.Id};

In LinqToSql, suppose you have an IQueryable<Customer> db.Customers
  //Straight projection
  //when the query is resolved
  // DataContext.Translate<Customer> is called
  // which converts the private dbReader into new Customer instances.
IQueryable<Customer> result =
  from c in db.Customers where c.Name == "Bob"
  select c;

  //Different Type Projection
  //when the query is resolved
  // DataContext.Translate<CustomerName> is called
  // which converts the private dbReader into new CustomerName instances.
  // 0 Customer instances are created.
IQueryable<Customer> result =
  from c in db.Customers where c.Name == "Bob"
  select new CustomerName() {Name = c.Name};

  //Different Type Projection with a twist
  //when the query is resolved
  // DataContext.Translate<CustomerGroup> is called
  // which converts the private dbReader into new CustomerGroup instances.
  // 0 Customer instances are created.
  //the anonymous type is used in the query translation
  // yet no instances of the anonymous type are created.
IQueryable<Customer> result =
  from c in db.Customers
  group c by new {c.Name, TheCount = c.Orders.Count()} into g
  select new CustomerGroup()
  {
    Name = g.Key.Name,
    OrderCount = g.Key.TheCount,
    NumberInGroup = g.Count()
  };

Ok, that's enough for now.


text:
Q: How many $N$-isogeny maps s.t. given kernel of $N'$ multiplication Sorry for my bad English.
Let $p$ be a prime number,
$N'>N$ be coprime positive integer and
$f:E_1\to E_2$ be a degree $N$ separable isogeny map between elliptic curves (if necessary supersingular).
When given  basis $P,Q\in E_1[N']$ and the image $f(P), f(Q)$, how many $N$-isogenies $g:E_1\to E_2$ are there with $g(P)=f(P)$ and $g(Q)=f(Q)$?
By assumption there is at least example $f=g$, but when $g$ is uniquely determined?


text:
Q: Cannot install Devise in Rails 5.0.2 I'm running Rails 5.0.2 on a Cloud9 install. I successfully bundle install Devise 4.2.1, but when I try rails g devise:install I get an error.
Here's my command line after bundle updating:
$ bundle update
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/.........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using rake 12.0.0
Using concurrent-ruby 1.0.5
Using i18n 0.8.1
Using minitest 5.10.1
Using thread_safe 0.3.6
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 2.0.1
Using nio4r 2.0.0
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 7.1.4 (was 8.0.0)
Using public_suffix 2.0.5
Using bcrypt 3.1.11
Using bindex 0.5.0
Using bundler 1.14.6
Using byebug 9.0.6
Using ffi 1.9.18
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using method_source 0.8.2
Using thor 0.19.4
Using orm_adapter 0.5.0 (was 0.0.7)
Using multi_json 1.12.1
Using rb-fsevent 0.9.8
Using ruby_dep 1.5.0
Using pg 0.20.0
Using puma 3.8.2
Using rubyzip 1.2.1
Using sass 3.4.23
Using tilt 2.0.7
Using websocket 1.2.4
Using turbolinks-source 5.0.0
Using tzinfo 1.2.3
Using nokogiri 1.7.1
Using rack-test 0.6.3
Using warden 1.2.7
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using addressable 2.5.1
Using childprocess 0.6.3
Using rb-inotify 0.9.8
Using coffee-script 2.4.1
Using uglifier 3.2.0
Using turbolinks 5.0.1
Using activesupport 5.0.2 (was 5.1.0)
Using loofah 2.0.3
Using xpath 2.0.0
Using mail 2.6.5
Using selenium-webdriver 3.4.0
Using listen 3.1.5
Using rails-dom-testing 2.0.2
Using globalid 0.4.0
Using activemodel 5.0.2 (was 5.1.0)
Using jbuilder 2.6.3
Using spring 2.0.1
Using rails-html-sanitizer 1.0.3
Using capybara 2.13.0
Using activejob 5.0.2 (was 5.1.0)
Using activerecord 5.0.2 (was 5.1.0)
Using spring-watcher-listen 2.0.1
Using actionview 5.0.2 (was 5.1.0)
Using actionpack 5.0.2 (was 5.1.0)
Using actioncable 5.0.2 (was 5.1.0)
Using actionmailer 5.0.2 (was 5.1.0)
Using railties 5.0.2 (was 5.1.0)
Using sprockets-rails 3.2.0
Using coffee-rails 4.2.1
Using responders 2.3.0
Using web-console 3.5.0
Using rails 5.0.2 (was 5.1.0)
Using sass-rails 5.0.6
Using devise 4.2.1 (was 1.5.4)
Bundle updated!

All looks good. Now let's try installing devise.
$ rails g devise:install
    /usr/local/rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/railtie/configuration.rb:95:in `method_missing': undefined method `load_defaults' for #<Rails::Application::Configuration:0x0000000414dfd0> (NoMethodError)
            from /home/ubuntu/workspace/eps-donation-pages/config/application.rb:12:in `<class:Application>'
            from /home/ubuntu/workspace/eps-donation-pages/config/application.rb:10:in `<module:EpsDonationPages>'
            from /home/ubuntu/workspace/eps-donation-pages/config/application.rb:9:in `<top (required)>'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:82:in `require'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:82:in `preload'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:143:in `serve'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:131:in `block in run'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:125:in `loop'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application.rb:125:in `run'
            from /usr/local/rvm/gems/ruby-2.4.1/gems/spring-2.0.1/lib/spring/application/boot.rb:19:in `<top (required)>'
            from /usr/local/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
            from /usr/local/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
            from -e:1:in `<main>'

I originally tried Rails 5.1.0, but apparently Devise doesn't support this yet (Unless I'm mistaken)

A: In Gemfile, please include devise like this for now:
gem 'devise', github: 'plataformatec/devise', ref: '83002017'

A: Looks like this issue was due to using Rails 5.1.0 (which was released just yesterday, April 27th) then attempting to downgrade to 5.0.2. Creating a new application with 5.0.2 from the outset and adding gem 'devise' installed the latest version of Devise and solved my issue.


text:
Q: How to do sliding panel in Flutter? I am building proof of concept on Flutter and trying as much as possible copy existing app. Our current app has sliding panel aka drop down at the top of the list, is there any way to do same behaviour in Flutter?

A: You can expand the panel with an Animation. In the code below, I used AnimatedBuilder to resize the panel as the animation ticks.
Because the panel is in the app bar, it's tricky to get it to interact well with scrolling. Once approach (shown below) is to use a NestedScrollView and put your expanding panel in the bottom of a SliverAppBar. It feels nice, but it does cause the content to get pushed down by the expanding panel and has some mild interactions with scroll physics at the edges of your item list. If you want to customize the behavior further you could copy NestedScrollView and modify it to your liking.

import 'package:flutter/material.dart';

class DayPickerBar extends StatefulWidget {
  DayPickerBar({ this.selectedDate, this.onChanged });

  final DateTime selectedDate;

  final ValueChanged<DateTime> onChanged;

  DayPickerBarState createState() => new DayPickerBarState();
}

class DayPickerBarState extends State<DayPickerBar> {
  DateTime _displayedMonth = new DateTime.now();

  @override
  Widget build(BuildContext context) {
    return new Container(
      color: Theme
        .of(context)
        .canvasColor,
      height: 250.0,
      child: new Row(
        children: <Widget>[
          new IconButton(
            icon: new Icon(Icons.chevron_left),
            onPressed: () {
              setState(() {
                _displayedMonth = new DateTime(
                  _displayedMonth.year,
                  _displayedMonth.month - 1,
                );
              });
            },
          ),
          new Expanded(
            child: new DayPicker(
              selectedDate: widget.selectedDate,
              currentDate: new DateTime.now(),
              displayedMonth: _displayedMonth,
              firstDate: new DateTime.now().subtract(new Duration(days: 1)),
              lastDate: new DateTime.now().add(new Duration(days: 30)),
              onChanged: widget.onChanged,
            ),
          ),
          new IconButton(
            icon: new Icon(Icons.chevron_right),
            onPressed: () {
              setState(() {
                _displayedMonth = new DateTime(
                  _displayedMonth.year,
                  _displayedMonth.month + 1,
                );
              });
            },
          ),
        ],
      ),
    );
  }
}

class FilterBar extends StatelessWidget {
  FilterBar({ this.isExpanded, this.onExpandedChanged });

  /// Whether this filter bar is showing the day picker or not
  final bool isExpanded;

  /// Called when the user toggles expansion
  final ValueChanged<bool> onExpandedChanged;

  static const Color _kFilterColor = Colors.deepOrangeAccent;

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    return new Container(
      color: Theme.of(context).canvasColor,
      child: new Row(
        children: <Widget>[
          new FlatButton(
            onPressed: () => onExpandedChanged(!isExpanded),
            textColor: theme.primaryColor,
            child: new Row(
              children: <Widget>[
                new Text('Watch Today'),
                new Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
              ],
            ),
          ),
          new Expanded(
            child: new Container(),
          ),
          new Container(
            decoration: new BoxDecoration(
              color: _kFilterColor,
              borderRadius: new BorderRadius.circular(16.0),
            ),
            padding: const EdgeInsets.all(6.0),
            child: new Text(
              'All Cinemas',
              style: theme.primaryTextTheme.button,
            ),
          ),
          new Container(
            decoration: new BoxDecoration(
              color: _kFilterColor,
              shape: BoxShape.circle,
            ),
            padding: const EdgeInsets.all(6.0),
            margin: const EdgeInsets.symmetric(
              horizontal: 6.0),
            child: new Text(
              ' + ',
              style: theme.primaryTextTheme.button,
            ),
          ),
        ],
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  HomeScreenState createState() => new HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  bool _isExpanded = false;
  DateTime _selectedDate = new DateTime.now();
  AnimationController _expandAnimationController;
  Animation<Size> _bottomSize;

  @override
  void initState() {
    super.initState();
    _expandAnimationController = new AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );
    _bottomSize = new SizeTween(
      begin: new Size.fromHeight(kTextTabBarHeight + 40.0),
      end: new Size.fromHeight(kTextTabBarHeight + 280.0),
    ).animate(new CurvedAnimation(
      parent: _expandAnimationController,
      curve: Curves.ease,
    ));
  }

  static const List<Tab> _tabs = const <Tab>[
    const Tab(text: 'NOW SHOWING'),
    const Tab(text: 'COMING SOON'),
  ];

  Widget _buildMovie(BuildContext context, int index) {
    ThemeData theme = Theme.of(context);
    return new Container(
      decoration: new BoxDecoration(
        border: new Border(
          bottom: new BorderSide(
            color: Colors.grey[500],
          ),
        ),
        image: new DecorationImage(
          fit: BoxFit.cover,
          image: new NetworkImage(
            'http://cdn.bloody-disgusting.com/wp-content/uploads/2016/06/hollywood-takes-a-bite-out-of-green-lantern-star-2-new-shark-movies-on-the-horizon-835796.jpg',
          ),
        ),
      ),
      child: new Stack(
        children: <Widget>[
          new Positioned(
            bottom: 0.0,
            left: 0.0,
            right: 0.0,
            child: new Container(
              padding: const EdgeInsets.all(20.0),
              color: Colors.grey[800].withOpacity(0.2),
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text(
                    '27 Meters Down',
                    style: theme
                      .primaryTextTheme.subhead,
                  ),
                  new Text(
                    'M 1h 29min, Horror',
                    style: theme.primaryTextTheme.
                    caption,
                  ),
                ],
              )
            )
          ),
        ],
      ),
    );
  }

  Widget _buildBottom() {
    return new PreferredSize(
      child: new SizedBox(
        height: _bottomSize.value.height,
        child: new Column(
          children: <Widget>[
            new TabBar(
              tabs: _tabs,
            ),
            new FilterBar(
              onExpandedChanged: (bool value) async {
                if (value &&
                  _expandAnimationController.isDismissed) {
                  await _expandAnimationController.forward();
                  setState(() {
                    _isExpanded = true;
                  });
                } else if (!value &&
                  _expandAnimationController.isCompleted) {
                  await _expandAnimationController.reverse();
                  setState(() {
                    _isExpanded = false;
                  });
                }
              },
              isExpanded: _isExpanded,
            ),
            new Flexible(
              child: new Stack(
                overflow: Overflow.clip,
                children: <Widget>[
                  new Positioned(
                    top: 0.0,
                    left: 0.0,
                    right: 0.0,
                    child: new DayPickerBar(
                      onChanged: (DateTime value) {
                        setState(() {
                          _selectedDate = value;
                        });
                      },
                      selectedDate: _selectedDate,
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
      preferredSize: _bottomSize.value,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      drawer: new Container(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.filter_list),
        onPressed: () {},
      ),
      body: new DefaultTabController(
        length: _tabs.length,
        child: new NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              new AnimatedBuilder(
                animation: _bottomSize,
                builder: (BuildContext context, Widget child) {
                  return new SliverAppBar(
                    pinned: true,
                    floating: true,
                    title: const Text('Movies'),
                    actions: <Widget>[
                      new IconButton(
                        icon: new Icon(Icons.search),
                        onPressed: () {},
                      ),
                      new PopupMenuButton(
                        child: new Icon(Icons.more_vert),
                        itemBuilder: (BuildContext context) {
                          return <PopupMenuEntry>[
                            new PopupMenuItem(
                              child: new Text('Not implemented'),
                            )
                          ];
                        },
                      ),
                    ],
                    bottom: _buildBottom(),
                  );
                },
              ),
            ];
          },
          body: new TabBarView(
            children: <Widget>[
              new ListView.builder(
                itemBuilder: _buildMovie,
                itemExtent: 200.0,
              ),
              new Container(
                child: new Center(
                  child: new Text('Coming soon!'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: new HomeScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}

void main() {
  runApp(new ExampleApp());
}


text:
Q: Convexity or not I'd like to know if the reasoning below is correct or not.
I have this problem: $\underset{x}{\operatorname{min}}\begin{Bmatrix}
\operatorname{c}^T\operatorname{x} : A(\zeta)\operatorname{x} \leq \operatorname{b},\forall \zeta \in U
\end{Bmatrix}$ with $\operatorname{c}\in \mathbb{R}^n, \operatorname{b}\in \mathbb{R}^m, A\in \mathbb{R}^{m \times n}$ and $\zeta \in \mathbb{R}^L$. This is a LP problem under uncertainty, where the uncertainty is now detectable only at the level of eligible region with particular reference to the matrix of coefficients $A$, for $\zeta \equiv \zeta(\omega),\omega \in \Omega$ the single realization of the uncertain parameters of $A$. Generally I know that a LP problem without uncertainty is a convex problem, since the constraints system describes a convex set intended as the intersection of a finite number of half-spaces. And if we consider the same problem under uncertainty, I know that it's possible to represent the uncertainty set through intervals, i.e. to say $U=\begin{Bmatrix}
A: A^- \leq A \leq A^+
\end{Bmatrix}$, with $A^-$ and $A^+$ the estimates of lower and upper bounds of the interval of $A$. Obviously, in spite of this assumption, remain infinite values that the parameters of $A$ could assume, which is why I think it's out of question the convexity of $U$: number of potential half-spaces is now uncountable. However we can consider $U$ like $\operatorname{conv}(U)$, i.e. the smallest convex set that includes $U$,  because testing the feasibility of a solution on $U$ for a maximization problem means evaluating the objective function respect to $A^+$ which will coincide (no escaping) with the value of objective evaluating on his convex hull. So a LP problem under uncertainty that should be unconvex can always be considered in the same way of a convex problem.
Is it right? Thanks in advance for any clarification.


text:
Q: how to change android compose TextFeild`s content padding? It`s padding is to large!what can i delete them?
TextField(
            value = text,
            textStyle = TextStyle(
                color = Color.Red,
                textDecoration = TextDecoration.None
            ),
            onValueChange = {
                text = it
            },
            placeholder = {
                Text(text = "请输入设备序列号", color = Color.Gray)
            },
            singleLine = true,
            activeColor = Color.Yellow,
            modifier = Modifier.padding(1.dp),
            backgroundColor = Color.Transparent
        )

this is my code.please help me !

A: You can use BasicTextField to take control over it.
            var value by rememberSaveable { mutableStateOf("") }

            BasicTextField(

                cursorBrush = SolidColor(Color.White),
                value = value,
                onValueChange = { value = it },
                textStyle = TextStyle(color = Color.White),
                decorationBox = { innerTextField ->

                    Row(modifier = Modifier.fillMaxWidth()) {
                        if (value.isEmpty()) {
                            Text(text = "Placeholder", color = Color.White)
                        }
                    }

                    innerTextField()
                }
            )


text:
Q: database design : Inventory with multiple item units ( wholesale and retail ) I have designed a db for drug ( pharmacy ) store which will sell medicine both wholesale and retail. There are some medicine that can be sold in multiple units, for example, strip, capsule and vial of medicine. Basically, each medicine can be sold in more than one unit. Here is my db:

I have an inventory movement records  that record the specific stock used to fill each order. if a medicine's base unit is set to vial, and It has some records with vial in the inventory movement, and after a period of time, I want to sell that medicine with capsule unit, at this time, how do I record this to the inventory movement ? And how do I calculate the stocks from inventory ?
If I update the item_unit record to set the data like following:

And I need to scan whole InventoryMocement table to update the base unit to the new one ( capsule ) and re-calculate the quantity with the multiplier. Is this reasonable ?
Is there any flaws in my design ? Does anyone have any ideas (or examples)?


text:
Q: 'invalid arguments' error message when loading array of Files Let's have the following page:

<meta charset="utf-8">

<input type="file" id="file0" onchange="readFile(event)" />

<input type="file" id="file1" onchange="readFile(event)" />

<input type="button" value="send" onclick="sendFile()" />

I'm loading 2 files from my computer and click on "send". But I'm receiviving error message on console in FF: TypeError: invalid arguments. Different error message in IE: Typed array constructor argument is invalid. Seems to me that problem is with Uint8Array() but what's wrong? If I send a single file it is okay.


text:
Q: Connect Java to Access DB on network drive I'm creating a desktop Java application that will connect to an access database, using ucanaccess as a driver.
The entire thing will be located on a shared network drive.
I use an absolute file path to connect to my database. I expect this database to outlast my tenure at the office. What happens when another user moves the database, or changes the name of the folder etc... I'm the only Java geek in the office, so this needs to be somewhat automated or easily doable for someone who is... well let's just say not computer literate.
I'm looking for ideas on how to get around this. I thought of opening a file dialog and having the user select the location of the file, but this seems like too much work for the kind of people I work with. It should just open...
Any help is much appreciated. Code sample below.
package databaseTest;

import java.sql.Connection;
import java.sql.DriverManager;

public class test {

    public test() {
        try {
            String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
            Class.forName(driver);
            Connection cnct = DriverManager.getConnection("jdbc:ucanaccess://c:\\users\\Christopher\\Desktop\\JavaProject\\Database11.accdb", "", "");
            System.out.println("Connected");
        } catch(Exception ex) {System.out.println(ex.getMessage());}
    }

    public static void main(String[] args) {
        System.out.println("connecting...");
        new test();
    }

}

A: Suggestion:
I would suggest you to store the database related parameters/configurations

*

*Path to database

*Name of network shared directory

*Database Name
etc. in a properties file. You can then load the properties file using getResourceAsStream. You only need to ensure two things —

*

*The properties file is in a directory which is in the project build path.

*If any of the parameter(s) are changed(files moved/renamed), the corresponding value(s) in the properties file are changed also.

Here's one concrete example(tested on Ubuntu Linux).
Let's say we have a:

*

*MS Access database named Foo.mdb stored under a shared directory /path/to/sharedDirectory

*Shared directory named shared_dir
MyDatabaseProperties.properties:
pathToDB = /path/to/sharedDirectory
sharedFolderName = shared_dir
databaseName = Foo.mdb

Table Definition:

Example:
package com.stackoverflow.questions.Q32641670;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Initializes a connection to an MS-Access DB using JDBC/UCanAccess API, inserts a record and closes the connection.
 * <p>
 * ADDITIONAL JARS REQUIRED:
 * ------------------------
 * commons-lang-2.6.jar
 * commons-logging-1.1.1.jar
 * hsqldb.jar
 * jackcess-2.1.0.jar
 * ucanaccess-2.0.9.5.jar
 *
 * @see @link {https://stackoverflow.com/questions/32641670/connect-java-to-access-db-on-network-drive}
 * @since 18/9/15.
 */

/**
 * @author Sandeep Chatterjee
 * @version 1.0
 */
public class ConnectRemoteDB {

    /**
     * @param args The command line arguments
     */
    public static void main(String[] args) throws IOException {

        initializeConnection();

    }

    /**
     * Initializes remote database connection and inserts a record and closes the connection.
     */
    private static void initializeConnection() throws IOException {

        System.out.println("Attempting Database Connection...");

        Connection connection = null;

        PreparedStatement preparedStatement;

        try {

            final Properties PROPERTIES = new Properties();

            InputStream inputStream = ConnectRemoteDB.class.getResourceAsStream("/MyDatabaseProperties.properties");

            PROPERTIES.load(inputStream);

            String pathToDB = PROPERTIES.getProperty("pathToDB");

            String sharedFolderName = PROPERTIES.getProperty("sharedFolderName");

            String databaseName = PROPERTIES.getProperty("databaseName");

            String connectionString = "jdbc:ucanaccess:///" + pathToDB + "/" + sharedFolderName + "/" + databaseName;

            connection = DriverManager.getConnection(connectionString, PROPERTIES);
            System.out.println("CONNECTION ESTABLISHED....");
            String insertTableSQL = "INSERT INTO Table1" + "(Name) VALUES"
                    + "(?)";
            preparedStatement = connection.prepareStatement(insertTableSQL);
            preparedStatement.setString(1, "A");
            preparedStatement.executeUpdate();
            System.out.println("RECORD INSERTED...");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                connection.close();
                System.out.println("CONNECTION CLOSED...");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Again:

*

*If you move the database to a different shared directory, set the value of pathToDB accordingly.

*If you rename the shared directory, set the value of sharedFolderName accordingly.

*If you rename the database, set the value of databaseName accordingly.

A: The simplest solution is to put the accdb file in a location relative to the java class and not use an absolute path.
For example if the java class (or jar you have packaged your program into as it may be) resides at c:\share\foo.class (or c:\share\foo.jar) then put the acdb file in the same directory structure e.g. c:\share\database\Database11.accdb.
You can then use a relative path in the connection string:
 Connection cnct = DriverManager.getConnection("jdbc:ucanaccess:database/Database11.accdb", "", "")