text:
Q: Post request not working Drupal and Ubuntu 14.04 In my ubuntu 14.04 OS machine for drupal 7 login not working, may be it is not only login but all post request not working here. For the same filesystem and codebase it works fine in windows 7 machine.
Here is my apache server configuration:
<VirtualHost *:80>

ServerName somedomain.local

DocumentRoot "/home/mycompany/Development/Projects/Drupal/cbb"

<Directory "/home/mycompany/Development/Projects/Drupal/cbb/">

   Options Indexes FollowSymLinks

   AllowOverride All

   Require all granted

</Directory>

</VirtualHost>

for above configuration when i try to submit data for login it showing..
"NetworkError: 404 Not Found - http://somedomain.local/user".
#UPDATE:
I just find out that login not working only from www.domainname.local/user path but if this login form in homepage sidebar it works fine, for all of drupal sire in ubuntu machine. With this no error message also not display.
I am in trouble for two of my drupal site in Ubuntu machine. Any help will be appreciated.

A: Your Apache vhost file looks like it has the key components set and I'm assuming that the .htaccess file exists in your document root and hasn't been modified from the Drupal default.
When you click on the login link in the sidebar, does it take you to http://somedomain.local?q=user/login ?
Your #update suggests that even though your Apache environment may be set up for "clean URLs", the feature is not enabled in Drupal at Administer > Configuration > Search and metadata > Clean URLs.
If modifying this compromises your access to Drupal, you can apply/disable this change via Drush (drush vset clean_url 0 --yes) or directly through MySQL (UPDATE variable SET value = 's:1:"0";' WHERE name = 'clean_url';) as per https://www.drupal.org/node/5590.
Also worth mentioning, seeing it on this related question (Very strange Drupal 7 404 behaviour): make sure that Apache modules mod_rewrite and mod_headers are enabled:
sudo a2enmod rewrite
sudo service apache2 restart

A: *

*Check if .htaccess file present in drupal root directory.

*Check if you've added your domain to /etc/hosts file
127.0.0.1 domain.name

*Domains with 'www' and without it are totally different. Add both to /etc/hosts and to apache's config file to avoid problems.

*Clear cache to avoid previous domain name which could be stored in cache.
drush cc all

*If you've just added new site to apache's configuration be sure to run:
sudo service apache2 graceful


text:
Q: ORA-00907: Missing right parenthesis in SQL I'm trying to run this SQL query in java
String query = "update table_name set refresh_date=to_date('01-SEP-2013','dd-mon-yyyy') where colomn_name like '%my_col%'"
jdbc.execute(query);

I'm getting the error
 java.sql.SQLException: ORA-00907: missing right parenthesis

I have looked at other similar questions on stackoverflow but cannot figure out what's wrong here.

A: You have some invalid quotes. You need to match them like this
update table_name set refresh_date=to_date('01-SEP-2013','dd-mon-yyyy') where colomn_name like '%my_col%'

A: You are using the wrong quotes. Try this:
update table_name
  set refresh_date=to_date('01-SEP-2013','dd-mon-yyyy')
  where colomn_name like '%my_col%'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django form with grouped checkboxes I need to create a form in Django which contains a list of grouped checkboxes like:
group_one
  [] option_one
  [] option_two
group_two
  [] option_one
  [] options_three

Right now I've an intermediate table where I'm storing a option_id and a group_id.
I found this snippet but only works on Django 1.8, after that version some classes were removed from the core of django forms...
I could find the way to update the snippet, but I wonder if maybe somebody had the same situation and found a better solution for this challenge.
Thank you in advance!

A: You can do something like this (not tested)
from django import forms
set_a = (("a", "A"),
         ("b", "B"),)

set_b = (("c", "C"),
         ("d", "D"),)

    class Test(forms.Form):
        group_a = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                         choices=set_a)
        group_a = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                         choices=set_b)


text:
Q: What is the difference between Silverlight and XBAP? What is the difference between Silverlight and XBAP?
Where would you use one vs. the other?

A: *

*From users perspective to view WPF Browser application user will need total dot net framework to be installed that is considerably higher than Silverlight runtime.

*WPF browser applications will not work except windows OS

*There are much more features you can use (Like real 3D with camera and light) with WPF browser applications that you can not do with silverlight.

A: History Lesson.
We made WPF originally to allow design to get more hands on when it comes to Windows based applications as this was consistent feedback we found from the WinForms world. We produce WPF, and it kind of borrowed similar techniques found from HTML but in a more what we'd call mature fashion (XAML).
We then decided (based off customer feedback) to enable a subset of this vision on x-platform and x-browser machines. As a result we ended up with WPF/E (WPF Everywhere) which was later renamed Silverlight.
WPF vs Silverlight.
Easy answer is this, if you want create a solution with x-platform / x-browser reach, then Silverlight is your best bet. The downside is you won't be able to break out of the sandbox imposed within browsers, so if its an application that is happy to live in a hands off the machine it dwells in world, Silverlight can provide you a more than reasonable result (Out Of Browser, Isolated Storage etc do allow you more access to a persons machine than normal).
WPF however is there for deep access, meaning you want to access a USB driver or talk to an alternative technology to .NET etc.. same principles, just deeper unrestricted access.
You can deploy .XBAP solutions which is very similar to Silverlight, but provides a bit deeper in terms of access... think of it as the middle child between WPF and Silverlight.
Going Forward.
We are spending cycles ensuring WPF/Silverlight converge more in terms of a uniform API etc, to enable you to graduate up/down the technology experience without having to radically shift your logic. We've got frameworks in place today (ie PRISM/MEF) that will help you here, but we are working hard to bring the two technologies back to parity for you all.
Feedback is always welcome and feel free to follow us on twitter to complain/praise via @teamsilverlight.
Scott Barnes / Rich Platforms Product Manager / Microsoft.

A: Silverlight is cross-platform and runs its applications in the browser; it can be used anywhere you use a web-browser.
WPF is Windows-only and usually runs its applications on the desktop; it requires that the .NET framework is installed.
Silverlight can be viewed as a subset of WPF (though this isn't technically correct). It does not have quite the feature set that WPF has. What you lose in functionality, though, you gain in adoptability.
WPF can deploy applications through the browser, using what is called an XBAP. This is not the same as Silverlight, though; whereas Silverlight applications are actually integrated into the browser, WPF is merely using the browser as a host for its process.
For a more in-depth guide on the differences between WPF and Silverlight, I would refer to this white-paper on CodePlex.

A: The big difference is the sandbox.  Both are sandboxed, but WPF-Browser apps (e.g. XBAP) can ask for more permissions, but in Silverlight you can't (by design).


text:
Q: C# SqlCommand and SqlDataAdapter ExecuteNonQuery for SQL Server INSERT, UPDATE, and DELETE operations? Please advise as to choose between SqlCommand and SqlDataAdapter for SQL Server INSERT, UPDATE, and DELETE operations.
Let's consider the following code snippet for SQL Server:
public int Execute(SqlCommand commandSql)

or
public int Insert(SqlCommand commandSql)

Considering the obvious advantage of SqlCommand (Execute  method) is that it can be used for all INSERT, UPDATE, and DELETE operations and the advantage of SqlDataAdapter (Insert, Update, Delete methods) is disconnected architecture, what are the pros and cons of using SqlCommand ExecuteNonQuery vis-à-vis SqlDataAdapter ExecuteNonQuery?
Caveats for enterprise-class web applications? Please let experts clarify.
Please note that this question is not about LINQ or Entity Framework, this is about SqlCommand ExecuteNonQuery vis-à-vis SqlDataAdapter ExecuteNonQuery?
Important question: does SqlCommand ExecuteNonQuery use a connected or disconnected architecture?
//Insert
private bool Insert(string firstName, string lastName, string synonym)
{
    bool isInserted = false;
    try
    {
        int rowsAffected = 0;
        StringBuilder insertQuery = new StringBuilder();
        insertQuery.Append("INSERT INTO Customer ");
        insertQuery.Append("(");
        insertQuery.Append("FirstName, ");
        insertQuery.Append("LastName, ");
        insertQuery.Append("Synonym ");
        insertQuery.Append(") ");
        insertQuery.Append("VALUES ");
        insertQuery.Append("(");
        insertQuery.Append("@FirstName, ");
        insertQuery.Append("@LastName, ");
        insertQuery.Append("@Synonym ");
        insertQuery.Append(");");
        using (SqlCommand commandSql = new SqlCommand(insertQuery.ToString()))
        {
            commandSql.Parameters.AddWithValue("@FirstName", firstName);
            commandSql.Parameters.AddWithValue("@LastName", lastName);
            commandSql.Parameters.AddWithValue("@Synonym", synonym);
            DataAccessLayer dal = new DataAccessLayer();

            rowsAffected = dal.Execute(commandSql); // SqlCommand ????
        rowsAffected = dal.Insert(commandSql); // SqlDataAdapter ???

        }
        if (rowsAffected > 0)
        {
            isInserted = true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return isInserted;
}
//UPDATE
private bool Update(int custId, string firstName, string lastName, string synonym)
{
    bool isUpdated = false;
    try
    {
        int rowsAffected = 0;
        StringBuilder updateQuery = new StringBuilder();
        updateQuery.Append("UPDATE Customer ");
        updateQuery.Append("SET ");
        updateQuery.Append("FirstName = @FirstName, ");
        updateQuery.Append("LastName = @LastName, ");
        updateQuery.Append("Synonym = @Synonym ");
        updateQuery.Append("WHERE ");
        updateQuery.Append("CustomerId = @CustomerId;");
        using (SqlCommand commandSql = new SqlCommand(updateQuery.ToString()))
        {
            commandSql.Parameters.AddWithValue("@CustomerId", custId);
            commandSql.Parameters.AddWithValue("@FirstName", firstName);
            commandSql.Parameters.AddWithValue("@LastName", lastName);
            commandSql.Parameters.AddWithValue("@Synonym", synonym);
            DataAccessLayer dal = new DataAccessLayer();
            rowsAffected = dal.Execute(commandSql); // SqlCommand ????
        rowsAffected = dal.Update(commandSql); // SqlDataAdapter ???
        }
        if (rowsAffected > 0)
        {
            isUpdated = true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return isUpdated;
}
//DELETE
private bool Delete(int custId)
{
    bool isDeleted = false;
    try
    {
        int rowsAffected = 0;
        StringBuilder deleteQuery = new StringBuilder();
        deleteQuery.Append("DELETE FROM Customer ");
        deleteQuery.Append("WHERE ");
        deleteQuery.Append("CustomerId = @CustomerId;");
        using (SqlCommand commandSql = new SqlCommand(deleteQuery.ToString()))
        {
            commandSql.Parameters.AddWithValue("@CustomerId", custId);
            DataAccessLayer dal = new DataAccessLayer();
            rowsAffected = dal.Delete(commandSql);
        rowsAffected = dal.Execute(commandSql); // SqlCommand ????
        rowsAffected = dal.Delete(commandSql); // SqlDataAdapter ???
        }
        if (rowsAffected > 0)
        {
            isDeleted = true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return isDeleted;
}

// SqlCommand
public int Execute(SqlCommand commandSql)
{
    int rowsAffected = 0;
    using (SqlConnection connectionSql = new SqlConnection("ConnectionString"))
    {
        commandSql.Connection = connectionSql;
        commandSql.Connection.Open();
        rowsAffected = commandSql.ExecuteNonQuery();
    }
    return rowsAffected;
}

// SqlDataAdapter
public int Insert(SqlCommand commandSql)
{
    int rowsAffected = 0;
    using (SqlConnection connectionSql = new SqlConnection("ConnectionString"))
    {
        using (SqlDataAdapter dataAdapterSql = new SqlDataAdapter())
        {
            dataAdapterSql.InsertCommand = commandSql;
            dataAdapterSql.InsertCommand.Connection = connectionSql;
            dataAdapterSql.InsertCommand.Connection.Open();
            rowsAffected = dataAdapterSql.InsertCommand.ExecuteNonQuery();
        }
    }
    return rowsAffected;
}
// SqlDataAdapter
public int Update(SqlCommand commandSql)
{
    int rowsAffected = 0;
    using (SqlConnection connectionSql = new SqlConnection("ConnectionString"))
    {
        using (SqlDataAdapter dataAdapterSql = new SqlDataAdapter())
        {
            dataAdapterSql.UpdateCommand = commandSql;
            dataAdapterSql.UpdateCommand.Connection = connectionSql;
            dataAdapterSql.UpdateCommand.Connection.Open();
            rowsAffected = dataAdapterSql.UpdateCommand.ExecuteNonQuery();
        }
    }
    return rowsAffected;
}
// SqlDataAdapter
public int Delete(SqlCommand commandSql)
{
    int rowsAffected = 0;
    using (SqlConnection connectionSql = new SqlConnection("ConnectionString"))
    {
        using (SqlDataAdapter dataAdapterSql = new SqlDataAdapter())
        {
            dataAdapterSql.DeleteCommand = commandSql;
            dataAdapterSql.DeleteCommand.Connection = connectionSql;
            dataAdapterSql.DeleteCommand.Connection.Open();
            rowsAffected = dataAdapterSql.DeleteCommand.ExecuteNonQuery();
        }
    }
    return rowsAffected;
}

Please help.
Thanks

A: SQLDataAdapter is a specialized case for use with Dataset classes.  If you are using plain SQL input as in your examples it would be better to use SQLCommand for this purpose if a specific dataset is not being used. If you are going to use something like a dataset for Enterprise use it would be worthwhile to consider the more updated Entity Framework instead as it provides typing versus the plain datasets.


text:
Q: Is torque possible without any pivot point? In the picture, AB is a rod. The resultant of force P=10N and Q=5N works at point C which is P+Q. When I apply both forces simultaneously, the rod will rotate and accelerate. 5N from both end will contribute accelerating toward a straight path and the rest 5N of P at point A will contribute to the rotation.

Now my question is, can I interpret that rotation as Torque though there seems to be no defined pivot point? What is the role of the resultant at C? Shouldn't is contribute to both acceleration to the straight path and rotation? Is point C comparable with center of mass(com) in that context?

A: You can calculate torque about any desired point; that point is not required to be pivoted. In $\vec{\tau} = \vec{r} \times \vec{F}$, vector $\vec{r}$ is the position vector of point where force $\vec{F}$ acts with respect to the point, say, $P$ considered for calculating torque.

5N from both end will contribute accelerating toward a straight path and the rest 5N of P at point A will contribute to the rotation.

It is not like that. First consider, linear acceleration. You need to take resultant $\vec{P}+\vec{Q}$ and divide its magnitude by mass of the rod. It gives linear acceleration of center of mass.
Next, consider angular acceleration. Calculate net torque due to both forces about the center of mass $C$. Dividing magnitude of resultant torque by moment of inertia will give angular acceleration of the rod.
Note that in above, it has been assumed that all the forces lie in the same plane as your example indicates.

A: I'm assuming that the only forces actually applied to the bar are P and Q as I show in FIG 1 below. Then you are saying equivalent result force is P + Q = 15 located at point C. But you didn't go far enough.
The equivalent force system to FIG 1 below is FIG 2, with the net force applied at the center of mass (COM assuming bar is uniform) to account for the linear acceleration of the COM of the bar, plus a force couple (torque) to account for the rotational acceleration about the COM due to the torque contributions of the forces at P and Q. That net torque $\tau_{net}$ is, counter clockwise torque being positive torque,
$$\tau_{net}=-5\biggl(\frac{AB}{2}\biggr) + 10\biggl (\frac{AB}{2}\biggr) = +2.5AB$$
Hope this helps.

A: The acceleration of the center of mass (CM) is determined by the net external force.
The net torque is the change in the angular momentum if you use the CM as the point about which to evaluate torque and angular momentum; this is true even if the CM is accelerating.  This is not true using a point other than the CM for torque and angular momentum if the point is accelerating.
So the overall motion is most easily evaluated as:
(1) translational acceleration of the CM with
(2) rotational motion about the CM.
You do not need to use any "resultant force".
Addition based on your later comment specifying location of point C.
You added "5.AC=10.BC. Distance of C from 5N is twice as it is from 10N."
Then AC = 2/3 d where d is length of rod; C is d/6 to right of CM. Total torque from resultant force wrt CM is 15 * d/6 = 15/6 d = 5/2 d. This equals total torque from the actual forces: 5 * -d/2 + 10* d/2 = 5 d/2. So, C is with respect to the CM in terms of equivalent torque. That is the resultant force equivalent to the actual forces with torques evaluated wrt the CM is 15N applied at d/6 to right of CM.
You can solve the motion using either the actual forces/locations or the resultant force at location C.
Using resultant force at C, evaluate motion as translational acceleration of CM plus rotational motion about CM as other answers discuss. (If a point is not fixed or is not the CM (can be moving) net torque is not equal to the change in angular momentum. So pick CM for rotational evaluation for this problem.)  CM will move upwards and rod will rotate counterclockwise wrt CM.  This agrees with earlier answer by @Bob D (except for minor math error that you pointed out.)


text:
Q: Java Collection value locator i'm currently creating a GUI that uses the list collection. My problem is with the validation function.
public void idValidate(int id) {
    for (Item i : items) {
        if (i.getId() == id) {
            checker = true;
        } else {
            checker = false;
        }
    }

}

Here's a sample of where I use this function.
private void checkEditBtnActionPerformed(java.awt.event.ActionEvent evt) {
    int id = Integer.parseInt(idEditTxt.getText());
    idValidate(id);
    System.out.println(checker);
    if (checker == true) {
        nameEditTxt.setEditable(true);
        priceEditTxt.setEditable(true);
        descEditTxt.setEditable(true);
        updateEditBtn.setEnabled(true);
    } else {
        JOptionPane.showMessageDialog(myJFrame.this, "ID not found!", "Validation Message", JOptionPane.WARNING_MESSAGE);
    }

When I input 2 or more lists, the only ones that return true are the recently added ones. The checker does not return true if I try to locate the first item I input.
Thank you :)

A: This is where using a debugger is helpful.  You would be able to see that when you do checker = false this overwrites the existing value so it doesn't matter how many times you call checker = true; if you call checker = false; after it, this is the value you have.
Most likely you expected that once you set true, this is the value you want to keep.  In fact there is no point continuing in the loop, it's not going to get any true-r
Also it is better to return a result than set a mutable field.  This minimises the number of side effects of the method and makes it easier to reason about. i.e. minimises bugs.
public boolean idValidate(int id) {
    for (Item i : items)
        if (i.getId() == id)
            return true; // stop as soon as one is true.
    return false;
}

BTW In Java 8 you can write
public boolean idValidate(int id) {
    return items.stream().anyMatch(i -> i.getId() == id);
}

A: Edit yuor as below:
public void idValidate(int id) {
    for (Item i : items) {
        if (i.getId() == id) { // if found then break the loop
            checker = true;
            break; // here
        } else {
            checker = false;
        }
    }

}

Once it was fund break the loop, otherwise the checker value again become false
But is better to the code like this:
public boolean idValidate(int id) {
        for (Item i : items) {
            if (i.getId() == id) {
                return true;
            }
        }
        return false;
    }

Then use like this:
boolean isValid = idValidate(id);
if(isValid) {
    // your code
}


text:
Q: Seaborn keeps flipping my rows for multi-graphs I'm using Seaborn for some data exploration and am using the catplot functions. When I use col='something' to create multiple graphs, I am running into an issue where the variable names of one plot do not match up with another. The colors are the same. I've tried using the order=list, but nothing seems to work.
An example would be
sns.catplot(x=variable, y=other_variable, data=df, col=something, kind='bar')

and I get something like this.


text:
Q: Passsing slider values between pages in JQuery Mobile I'm trying to pass form slider values between pages so that the changed settings can be used in the target page. For that I'm just accessing the DOM on the same page as explained in the answer here.
Here is my sample code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Multi-page template</title>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

Review

                Review content

                <form>
                    First:
                    <input type="range" id="first_slider" value="60" min="0" max="100" />
                    Second:
                    <input type="range" id="second_slider" value="60" min="0" max="100" />
                    <input type="submit" value="Submit" />
                </form>

Front

                    Front content

                    Main

This seems to work the first time and the changed setting would show on the 'front' page, but not on subsequent page calls. I tried other JQM page events than 'pageinit' but can't get this to work.

A: I played around with your example and got it working. I used this info from the docu

Form buttons
For ease of styling, the framework automatically converts any button
  or input element with a type of submit, reset, or button into a custom
  styled button — there is no need to add the data-role="button"
  attribute. However, if needed, you can directly call the button plugin
  on any selector, just like any jQuery plugin:
 $('[type="submit"]').button();

which results in this script

complete corrected version of your example:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Multi-page template</title>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

Review

      Review content

      <form>
        First:
        <input type="range" id="first_slider" value="60" min="0" max="100" />
        Second:
        <input type="range" id="second_slider" value="60" min="0" max="100" />
        <input type="submit" value="Submit" />
      </form>

Front

        Front content

        Main

screenshot


text:
Q: HTML submit form does not work as expected I have recently started practicing Html. I am working on simple submit form without any kind of data.
Here is my index.html code

     <form action="/a.html">
Vignesh
 >

 <input type="submit" value="SUBMIT">
    </form> >

Here is my a.html code...

    SUBMITTED

when I press SUBMIT it shows "File a.html? not found" I don't know it adds '?' in end. If remove ? manually from link it works.

A:

      <form action="/a.html" method="POST">

Vignesh

            >

 <input type="submit" value="SUBMIT">
      </form>
      >

Add an attribute method="POST" will fix your question mark issue.


text:
Q: Can't override style, element not accessible, although appears in code I have an element in the page that was injected using jQuery. When inspecting the page code, I can clearly see the element and its Id. When trying to access it using jQuery:
$("#camera-1-height-specs")

or using Javascript:
document.getElementById("camera-1-height-specs")

The element doesn't exist and I get null for Javascript and [] for jQuery. I can inspect the element in Chrome and can even see it's styles using Chrome developer console. I copy paste the exact Id and triple check myself.
I try overriding the style using CSS, which seems to be the easiest solution, but it doesn't work either:
<style>
 #camera-1-height-specs , #camera-2-height-specs  {
   writing-mode: initial !important;
 }
</style>

Here's the element as seen by Google Chrome using the developer tools:

My goal was to override the element with a new style, but nothing works. I tried accessing other page elements and I can access them, it's just that specific element that is not accessible. I try to access it after the page is fully loaded, and it still not working.
You can see in the code that I tried to override the writing-mode style with a different one, but if the browser doesn't recognize the element in the dome, the style can't apply to it.
My goal is to be able to override the writing-mode css style from inline, but an inline javascript code is also an option.

A: The id of element at console is #camera-1-height-spec , not #camera-1-height-specs
Substitute selector
$("#camera-1-height-spec")

without "s", for
$("#camera-1-height-specs")


text:
Q: Istio concepts - inter-service communication and tracing EDIT: I am rewriting this question to narrow the scope as suggested in comments.
Under Deploying the application, the documentation says,

To run the sample with Istio requires no changes to the application itself. Instead, you simply need to configure and run the services in an Istio-enabled environment, with Envoy sidecars injected along side each service.

I have a NodeJS back-end API, that writes logs with winston package. I would presume that, the application will have to be changed so that the logs from the winston package can participate in distributed tracing. Is this correct?

A: Distributed tracing systems in general require adding headers to outbound requests to tell the tracing system and downstream tasks which trace a given request belongs to.  While this isn't Istio-specific, Istio does document a list of OpenTracing headers that need to be passed along.  If you don't do this, then each call between services will show up as a separate trace instead of them being stitched together into a single unified end-to-end trace.
This is separate from your logging system.  Unless you're sending logs via HTTP to something like Logstash or directly into Elasticsearch, logs won't show up in traces at all.  The flip side of this is that you don't need to change anything in your logging setup to "work with" Istio, but mostly because there's not a lot of direct interaction.

A: No, your assumption is not correct. Istio tracing has nothing to do with logs. It's all about custom headers managed by Istio and modified automatically by sidecars to allow each sidecar processing traffic to put timestamp when traffic enters (request) and leaves (response). This gives you somewhat useful picture of actual delays between the containers participating in a network call.
On top of that, you are free to modify your app's code to include even more detailed method-level tracing using some OpenTracing-compatible lib for your app's language. Basically you add some lines besides your Winston logging in order to include checkpoints of your code execution pipeline too. While you can parse your logs and measure the same by math with log timestamps it's still way more job to be done to achieve what opentracing already offers you.


text:
Q: Casting of 2D array to double pointer fails Initialise a 2D array matrix as follows:
#define N 3
...
int matrix[N][N] = {};

The elements of the matrix can be accessed as follows:
for(i=0; i<N; ++i)
{
    for(j=0; j<N; ++j)
        printf("%d ", *(*(matrix + i) + j) );
    printf("\n");
}

However the following code fails with a segmentation fault.
int **matrix_pointer = (int **)matrix;
for(i=0; i<N; ++i)
{
    for(j=0; j<N; ++j)
        printf("%d ", *(*(matrix_pointer + i) + j) );
    printf("\n");
}

Please, Explain why or suggest an alternate method (with pointers) that works.

A: If defining
int matrix[3][5];

add then putting just matrix to the right of an =-operator, the array matrix decays (as every array would do) to the address of it's 1st element.
matrix's 1st element is an int[5]. The address of an int[5] is int(*)[5].
To if "putting just matrix to the right of a =-operator" then the left side of this assignment operation is expect to be a int(*)[5]:
int (*row)[5] = matrix;

Understanding the above it is obvious that doing
int ** ppi = matrix

cannot be correct as int ** is not the same as int(*)[5].
It assigns to a pointers from another pointer of different, will say incompatible type. The compiler would warn about this.
Apply a cast to the right hand side expression to fit the left hand side, is just telling the compiler to shut-up.


text:
Q: WPF deployed to Store missing some functionalities I've published a WPF app to the Microsoft Store. While it generally runs find I do find that some functionalities are missing. For example - I'm using TaskbarItemInfo to indicate stats on the Taskbar icon but it doesn't seem to make any effect.
(sample)
            Dispatcher.Invoke(new Action(() =>
            {
                TaskbarItemInfo.ProgressValue = value;
                TaskbarItemInfo.ProgressState = pstate;
            }));

I did find out that when I go to the path installed by the store (C:\Program Files\WindowsApps...) and copy the content to another folder on my hard drive, everything works fine.
This leads me to believe the problem is around a more restricted permissions for the store folder, but it's only an assumption at this point.
My questions are:

*

*Is there any knowledge or docs around restrictions for store apps?

*Is there a way to simulate the store environment without publishing? Feels like trial & error is not very effective

Link to the app (just for reference): link

A:
Is there any knowledge or docs around restrictions for store apps?

Yes, there is a document that lists the things you need to know before you package your desktop application. Here is it: Prepare to package a desktop application.

Is there a way to simulate the store environment without publishing? Feels like trial & error is not very effective

Generally, I'd suggest you create a sideload desktop-bridge package, then deploy and test it in your device first. This should be easier to find out issues than directly upload it to the store.


text:
Q: Как натягивать landing page на wordpress Как известно, в landing page содержатся много блоков, каким образом сохранять эти блоки, в качестве страниц, рубрик, записей?
Еще бывают моменты типа калькулятора, каким образом добавлять данные для него и куда создавать в админке новый тип записей, но это не совсем записи, это просто поля, так что не понимаю как.

A: Это называется "вёрстка". Верстаешь страницу как тебе надо.
См http://codex.wordpress.org/%D0%98%D0%B5%D1%80%D0%B0%D1%80%D1%85%D0%B8%D1%8F_%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD%D0%BE%D0%B2
Или берёшь готовую тему. Сейчас 90% тем имеют на морде лединг. Но не у всех нормальный функционал. У нек для этого используются плагины-конструкторы страниц (зло это). Одна из последних используемых мной тем с хорошим функционалом и без конструкторов: Himalayas
PS. Не забываем про механизм дочерних тем


text:
Q: error 500 for .htaccess error I am running a LAMP server, and this .htaccess is giving me a 500 error. What this does is filter keywords and redirect to the respective domain names.
Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{HTTP_HOST} xy|yz|xz
RewriteRule ^xyz.com

RewriteCond %{HTTP_HOST} ab|bc|ac
RewriteRule ^abc.net

<IfModule>

Error Message from error.log
/var/www/conf/.htaccess: <IfModule> directive requires additional arguments, referer: http://localhost/conf/rewrite.php

Why does it give me a 500 error, do I have to check if IfModule is installed, or has to be installed.
Thanks Jean

A: You are missing a slash. The closing tag must be
</ifModule>

that also explains the error message: <IfModule> directive requires additional arguments

A: You are using RewriteRule with only one parameter :
RewriteRule ^abc.net

Judging from the manual, the syntax is :
RewriteRule Pattern Substitution [flags]

I would say you need to indicate the destination of your rewriting.

A: You need to specify a pattern in the requested URL to match, and a destination to redirect to. Try:
RewriteRule (.*) http://abc.net$1


text:
Q: Time out prompt in imacros by using javascript How could it possible in Imacros to assign default number to variable.
After time out 10 seconds if user doesn't change number with in 10 seconds ?
var n = prompt ( " Number of loops. " , 500 ) ;

A: It's not possible because this control is integrated and built-in in the browser. It's not customizable. I'd advise against using if you have special needs.
You can do the same with FancyBox. I'm not sure if it has the timeout functionality, but even if not, you can close the FancyBox using its API.


text:
Q: Vba Convert days to Years, Months, Days I have this code that shows how old (by days) a file is:
Date_Created = Worksheets("FileCleaner").Range("D" & startrow).Value
File_Age_Day = DateDiff("d", Date_Created, Date)
Worksheets("FileCleaner").Range("E" & startrow).Value = File_Age_Day

Is there anyway that I can convert it to a format like this, lets say "0 Year 3 Months 3 days"?

A: As has already been noted by other users, you're going to run into difficulties because different months have different day counts and week counts (and a given year might have different day counts as well).
I think your best bet is to "assume" that a month has a given number of days (e.g. 30) and that you're not in a leap year. Then your algorithm would be something like this:
Private Const DAYS_IN_YEAR As Integer = 365
Private Const DAYS_IN_MONTH As Integer = 30

Public Sub OutputElapsed(days As Integer)
    Dim years As Integer, months As Integer, daysRemaining As Integer

    years = Int(days / DAYS_IN_YEAR)
    daysRemaining = days - (years * DAYS_IN_YEAR)

    months = Int(daysRemaining / DAYS_IN_MONTH)
    daysRemaining = daysRemaining - (months * DAYS_IN_MONTH)

    Debug.Print _
            years & " years, " & _
            months & " months, " & _
            daysRemaining & " days"
End Sub

A: This is the sub that I came up with to accomplish this task. I take a bit of a step back from your code. If I read your question right, you have a cell that contains a date Range("D" & startrow) and you then calculate the raw number of days since that date, and were then going to convert that number to years, months days. My code instead takes the string of the date from the cell (ex: 3/1/2019) and then calculates the years, months, and days passed independently. It takes into account the different days per each month and leap years and through my testing the only logic that isn't handled is if the date in the cell is actually in the future - I hope that's okay.
Sub DateCalc()
    'Worksheet Variables
    Dim mySheet As Worksheet
    Dim dateCell, outputCell As Range

    Set mySheet = Sheets("Sheet1")
    Set dateCell = mySheet.Cells(1, 1)
    Set outputCell = mySheet.Cells(1, 2)

    'Date variables
    Dim fileDate, curDate, tempDate As Date
    Dim fileYear, curYear, tempYear, years, _
    fileMonth, curMonth, tempMonth, months, _
    fileDay, curDay, tempDay, days, _
    curDPM, fileDPM _
    As Integer

    'Get date of file and calculate year, month, and day
    fileDate = dateCell.Value
    fileYear = CInt(Split(fileDate, "/")(2))
    fileMonth = CInt(Split(fileDate, "/")(0))
    fileDay = CInt(Split(fileDate, "/")(1))

    'Get the current date, year, month, and day
    curDate = Date
    curYear = CInt(Split(curDate, "/")(2))
    curMonth = CInt(Split(curDate, "/")(0))
    curDay = CInt(Split(curDate, "/")(1))

    'Calculate years passed
    If curYear > fileYear Then
        years = curYear - fileYear
    End If
    If years = "" Then
        years = 0
    End If

    'Calculate months passed
    If curMonth > fileMonth Then
        months = curMonth - fileMonth
    ElseIf curMonth = fileMonth Then
        months = 0
    ElseIf curMonth < fileMonth Then
        months = (12 - fileMonth) + curMonth
    End If

    'Calculates days per month (DPM) for current year
    Select Case curMonth
        Case 4 Or 6 Or 9 Or 11
            '31-Day months
            'April, June, September, November.
            curDPM = 30
        Case 2
            'February will either have 29 or 28 days
            'If the current year is divisible by 4 it
            'is a leap year and there are 29
            curDPM = IIf(curYear Mod 4 = 0, 29, 28)
        Case Else
            '31-Day months
            curDPM = 31
    End Select

    'Calculates days per month (DPM) for file year
    Select Case fileMonth
        Case 4 Or 6 Or 9 Or 11
            fileDPM = 30
        Case 2
            fileDPM = IIf(fileYear Mod 4 = 0, 29, 28)
        Case Else
            fileDPM = 31
    End Select

    'Calculates days passed
    If curDay > fileDay Then
        days = curDay - fileDay
    ElseIf (curDay = fileDay) Then
        days = 0
    ElseIf (curDay < fileDay) Then
        days = (fileDPM - fileDay) + curDay
    End If

    'years, months, and days are calculate independently
    'so this loop corrects them to work together
    'Ex: 12/31/2000 to 1/1/2001 would be 1 year, 1 month, 1 day without this loop
    Do
        tempDate = DateAdd("yyyy", years, fileDate)
        tempDate = DateAdd("m", months, tempDate)
        tempDate = DateAdd("d", days, tempDate)

        tempYear = CInt(Split(tempDate, "/")(2))
        tempMonth = CInt(Split(tempDate, "/")(0))
        tempDay = CInt(Split(tempDate, "/")(1))

        If tempYear > curYear Then
            years = years - 1
        ElseIf tempYear < curYear Then
            years = years + 1
        End If

        If tempMonth > curMonth Then
            months = months - 1
        ElseIf tempMonth < tempMonth Then
            months = months + 1
        End If

        If tempDay > curDay Then
            days = days - 1
        ElseIf tempDay < curDay Then
            days = days + 1
        End If
    Loop While tempDate <> curDate

    'Set cell to display time passed
    outputCell.Value = years & " Years, " & months & " Months, " & days & " Days"
End Sub

This is the output
All you should have to do to make it work for your individual worksheet is change the mySheet, dateCell, and outputCell variables. My date cells are set to the format of mm/dd/yyyy. I have not tested it with other date formats.

A: Here's my solution. I'm using this in my company, though it's written in Indonesian language as that's where I come from. It's a function where it takes two arguments: tanggal_akhir (which translates to 'start date') and tanggal_mulai (which translates to 'end date'). Formula is BEDATANGGAL which means 'date difference'. Hope it helps.
Function BEDATANGGAL(tanggal_mulai As Date, tanggal_akhir As Date)

Dim hari As Integer
Dim bulan As Integer
Dim tahun As Integer
Dim durasi As Integer
Dim tambah As Date

hari = 0
bulan = 0
tahun = 0
tambah = tanggal_mulai

durasi = DateDiff("d", tanggal_mulai, tanggal_akhir) - 1

For i = 0 To durasi

hari = hari + 1
tambah = tambah + 1

If Day(tanggal_mulai) = Day(tambah) Then

    hari = 0
    bulan = bulan + 1

    End If

If bulan = 12 Then

    hari = 0
    bulan = 0
    tahun = tahun + 1

    End If

Next i

BEDATANGGAL = tahun & " tahun, " & bulan & " bulan, " & hari & " hari"

End Function

A: Modification to the above answer by tyler
Function date_duration(start_date, end_date)
'Worksheet Variables

Dim dateCell, outputCell As Range

'Date variables
Dim fileDate, curDate, tempDate As Date
Dim fileYear, curYear, tempYear, years, _
fileMonth, curMonth, tempMonth, months, _
fileDay, curDay, tempDay, days, _
curDPM, fileDPM _
As Integer

'Get date of file and calculate year, month, and day
fileDate = start_date
fileYear = CInt(Split(fileDate, "/")(2))
fileMonth = CInt(Split(fileDate, "/")(0))
fileDay = CInt(Split(fileDate, "/")(1))

'Get the current date, year, month, and day
curDate = end_date
curYear = CInt(Split(curDate, "/")(2))
curMonth = CInt(Split(curDate, "/")(0))
curDay = CInt(Split(curDate, "/")(1))

'Calculate years passed
If curYear > fileYear Then
    years = curYear - fileYear
End If
If years = "" Then
    years = 0
End If

'Calculate months passed
If curMonth > fileMonth Then
    months = curMonth - fileMonth
ElseIf curMonth = fileMonth Then
    months = 0
ElseIf curMonth < fileMonth Then
    months = (12 - fileMonth) + curMonth
End If

'Calculates days per month (DPM) for current year
Select Case curMonth
    Case 4 Or 6 Or 9 Or 11
        '31-Day months
        'April, June, September, November.
        curDPM = 30
    Case 2
        'February will either have 29 or 28 days
        'If the current year is divisible by 4 it
        'is a leap year and there are 29
        curDPM = IIf(curYear Mod 4 = 0, 29, 28)
    Case Else
        '31-Day months
        curDPM = 31
End Select

'Calculates days per month (DPM) for file year
Select Case fileMonth
    Case 4 Or 6 Or 9 Or 11
        fileDPM = 30
    Case 2
        fileDPM = IIf(fileYear Mod 4 = 0, 29, 28)
    Case Else
        fileDPM = 31
End Select

'Calculates days passed
If curDay > fileDay Then
    days = curDay - fileDay
ElseIf (curDay = fileDay) Then
    days = 0
ElseIf (curDay < fileDay) Then
    days = (fileDPM - fileDay) + curDay
End If

'years, months, and days are calculate independently
'so this loop corrects them to work together
'Ex: 12/31/2000 to 1/1/2001 would be 1 year, 1 month, 1 day without this loop
Do
    tempDate = DateAdd("yyyy", years, fileDate)
    tempDate = DateAdd("m", months, tempDate)
    tempDate = DateAdd("d", days, tempDate)

    tempYear = CInt(Split(tempDate, "/")(2))
    tempMonth = CInt(Split(tempDate, "/")(0))
    tempDay = CInt(Split(tempDate, "/")(1))

    If tempYear > curYear Then
        years = years - 1
    ElseIf tempYear < curYear Then
        years = years + 1
    End If

    If tempMonth > curMonth Then
        months = months - 1
    ElseIf tempMonth < tempMonth Then
        months = months + 1
    End If

    If tempDay > curDay Then
        days = days - 1
    ElseIf tempDay < curDay Then
        days = days + 1
    End If
Loop While tempDate <> curDate

'Set cell to display time passed
date_duration = years & " Years, " & months & " Months, " & days & " Days"
End Function

A: Try the following.
date_created = Worksheets("FileCleaner").Range("D" & startrow).Value
File_Age_Day = DatePart("yyyy", date_created) & " years, " & DatePart("M",
date_created) & " Months, " & DatePart("d", date_created) & " days"
Worksheets("FileCleaner").Range("E" & startrow).Value = File_Age_Day


text:
Q: Need help trying to get a Python multiprocess pool working I have a database table I am reading rows from ( in this instance ~360k rows ) and placing the pyodbc.row objects into a list for later consumption then writing using this script.
from hashlib import sha1
import multiprocessing
import datetime, os
import pyodbc
import math
import traceback, sys
source_rows = []
processors = 8

def split(a, n):
    k, m = len(a) / n, len(a) % n
    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(n))

def sqn(*args):
    return sha1('}#EUCLID#{'.join([str(arg.upper().strip()) for arg in args]).encode()).hexdigest().upper()

def sDB_read():
    t1 = datetime.datetime.now()
    #Initialize Source Database
    src_driver='{SQL Server Native Client 11.0}'
    src_server='SCCMSV2SS010'
    src_database='STAGE'
    src_trusted_conn='yes'
    src_uid = 'myUserID'
    src_pwd = 'myPwd'
    if src_trusted_conn == 'yes':
        src_conn_str =  """Driver=""" + src_driver + """;Server=""" + src_server + """;Database=""" + src_database + """;Trusted_Connection=""" + src_trusted_conn + """;PacketSize=32767;"""
    else:
        src_conn_str =  """Driver=""" + src_driver + """;Server=""" + src_server + """;Database=""" + src_database + """;UID=""" + src_UID + """;PWD=""" + src_pwd + """;PacketSize=32767;"""
    sql = 'SELECT [AgentID]               ,[BootDevice00]              ,[BuildNumber00]              ,[BuildType00]              ,[Caption00]              ,[CodeSet00]              ,[CountryCode00]              ,[CSDVersion00]              ,[CurrentTimeZone00]              ,[Debug00]              ,[Description00]              ,[Distributed00]              ,[ForegroundApplicationBoost00]              ,[FreePhysicalMemory00]              ,[FreeSpaceInPagingFiles00]              ,[FreeVirtualMemory00]              ,[InstallDate00]              ,[InstanceKey]              ,[LastBootUpTime00]              ,[LocalDateTime00]              ,[Locale00]              ,[MachineID]              ,[Manufacturer00]              ,[MaxNumberOfProcesses00]              ,[MaxProcessMemorySize00]              ,[Name00]              ,[NumberOfLicensedUsers00]              ,[NumberOfProcesses00]              ,[NumberOfUsers00]              ,[OperatingSystemSKU00]              ,[Organization00]              ,[OSArchitecture00]              ,[OSLanguage00]              ,[OSProductSuite00]              ,[OSType00]              ,[OtherTypeDescription00]              ,[PlusProductID00]              ,[PlusVersionNumber00]              ,[Primary00]              ,[ProductType00]              ,[RegisteredUser00]              ,[RevisionID]              ,[rowversion]              ,[SerialNumber00]              ,[ServicePackMajorVersion00]              ,[ServicePackMinorVersion00]              ,[SizeStoredInPagingFiles00]              ,[Status00]              ,[SystemDevice00]              ,[SystemDirectory00]              ,[TimeKey]              ,[TotalSwapSpaceSize00]              ,[TotalVirtualMemorySize00]              ,[TotalVisibleMemorySize00]              ,[Version00]              ,[WindowsDirectory00]         FROM [STAGE].[dbo].[Operating_System_DATA]'
    src_db_conn = pyodbc.connect(src_conn_str)
    src_db_conn.autocommit = False
    src_db_cursor = src_db_conn.cursor()
    src_db_cursor.execute( sql )
    source_rows = [ {c[0]: v for (c, v) in zip(row.cursor_description, row)} for row in src_db_cursor.fetchall() ]
    t2 = datetime.datetime.now()
    print('\nWe Read ' + str(len(source_rows)) + ' rows in ' + str( t2 - t1 ))
    return source_rows

def tDB_write():
    print('\nPOOL: Received ' + str(len( source_rows )) + ' rows to work on')
    t1 = datetime.datetime.now()
    #Initialize Target Database
    targ_driver='{SQL Server Native Client 11.0}'
    targ_server='SCCMSV2SS010'
    targ_database='STAGE'
    targ_trusted_conn='yes'
    targ_uid = 'myUserID'
    targ_pwd = 'myPwd'
    if targ_trusted_conn == 'yes':
        targ_conn_str =  """Driver=""" + targ_driver + """;Server=""" + targ_server + """;Database=""" + targ_database + """;Trusted_Connection=""" + targ_trusted_conn + """;PacketSize=32767;"""
    else:
        targ_conn_str =  """Driver=""" + targ_driver + """;Server=""" + targ_server + """;Database=""" + targ_database + """;UID=""" + targ_UID + """;PWD=""" + targ_pwd + """;PacketSize=32767;"""
    targ_db_conn = pyodbc.connect(targ_conn_str)
    targ_db_conn.autocommit = False
    targ_db_cursor = targ_db_conn.cursor()
    table = 'Operating_System_DATA_INSERT'
    for sourceitems in source_rows:
        for source_row in sourceitems:
            try:
                sql = ''
                #print( str( source_row ) )
                columns = ', '.join( source_row.keys() )
                placeholders = ', '.join(['?'] * len( source_row ))
                obj = source_row.values()
                sql = "targ_db_cursor.execute('INSERT into {} ( {} ) VALUES ( {} )', {} )".format(table, columns, placeholders , obj )
                #print( sql )
                res = eval( sql )
            except Exception,e:
                traceback.print_exc(file=sys.stdout)
    targ_db_conn.commit()
    t2 = datetime.datetime.now()
    print('\nWe Wrote ' + str(len(source_rows)) + ' rows in ' + str( t2 - t1 ))
    return

if __name__ == '__main__':
    print( '\nStarting multiprocessing pool..' )
    pool = multiprocessing.Pool( processes = processors )
    source_rows = sDB_read()
    print( type(source_rows) )
    targetsize = len(source_rows)
    print( '\nProcessing ' + str(targetsize) + ' rows')
    chunksize = math.ceil(len(source_rows) / processors )
    print( 'Splitting into ' + str(processors) + " chunks with " + str(chunksize) + ' rows each')
    source_rows = list(split( source_rows , processors ))
    write_pool_outputs = pool.map( tDB_write() , source_rows )
    print( '\nClosing multiprocessing pool..' )
    pool.close()
    pool.join()

which provides the following output
c:\Python27>.\python27.exe .\multitest.py
Starting multiprocessing pool..
We Read 361554 rows in 0:00:14.064000
<type 'list'>
Processing 361554 rows
Splitting into 8 chunks with 45194.0 rows each
POOL: Received 8 rows to work on

I guess I am unclear on how to split/chunk the list up so each worker gets a equal share of the rows to work with. no matter if I try to split the list manually or just pass the unaltered one directly to the pool.map there is only one worker launched getting all the rows. Can some one educate me on the proper way to accomplish this?

A: I think you may be missing the chunksize in the pool.map call:
 map(func, iterable[, chunksize])

I gave an explanation of chunksize here: Python: multiprocess workers, tracking tasks completed (missing completions)
Hope this helps.


text:
Q: Reading and storing a string in java So let's say I'm given a chess piece that is at location "c4", so it's in the 3rd column and 4th row. How would one go about reading this "c4" string and then marking on the board that a piece is there.
I've been thinking one for loop that reads for characters and another that reads for numbers, but not sure how to mark that a piece is in a location like c4.
Any ideas/ideas to push me into right direction?

A: You'll probably want to store these values with a 2D array like so:
bool[][] board = new bool[8][8];
As for reading the string there a many ways you could go about it. I would use charAt to pull out the individual characters, then put the first one through a switch statement to find it's numeric value.
String input = "c4"
int row = Character.getNumericValue(input.charAt(1));
char columnChar = input.charAt(0);
int column;
switch (Character.toLowerCase(input.charAt(1)) {
    case 'a':
        column = 1;
    case 'b':
        column = 2;
    // etc...
}
board[column - 1][row - 1] = true; // Fill the board, subtracting one to account for arrays indexing from zero

Here I used an array of bools to keep track, but of course you'll need something more complicated to keep track of different pieces. Possibility creating a ChessPiece class and extending it to create each piece would be helpful.

A: This really depends on what you are and are not guaranteed in this situation.  Do you know for a fact the first character will always be a letter?  What is your number limit?
If you're guaranteed the first is always a character, as in a chessboard (an 8x8 grid), then you can just do a simple myStr.charAt(0) to get that, do something with that character, then replace what was there and convert the rest a la myStr.replace(oldChar, '') and parse it with Integer.parseInt().
If your data is not guaranteed and much more complicated you'll want to break your string into parts, parse through what you break it down to, and do something with the data.  For example if I was given the string "hh88", I would start by finding where my numbers start, separating those two parts out, and doing something with the data from there. The same idea applies if you're not guaranteed the same order i.e. "8c" was a valid string entry, the difference here is you'd need to identify where each component was.


text:
Q: UIAlertView compatible for iOS 7, 8, or later I have an issue with a simple alert view that used to work but since it has changed in iOS 8, Xcode tells me I have to have a "if available version check" but the more I do what it tells me the more errors I get. What is the correct way of having a UIAlertView that works with different iOS versions with a simple title, message and Ok button? This is the code I have been using which used to work fine:
let Alert = UIAlertController(title: "This is the title", message: "This is the message", preferredStyle: .Alert)

let DismissButton = UIAlertAction(title: "OK", style: .Cancel, handler: {

    (alert: UIAlertAction) -> Void in

})

Alert.addAction(DismissButton)

self.presentViewController(Alert, animated: true, completion: nil)

EDIT: With the research/suggestions of Xcode I have come up with the following code.
The error messages I am now getting are " use of unresolved identifier 'alert' "
on the last two lines.
if activePlace == -1 {

    if #available(iOS 8.0, *) {
        let Alert = UIAlertController(title: "No place Selected", message: "Please press on back button and select a place in the list to use directions", preferredStyle: .Alert)
    } else {
        // Fallback on earlier versions
    }

    if #available(iOS 8.0, *) {
        let DismissButton = UIAlertAction(title: "OK", style: .Cancel, handler: {

            (alert: UIAlertAction) -> Void in

        })
    } else {
        // Fallback on earlier versions
    }

    Alert.addAction(DismissButton)

    self.presentViewController(Alert, animated: true, completion: nil)


text:
Q: Python SQL Data to Array (like csv) currently I am trying to read my SQL-Data to an array in python.
I am new to python so please be kind ;)
My csv-export can be read easily:
data = pd.read_csv('esoc_data.csv', header = None)
 x = data[[1,2,3,4,5,6,7,8,9,10,11,12]]
This one picks the second column (starting from 1, not 0) till 12th column of my dataset. I need this data in this exact format!
Now I want to do the same with the data I get from my SQL-fetch.
names = [i for i in cursor.fetchall()]

This one gives me my data with all (0-12) columns and separated by ","
Result:

[(name@mail.com', 13, 13, 0, 24, 2, 0, 20, 3, 0, 31, 12, 2), (...)]

Now .. how do I get this into my "specific" format I mentioned before?
I just need the numbers like this:
      1   2   3   4   5   6   7    8    9  10  11  12
0    13  13   0  24   2   0  20    3    0  31  12   2
1    21   0   0  24   0   0  32    0    0  30   0   0
2     9   7   0  26  31   0  19   27    0  30  32   2

I'm sorry if this is peanuts for you.

A: You can run a multi-loop for this, something like
def our_method():
    parent_list = list()
    for name in names:
        child_list = list()
        for index, item in enumerate(name):
            if index != 0:
                child_list.append(item)
        parent_list.append(child_list)
    return parent_list


text:
Q: How to write isolinux to an ext4 filesystem How would I write isolinux to an ext4 filesystem on an 1 GB SD card so that it would boot at startup?

A: You wouldn't as a SD card normally doesn't look like a ISO image. Instead have a look at EXTLINUX.
In short:

*

*Mount your sd card

*run extlinux --install MOUNTPOINT/boot


text:
Q: How to merge two text (log) files, sorted according to timestamp using python only? File1 is having timestamp in 1st entry, File2 is having timestamp in 3rd entry.Entries are separated by space.
Example: File1
01-01 **00:00:26.334** MODEM_CTRL: !!! Open /sys/devices/platform/
01-01 **00:00:26.335** MODEMD  : ro.modem.external.enable value is
01-01 **00:00:26.338** MODEMD  : TD modem is not enabled
01-01 **00:00:26.342** MODEMD  : W modem is enabled
01-01 **00:00:26.349** MODEMD  : It's w native version
01-01 **00:00:26.358** MODEMD  : enter start_service!
01-01 **00:00:26.360** MODEMD  : open stty dev: /dev/stty_w0

File2 :
<random_data> <random_data> 01-01 **00:00:26.333** c0 Booting Linux on physical
<random_data> <random_data> 01-01 **00:00:26.335** c0 Initializing cgroup subsy
<random_data> <random_data> 01-01 **00:00:26.336** c0 Initializing cgroup subsy
<random_data> <random_data> 01-01 **00:00:26.341** c0 Linux version 3.10.17-000
<random_data> <random_data> 01-01 **00:00:26.346** c0 CPU: ARMv7 Processor [410
<random_data> <random_data> 01-01 **00:00:26.349** c0 CPU: PIPT / VIPT nonalias
<random_data> <random_data> 01-01 **00:00:26.350** c0 Machine: sc8830, model: S
<random_data> <random_data> 01-01 **00:00:26.355** c0 mem_cs_get dram_cs_num=1
<random_data> <random_data> 01-01 **00:00:26.357** c0 mem_cs0_size_get dram_cs0

Expected output:
<random_data> <random_data> 01-01 **00:00:26.333** c0 Booting Linux on physical
01-01 **00:00:26.334** MODEM_CTRL: !!! Open /sys/devices/platform/
01-01 **00:00:26.335** MODEMD  : ro.modem.external.enable value is
<random_data> <random_data> 01-01 **00:00:26.335** c0 Initializing cgroup subsy
<random_data> <random_data> 01-01 **00:00:26.336** c0 Initializing cgroup subsy
01-01 **00:00:26.338** MODEMD  : TD modem is not enabled
<random_data> <random_data> 01-01 **00:00:26.341** c0 Linux version 3.10.17-000
01-01 **00:00:26.342** MODEMD  : W modem is enabled
<random_data> <random_data> 01-01 **00:00:26.346** c0 CPU: ARMv7 Processor [410
<random_data> <random_data> 01-01 **00:00:26.349** c0 CPU: PIPT / VIPT nonalias
01-01 **00:00:26.349** MODEMD  : It's w native version
<random_data> <random_data> 01-01 **00:00:26.350** c0 Machine: sc8830, model: S
<random_data> <random_data> 01-01 **00:00:26.355** c0 mem_cs_get dram_cs_num=1
<random_data> <random_data> 01-01 **00:00:26.357** c0 mem_cs0_size_get dram_cs0
01-01 **00:00:26.358** MODEMD  : enter start_service!
01-01 **00:00:26.360** MODEMD  : open stty dev: /dev/stty_w0

Question is different from the one, ift is marked duplicate of.
1> my files don't have any columns as entries are separated by spaces only.
2> Because that uses awk, And I need it in python only.
3> I don't want to merge only columns, I want to merge all full lines. the other one is just pasting column to first file.


text:
Q: WordPress: Custom default avatar on localhost? I'm trying to add a custom default avatar to WordPress in functions.php, but the image is not displaying in Settings/Discussion or elsewhere on the site. The code works because a new radio field is added with the custom field name, but the image won't display. Is the avatar not displaying because I'm using Localhost?
I don't have enough reps to comment on similar questions.
here's the code:
add_filter( 'avatar_defaults' , 'wps_new_avatar' );
function wps_new_avatar( $avatar_defaults ){
    $new_avatar = get_stylesheet_directory_uri() . '/images/default-avatar.png';
    $avatar_defaults[$new_avatar] = "Default Avatar";
    return $avatar_defaults;
}

I've tried other examples and the 'Add-New-Default-Avatar' plugin with the same result.

A: I was facing the same issue and came up with this completely hackish solution... It works though :)
add_filter( 'get_avatar', 'so_14088040_localhost_avatar', 10, 5 );

function so_14088040_localhost_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
    $whitelist = array( 'localhost', '127.0.0.1' );

    if( !in_array( $_SERVER['SERVER_ADDR'] , $whitelist ) )
        return $avatar;

    $doc = new DOMDocument;
    $doc->loadHTML( $avatar );
    $imgs = $doc->getElementsByTagName('img');
    if ( $imgs->length > 0 )
    {
        $url = urldecode( $imgs->item(0)->getAttribute('src') );
        $url2 = explode( 'd=', $url );
        $url3 = explode( '&', $url2[1] );
        $avatar= "<img src='{$url3[0]}' alt='' class='avatar avatar-64 photo' height='64' width='64' />";
    }

    return $avatar;
}

Result:

Of course, this filter is meant for development only.


text:
Q: how to pass data to Tbxml in iphone i am trying to use TBXML, i want to parse xml by sending username and password but dnt how to do it, i have already gone through many tutorials.
  -(IBAction)login{
                    NSString *str2=emailtxt.text;
                    NSString *str3=passtxt.text;

                    TBXML * tbxml = [TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.vinipost.com/my_service.asmx/signIn"]];

                    TBXMLElement *rootXMLElement = tbxml.rootXMLElement;

                    if (rootXMLElement)
                    {
                        TBXMLElement * user = [TBXML childElementNamed:@"Table1" parentElement:rootXMLElement];

                        while (user != nil)
                        {

                            TBXMLElement *CountryId = [TBXML childElementNamed:@"usrid" parentElement:user];
                            if (CountryId != nil)
                            {
                                NSLog(@"CountryId :: %@", [TBXML textForElement:CountryId]);
                            }

                            TBXMLElement *CountryName = [TBXML childElementNamed:@"ContctNmbr" parentElement:user];
                            if (CountryName != nil)
                            {
                                NSLog(@"CountryName :: %@", [TBXML textForElement:CountryName]);
                            }

                            user = [TBXML nextSiblingNamed:@"Table1" searchFromElement:user];
                        }
                    }
                }

A: Change your URL to
[NSURL URLWithString:@"http://www.vinipost.com/my_service.asmx/signIn?email=yourEmail&pass=yourPass"];

You can set your email and password on runtime by following this link Operation On String


text:
Q: Interpreting non-orthogonal contrasts R I'm having trouble finding information on helping me understand how to interpret non-orthogonal contrasts in a regression model.
I have simulated some data to show what I am working with:
set.seed(5552)
Subject <- 1:30
Group <- c(rep("Control", times = 10), rep("Experimental 1", times = 10), rep("Experimental 2", times = 10))
Pre <- round(rnorm(n = Subject, mean = 25, sd = 5), 1)
Post <- c(round(rnorm(n = 10, mean = 25, sd = 5), 1),
            round(rnorm(n = 10, mean = 28, sd = 3),1),
            round(rnorm(n = 10, mean = 33, sd = 4),1))

dat <- data.frame(Group, Subject, Pre, Post)
dat$Diff <- with(dat, Post - Pre)
dat

Model 1: Here is the regression model using the default contrasts in R:
model1.lm <- lm(Diff ~ Group, data = dat)
summary(model1.lm)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)            0.750      1.960   0.383  0.70495
GroupExperimental 1    3.530      2.772   1.274  0.21365
GroupExperimental 2    8.430      2.772   3.042  0.00519 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

The interpretation here is easy as each coefficient is the difference between that group and the reference (control) group, reflected as the intercept.
Model 2: Now, I change the contrasts to orthogonal:
contrast1 <- c(-2,1,1)
contrast2 <- c(0,1,-1)
contrasts(dat$Group) <- cbind(contrast1, contrast2)

Now re-run the regression model:
model1.lm2 <- lm(Diff ~ Group, data = dat)
summary(model1.lm2)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      4.7367     1.1315   4.186  0.00027 ***
Groupcontrast1   1.9933     0.8001   2.491  0.01917 *
Groupcontrast2  -2.4500     1.3858  -1.768  0.08837 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

Okay, this output makes sense. The intercept now reflects the grand mean. The coefficient for contrast 1 (1.99) is the difference between the pooled mean of the 2 experimental groups and the control group, divided by3. The coefficient for contrast 2 now represents the difference between experimental group 2 and experimental group 3, divided by 2.
Model 3: Now, what if I make the contrasts non-orthogonal. I'll keep the first contrast the same (Control Group vs Both Experimental Groups) and change the second contrast to the Control Group vs Experimental Group 2. Because the Control group is entered back into another contrast, this analysis is non-orthogonal. Here are the contrasts:
contrast1 <- c(-2,1,1)
contrast2 <- c(-1,0,1)
contrasts(dat$Group) <- cbind(contrast1, contrast2)

Now re-run the regression:
model1.lm3 <- lm(Diff ~ Group, data = dat)
summary(model1.lm3)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      4.7367     1.1315   4.186  0.00027 ***
Groupcontrast1  -0.4567     1.6002  -0.285  0.77753
Groupcontrast2   4.9000     2.7716   1.768  0.08837 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

How do I best interpret these non-orthogonal contrasts? The intercept is the same as the orthogonal model, the grand mean. Coefficient 1 has changed yet the contrast is the same as the orthogonal model, it doesn't really make sense to me as to why? I can't make sense of the 2nd coefficient either.

A: The $\beta$s can be interpreted as weighted group means. However, the weights are not given by the coding matrix $\mathbf{B}$ that you specified, but by its inverse, namely, the contrast matrix $\mathbf{C} = \mathbf{B}^{-1}$:
    $$\beta = \mathbf{C} \mu = \mathbf{B}^{-1} \mu.$$
You can find details in the vignette of the R package codingMatrices, and I have a blog post about it here.
I'll go through your three models to illustrate the interpretation of the $\beta$s. (Instead of calculating the inverse by hand, I'll use codingMatrices::mean_contrasts(), which is really just a wrapper around solve(cbind(1, B)), but has nicer output.)
Dummy Coding
Looking at $\mathbf{C}$ instead of $\mathbf{B}$ we directly see that $\beta_0=1\mu_1$ (m1), $\beta_1=-1\mu_1+1\mu_2$ (-m1+m2), and $\beta_2=-1\mu_1+1\mu_3$.
(B1 <- contr.treatment(3))
#>   2 3
#> 1 0 0
#> 2 1 0
#> 3 0 1
codingMatrices::mean_contrasts(B1)
#>     m1 m2 m3
#> Ave  1  .  .
#> 2   -1  1  .
#> 3   -1  .  1

Orthogonal Contrasts
Here, $\mathbf{C}$ and $\mathbf{B}$ are structurally so similar that you knew the meaning of the $\beta$s without explicitly knowing $\mathbf{C}$.
(B2 <- cbind(c(-2, 1, 1), c(0, 1, -1)))
#>      [,1] [,2]
#> [1,]   -2    0
#> [2,]    1    1
#> [3,]    1   -1
codingMatrices::mean_contrasts(B2)
#>     m1   m2   m3
#> Ave  1/3  1/3  1/3
#>     -1/3  1/6  1/6
#>        .  1/2 -1/2

Nonorthogonal Contrasts I
Here, $\mathbf{C}$ and $\mathbf{B}$ are structurally completely different. You wanted to compare $\mu_3$ with $\mu_1$ but actually compared it with $\mu_2$ ($9.18 - 4.28 = 4.90$). As you can see, multiplying the contrasts of $\mathbf{C}$ with the group means gives you the $\beta$s.
(B3 <- cbind(c(-2, 1, 1), c(-1, 0, 1)))
#>      [,1] [,2]
#> [1,]   -2   -1
#> [2,]    1    0
#> [3,]    1    1
codingMatrices::mean_contrasts(B3)
#>     m1   m2   m3
#> Ave  1/3  1/3  1/3
#>     -1/3  2/3 -1/3
#>        .   -1    1

(group_means <- tapply(dat$Diff, dat$Group, mean))
#>        Control Experimental 1 Experimental 2
#>           0.75           4.28           9.18
codingMatrices::mean_contrasts(B3) %*% array(group_means, dim = c(3, 1))
#>           [,1]
#> Ave  4.7366667
#>     -0.4566667
#>      4.9000000

model1.lm3 <- lm(Diff ~ Group, data = dat, contrasts = list(Group = B3))
coef(model1.lm3)
#> (Intercept)      Group1      Group2
#>   4.7366667  -0.4566667   4.9000000

Nonorthogonal Contrasts II
We can use this the other way round and specify a matrix $\mathbf{C}$ to to compare $\mu_3$ with $\mu_1$. Then, we use its inverse as input to lm(), and this will give you the desired result, namely the difference between group 3 and group 1 which is $9.18 - 0.75 = 8.43$.
(C4 <- rbind(1/3, c(-1, 0.5, 0.5), c(-1, 0, 1)))
#>            [,1]      [,2]      [,3]
#> [1,]  0.3333333 0.3333333 0.3333333
#> [2,] -1.0000000 0.5000000 0.5000000
#> [3,] -1.0000000 0.0000000 1.0000000
solve(C4)
#>      [,1]       [,2] [,3]
#> [1,]    1 -0.6666667    0
#> [2,]    1  1.3333333   -1
#> [3,]    1 -0.6666667    1

model1.lm4 <- lm(Diff ~ Group, data = dat,
                 contrasts = list(Group = solve(C4)[, -1]))
coef(model1.lm4)
#> (Intercept)      Group1      Group2
#>    4.736667    5.980000    8.430000

In summary, if you want to know how to interpret the estimated $\beta$s, you have to look at the inverse of your design/coding matrix. It may be obvious for standard schemes (e.g., dummy) or for orthogonal contrasts, but definitely not for non-standard non-orthongonal coding schemes.


text:
Q: Sorting a DStream and taking topN I have some DStream in Spark Scala and I want to sort it then take the top N.
The problem is that whenever I try to run it I get NotSerializableException and the exception message says:

This is because the DStream object is being referred to from within the closure.

The problem is that I don't know how to solve it:
Here is my try:
package com.badrit.realtime

import java.util.Date

import com.badrit.drivers.UnlimitedSpaceTimeDriver
import com.badrit.model.{CellBuilder, DataReader, Trip}
import com.badrit.utility.Printer
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.{Duration, Milliseconds, StreamingContext}

import scala.collection.mutable

object StreamingDriver {
    val appName: String = "HotSpotRealTime"
    val hostName = "localhost"
    val port = 5050
    val constrains = UnlimitedSpaceTimeDriver.constrains;
    var streamingRate = 1;
    var windowSize = 8;
    var slidingInterval = 2;
    val cellBuilder = new CellBuilder(constrains)
    val inputFilePath = "/home/ahmedelgamal/Downloads/green_tripdata_2015-02.csv"

    def prepareTestData(sparkStreamCtx: StreamingContext): InputDStream[Trip] = {

        val sparkCtx = sparkStreamCtx.sparkContext
        val textFile: RDD[String] = sparkCtx.textFile(inputFilePath)
        val data: RDD[Trip] = new DataReader().getTrips(textFile)
        val groupedData = data.filter(_.pickup.date.before(new Date(2015, 1, 2, 0, 0, 0)))
          .groupBy(trip => trip.pickup.date.getMinutes).sortBy(_._1).map(_._2).collect()

        printf("Grouped Data Count is " + groupedData.length)
        var dataQueue: mutable.Queue[RDD[Trip]] = mutable.Queue.empty;

        groupedData.foreach(trips => dataQueue += sparkCtx.makeRDD(trips.toArray))
        printf("\n\nTest Queue size is " + dataQueue.size)

        groupedData.zipWithIndex.foreach { case (trips: Iterable[Trip], index: Int) => {
            println("Items List " + index)

            val passengers: Array[Int] = trips.map(_.passengers).toArray
            val cnt = passengers.length
            println("Sum is " + passengers.sum)
            println("Cnt is " + cnt)

            val passengersRdd = sparkCtx.parallelize(passengers)
            println("Mean " + passengersRdd.mean())
            println("Stdv" + passengersRdd.stdev())

        }
        }
        sparkStreamCtx.queueStream(dataQueue, true)
    }

    def cellCreator(trip: Trip) = cellBuilder.cellForCarStop(trip.pickup)

    def main(args: Array[String]) {
        if (args.length < 1) {
            streamingRate = 1;
            windowSize = 3 //2 hours 60 * 60 * 1000L
            slidingInterval = 2 //0.5 hour 60 * 60 * 1000L
        }
        else {
            streamingRate = args(0).toInt;
            windowSize = args(1).toInt
            slidingInterval = args(2).toInt
        }

        val sparkConf = new SparkConf().setAppName(appName).setMaster("local[*]")
        val sparkStreamCtx = new StreamingContext(sparkConf, Milliseconds(streamingRate))
        sparkStreamCtx.sparkContext.setLogLevel("ERROR")
        sparkStreamCtx.checkpoint("/tmp")

        val data: InputDStream[Trip] = prepareTestData(sparkStreamCtx)
        val dataWindow = data.window(new Duration(windowSize), new Duration(slidingInterval))

        //my main problem lies in the following line
        val newDataWindow = dataWindow.transform(rdd => sparkStreamCtx.sparkContext.parallelize(rdd.take(10)))
        newDataWindow.print

        sparkStreamCtx.start()
        sparkStreamCtx.awaitTerminationOrTimeout(1000)

    }
}

I don't mind any other ways to sort a DStream and get its top N rather than my way.

A: You can use transform method in the DStream object then sort the input RDD and take n elements of it in a list, then filter the original RDD to be contained in this list.
val n = 10
val topN = result.transform(rdd =>{
   val list = rdd.sortBy(_._1).take(n)
   rdd.filter(list.contains)
})
topN.print


text:
Q: PCI-E USB Controller not Recognizing Legacy USB devices I recently installed a pci-e usb 3.0 controller that uses the VL805 chipset. I did this because I wanted to hook up an old arcadestick that only uses UHCI (which this card supports). After I installed the card using the drivers VIA provided, the joystick worked. This morning I booted up my PC and the joystick no longer worked even though I made no changes. My machine is running windows 10 n pro, and I have an Intel processor.
What could be causing this problem? How would I go about troubleshooting?


text:
Q: add_submenu_page to a php file not a function I am using the below code to add a menu and add a sub menu.
function register_gapi_menu_page(){

   add_menu_page( 'Posts with analytic', 'Posts with analytic', 'manage_options', 'analyticapi/gapi.php', '', '' );
   add_submenu_page( 'analyticapi/gapi.php', 'Test Analytic', 'Tests', 'manage_options', 'analyticapi/test.php', '' );
}
add_action( 'admin_menu', 'register_gapi_menu_page' );

It works fine when I work in localhost. I get two link to handle each menu page. which work PERFECTLY the way I want.
http://wordpress.local/wp-admin/admin.php?page=analyticapi/gapi.php

http://wordpress.local/wp-admin/admin.php?page=analyticapi/test.php

.
But when i upload it to my server. The Submenu page link become.
http://www.xxxxxx.org/wp-admin/analyticapi/test.php

Which give me 500 Internal Server Error
And if I change the submenu code into  ( prefixing admin.php?page= )
add_submenu_page( 'analyticapi/gapi.php', 'Test Analytic', 'Tests', 'manage_options', 'admin.php?page=analyticapi/test.php', '' );

When I visit the link. It says "I DONT HAVE ENOUGH PERMISSION TO VISIT"
How i can fix this?  I want to use separate php file for each menu page.


text:
Q: Calculate previous year end date from current date I have a bus_date column. which has multiple records with different date i.e 2021-03-15, 2021-05-12, 2021-01-15 etc.
I want to calculate previous year end for all given dates. my expected output is 2020-12-31 for all three dates.
However, I can use function date_sub(start_date, num_days).
but I don't want to manually pass num_days. since there are million of rows with diff dates.
Can we write a view from a table or create dataframe, which will calculate previous year end?

A: You can use date_add and date_trunc to achieve this.
import pyspark.sql.functions as F

......
data = [
    ('2021-03-15',),
    ('2021-05-12',),
    ('2021-01-15',)
]
df = spark.createDataFrame(data, ['bus_date'])
df = df.withColumn('pre_year_end', F.date_add(F.date_trunc('yyyy', 'bus_date'), -1))
df.show()


text:
Q: Can I suppress all warnings when including a specific file? I'm working with a recent version of gcc, writing C++ code (but I would like an answer which would work for C as well). I have various extra warning flags enabled.
In my code, I am including a header from some popular library, #include <mylib.h>. Now, mylib.h triggers some of these compiler warnings; but I need to include it as-is, I can't alter it.
I want to suppress all compiler warnings when including mylib.h. I know I can suppress individual warnings with:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwarning-name-here"
#pragma GCC diagnostic ignored "-Wanother-warning-name-here"

// my code goes here

#pragma GCC diagnostic pop

but I want to suppress all of the warnings. Can I do that? Note that I'm willing to tweak the compiler command-line if that helps.
Note: This related question indicates that, in 2015, one could not do this using pragmas.

A: From GCC manual:

2.7 System Headers
The header files declaring interfaces to the operating system and
runtime libraries often cannot be written in strictly conforming C.
Therefore, GCC gives code found in system headers special treatment.
All warnings, other than those generated by `#warning' (see
Diagnostics), are suppressed while GCC is processing a system header.
Macros defined in a system header are immune to a few warnings
wherever they are expanded. This immunity is granted on an ad-hoc
basis, when we find that a warning generates lots of false positives
because of code in macros defined in system headers.
Normally, only the headers found in specific directories are
considered system headers. These directories are determined when GCC
is compiled. There are, however, two ways to make normal headers into
system headers.
The -isystem command line option adds its argument to the list of
directories to search for headers, just like -I. Any headers found in
that directory will be considered system headers.
All directories named by -isystem are searched after all directories
named by -I, no matter what their order was on the command line. If
the same directory is named by both -I and -isystem, the -I option is
ignored. GCC provides an informative message when this occurs if -v is
used.
There is also a directive, #pragma GCC system_header, which tells GCC
to consider the rest of the current include file a system header, no
matter where it was found. Code that comes before the `#pragma' in the
file will not be affected. #pragma GCC system_header has no effect in
the primary source file.

how to make this happen in CMake?

From CMake manual:

include_directories
Add include directories to the build.
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])

...
If the SYSTEM option is given, the compiler will be told the directories are meant as system include directories on some platforms. Signalling this setting might achieve effects such as the compiler skipping warnings, or these fixed-install system files not being considered in dependency calculations - see compiler docs.


text:
Q: How to restart tasklet at specific interval I have spring batch job as follows:
   <job id="messageConsumerJob"  xmlns="http://www.springframework.org/schema/batch">
    <split id="split1" task-executor="taskExecutor">
        <flow>
            <batch:step id="messageConsumerStep">
                <batch:partition step="receiverStep" partitioner="messageConsumer">
                    <batch:handler grid-size="10" task-executor="taskExecutor" />
                </batch:partition>
            </batch:step>
        </flow>
        <flow>
            <step id="publishStep">
                <tasklet ref="messagePublish" />
            </step>
        </flow>
    </split>
</job>

I want to restart the receiver step every 2 days.


text:
Q: Invoke Soap Service Using Proxy Service I want to create a proxy service to call an external Soap service using wso2 proxy service.
I have created a proxy service like this:
<target>
    <inSequence>
        <property name="messageType" value="text/xml" scope="axis2"/>
        <property name="ContentType" value="text/xml" scope="axis2"/>
    </inSequence>
    <outSequence>
        <property name="messageType" value="text/xml" scope="axis2"/>
        <property name="ContentType" value="text/xml" scope="axis2"/>
        <send/>
    </outSequence>
    <faultSequence>
        <log level="full">
            <property name="MESSAGE" value="Executing default "fault" sequence"/>
            <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
            <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
        </log>
        <log level="custom">
            <property name="Trace" expression="get-property('ERROR_DETAIL')"/>
        </log>
    </faultSequence>
    <endpoint>
        <address uri="http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit"/>
    </endpoint>
</target>

Please have a look into this link (http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit)
I want to call this Soap Service using a proxy service.
I am using REST Client (Mozilla Firefox Addon) and
My Input Request:
<CelsiusToFahrenheit xmlns="http://www.w3schools.com/webservices/">
 <Celsius>33</Celsius>
</CelsiusToFahrenheit>

I am getting an error while calling this service using a proxy service.
Below is my error. I have enabled TRACE on my proxy service configuration.
[2014-03-17 11:42:16,187]  WARN {SERVICE_LOGGER.FilterMediatorProxy} -  Executing fault handler due to exception encountered
[2014-03-17 11:42:16,188]  WARN {SERVICE_LOGGER.FilterMediatorProxy} -  ERROR_CODE : 0 ERROR_MESSAGE : Unexpected error during sending message out
[2014-03-17 11:42:16,188]  INFO {SERVICE_LOGGER.FilterMediatorProxy} -  FaultHandler executing impl: org.apache.synapse.mediators.MediatorFaultHandler
[2014-03-17 11:42:16,189]  WARN {SERVICE_LOGGER.FilterMediatorProxy} -  Executing fault sequence mediator : org.apache.synapse.mediators.base.SequenceMediator
[2014-03-17 11:42:16,194]  INFO {SERVICE_LOGGER.FilterMediatorProxy} -  To: http://10.132.97.131:9763/services/FilterMediatorProxy.FilterMediatorProxyHttpEndpoint/, From: 10.132.97.131, Direction: request, MESSAGE = Executing default "fault" sequence, ERROR_CODE = 0, ERROR_MESSAGE = Unexpected error during sending message out, Envelope:
<?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body>
<CelsiusToFahrenheit xmlns="http://www.w3schools.com/webservices/">
   <Celsius>33</Celsius>
</CelsiusToFahrenheit></soapenv:Body></soapenv:Envelope>
[2014-03-17 11:42:16,206]  INFO {SERVICE_LOGGER.FilterMediatorProxy} -
Trace = org.apache.synapse.SynapseException: Unexpected error during sending message out
    at org.apache.synapse.core.axis2.Axis2Sender.handleException(Axis2Sender.java:172)
    at org.apache.synapse.core.axis2.Axis2Sender.sendOn(Axis2Sender.java:71)
    at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.send   (Axis2SynapseEnvironment.java:338)
    at org.apache.synapse.endpoints.AbstractEndpoint.send(AbstractEndpoint.java:333)
    at org.apache.synapse.endpoints.AddressEndpoint.send(AddressEndpoint.java:59)
    at org.apache.synapse.core.axis2.ProxyServiceMessageReceiver.receive(ProxyServiceMessageReceiver.java:187)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
    at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
    at org.wso2.carbon.core.transports.CarbonServlet.doPost(CarbonServlet.java:231)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.equinox.http.helper.FilterServletAdaptor$FilterChainImpl.doFilter(FilterServletAdaptor.java:56)
    at org.wso2.carbon.mashup.jsservices.custom.ui.CustomUIServletFilter.doFilter(CustomUIServletFilter.java:233)
    at org.eclipse.equinox.http.helper.FilterServletAdaptor.service(FilterServletAdaptor.java:37)
    at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
    at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
    at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.axis2.AxisFault: Connection refused: connect
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:197)
    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)
    at org.apache.synapse.core.axis2.DynamicAxisOperation$DynamicOperationClient.send(DynamicAxisOperation.java:185)
    at org.apache.synapse.core.axis2.DynamicAxisOperation$DynamicOperationClient.executeImpl(DynamicAxisOperation.java:167)
    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at org.apache.synapse.core.axis2.Axis2FlexibleMEPClient.send(Axis2FlexibleMEPClient.java:482)
    at org.apache.synapse.core.axis2.Axis2Sender.sendOn(Axis2Sender.java:59)
    ... 44 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140)
    at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:125)
    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:622)
    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
    ... 53 more

What's wrong in my configuration? While I am directly calling the Soap service (without using any proxy from REST client), I am getting the response correctly.

A: You must send the request to the back-end service,
in following proxy, in inSequence it sends the request to the back-end service and the response of the back-end service is sent back to the client in outSequence by the <send/>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="CelsiusToFahrenheitService"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <send>
            <endpoint>
               <address uri="http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit"/>
            </endpoint>
         </send>
      </inSequence>
      <outSequence>
         <log level="full"/>
         <send/>
      </outSequence>
   </target>
   <description/>
</proxy>

I tested the above proxy using the Try this service in ESB,
Request is,
<body>
 <CelsiusToFahrenheit xmlns="http://www.w3schools.com/webservices/">
   <Celsius>88</Celsius>
 </CelsiusToFahrenheit>
</body>

And I got the following response,
<CelsiusToFahrenheitResponse xmlns="http://www.w3schools.com/webservices/">
   <CelsiusToFahrenheitResult>190.4</CelsiusToFahrenheitResult>
</CelsiusToFahrenheitResponse>


text:
Q: Is it possible to put Firefox into full screen mode programmatically? I'm testing something using Splinter / Selenium, using the Firefox webdriver.
I'd like to automate getting the browser into full screen mode. I've tried mozRequestFullScreen but it won't co-operate - I get errors about it not being triggered by a user event (presumably this is a security thing). Is there a way to run Firefox where it will allow this? Or a profile setting or something?


text:
Q: Open a new VC when pressing a button from a tableViewCell The problem is when I m trying to open a new VC when a button from a specific tableViewCell is pressed.
 Bellow is my tableView which is loading the cells. The one from section 0 is the one with the button.
class NewConversationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 1
    } else if section == 1{
        return friendList.count
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewGroupConversationCell") as! NewGroupConversationTableViewCell

        return cell
    } else if indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewConversationCell") as! NewConversationTableViewCell
        let friendList = self.friendList[indexPath.row]
        cell.populate(friendList)

        return cell
    }
    return UITableViewCell()
}

Bellow is the cell with the button and the action which will present the specific viewController which i want
class NewGroupConversationTableViewCell: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func groupButtonPressed(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let messagesViewController = storyboard.instantiateViewController(withIdentifier: "GroupListViewController") as! GroupListViewController
    self.window?.rootViewController?.present(messagesViewController, animated: true, completion: nil)
}

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[VoiceMe.GroupListViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7fb33171c4d0'

A: You can't do it like this, so those are the steps to open you VC:
1 - Add a target function to your button in:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewGroupConversationCell") as! NewGroupConversationTableViewCell
        cell.youButton.addTarget(self, action:#selector(handleBtnAction(sender:)), for: .touchUpInside)
        cell.youButton.tag = indexPath.row
        return cell
    }
    ...

2 - implement your selector:
func handleBtnAction(sender: UIButton){
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let messagesViewController = storyboard.instantiateViewController(withIdentifier: "GroupListViewController") as! GroupListViewController
    self.navigationController?.pushViewController(messagesViewController, animated: true)
}


text:
Q: Pgadmin4 installation fails on Ubuntu 18.04 Bionic Beaver I am trying to install pgadmin4 on Ubuntu 18.04 Bionic Beaver but every time I try to run the
sudo apt install pgadmin4 pgadmin4-apache2

it returns the following error:
Building dependency tree
Reading state information... Done
E: Unable to locate package pgadmin4-apache2

I read almost everything available in SO (e.g. link1, link2) but I always get the above mentioned error.
I do not want to install it by using Docker.
Could someone provide a solution for this?
Thanks!

A: There is no pgadmin4-apache2 package.  There never has been.
Upstream Postgres repositories however have a pgadmin4-web function though that will make it a webserver like function and configure webserver components.
From the pgadmin4 download/repositories page come instructions for using their repository:
#
# Setup the repository
#

# Install the public key for the repository (if not done previously):
sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add

# Create the repository configuration file:
sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'

#
# Install pgAdmin
#

# Install for both desktop and web modes:
sudo apt install pgadmin4

# Install for desktop mode only:
sudo apt install pgadmin4-desktop

# Install for web mode only:
sudo apt install pgadmin4-web

# Configure the webserver, if you installed pgadmin4-web:
sudo /usr/pgadmin4/bin/setup-web.sh

Desktop mode is as if you are the only user and using it as a desktop GUI on your system to maintain multiple postgres servers and disables authentication on the pgAdmin component so you don't have users, etc. configurable on the pgAdmin component.
Web mode is the 'server' mode and when installed works like phpMyAdmin does, except for Postgres stuff.
Install either mode you wish, but if you're configuring it so that it's served by a webserver, you want pgadmin4-web and need to run the configuration program as listed in the last line of their instructions.
At the time of writing, this works for the following non-EOL and still supported Ubuntu releases:

*

*Ubuntu 18.04 (Bionic)

*Ubuntu 20.04 (Focal)

*Ubuntu 20.10 (Groovy, from v4.30)