text:
Q: to get nth highest salary from a table there is a code which i dont understand
*

*first of all i cant understand how a.salary <= b.salary internally works. if worker a and worker b are clones then how is >= computed internally and if the sign is changed to <,>,= HOW is it working?

*COUNT(distinct salary)  should just give a number so if there are 3 distinct salaries there should be value 3 for it. if I execute it without the 'where' condition then  it does'nt show any result.

*how does the 'where 1=' actually work? it shows different result for 2>=,3>= etc.
there are other methods to find the nth highest salary but i need to understand this one
select distinct salary
from worker a
where 1 = (select COUNT(distinct salary) from worker b where a.salary >= b.salary)

A: Consider this table:
create table worker(name varchar(10), salary int);
insert into worker(name, salary) values
('Alice', 500),('Bob', 400),('John', 500),('Nick', 400),('Mary', 300),('Jill', 300);

And these queries with the corresponding results:
select count(distinct salary) counter from worker where salary >= 500
| counter |
|       1 |

select count(distinct salary) counter from worker where salary >= 400
| counter |
|       2 |

select count(distinct salary) counter from worker where salary >= 300
| counter |
|       3 |

What these queries do is return the number of distinct salaries that are greater or equal than a certain amount.
So if there is a salary = 500 since the result of the 1st query is 1 this means that there isn't any salary greater than this, so this is the max salary because the number of distinct salaries that are greater or equal to that salary is 1.
The 2nd query's result is 2 and this means that there is only 1 distinct salary greater than 400, so this the 2nd greater salary of all.
Now consider the same queries with the reverse inequality sign:
select count(distinct salary) counter from worker where 300 >= salary
| counter |
|       1 |

select count(distinct salary) counter from worker where 400 >= salary
| counter |
|       2 |

select count(distinct salary) counter from worker where 500 >= salary
| counter |
|       3 |

the 1st query returns the minimum salary because the number of distinct salaries that are less or equal than 300 is 1, and so on.
This is what your code does: it finds the minimum and not the maximum salary.
If you want the max salary you must write the code like this:
select distinct salary
from worker a
where 1 = (select COUNT(distinct salary) from worker b where b.salary >= a.salary)

If you want the 2nd highest salary you must write the code like this:
select distinct salary
from worker a
where 2 = (select COUNT(distinct salary) from worker b where b.salary >= a.salary)

See the demo.


text:
Q: Unable to clear data in ArrayAdapter by using adapterName.clear() I'm using PreferenceFragment and I want that every time I change the value of a PreferenceScreen's widget the results should be displayed according to that in the ListView. Everything is working fine except when I change the value of any PreferenceScreen's widget instead of showing me a new list in the ListView it's adding the values in that same list. Apparently, adapter.clear() is not working.
Can anyone suggest how to make it work?
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<String>,
SharedPreferences.OnSharedPreferenceChangeListener{
private static final String TAG = "MainActivity";

private static final int LOADER_INIT_KEY = 0;

EditText titleTextView;
Button searchButton;
ListView listView;

String query = "";
private ArrayList<String> authorsList = new ArrayList<>();
private ArrayList<BooksDetails> booksDetails = new ArrayList<>();
private String title = null, id = null;

private CustomAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    titleTextView = findViewById(R.id.author_textView);
    searchButton = findViewById(R.id.search);
    listView = findViewById(R.id.list_view);

    /**
     * this declaration is needed
     */
     adapter = new CustomAdapter(this, new ArrayList<BooksDetails>());

     final ListView listView = findViewById(R.id.list_view_in_main_layout);

     listView.setAdapter(adapter);

     // getting instance of SharedPreference and attaching listener to it
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    //  any change in the SharedPreference will get notified
    //  if user tweaks any settings
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);

    //  Search button
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //  getting value from textView
            query = titleTextView.getText().toString();

            Log.d(TAG, "onClick: "+query);

            //  clearing the adapter
            adapter.clear();

            //  checking the network connection
            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
            assert connectivityManager != null;
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if(networkInfo != null && networkInfo.isConnected()) {
                if(query.length() != 0) {

                    getSupportLoaderManager().initLoader(LOADER_INIT_KEY, null, MainActivity.this);
                    closeKeyboard();
                    Log.d(TAG, "onClick: ");
                }
                else
                    Toast.makeText(MainActivity.this, "Enter a title", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(MainActivity.this, "Not connected to internet", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

private void closeKeyboard(){
    //  hiding keyboard after the search
    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

    View focusedView = this.getCurrentFocus();
    if(focusedView != null) {
        try {
            assert inputMethodManager != null;

        inputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }catch (AssertionError e){
            Log.e(TAG, "closeKeyboard: Assertion error is thrown inputMethodManager is null", e);
        }
    }
}

@NonNull
@Override
public android.support.v4.content.Loader onCreateLoader(int id, @Nullable Bundle args) {

    Log.d(TAG, "onCreateLoader: ");
    //  getting the SharedPreference which contains all the values of the Preference

    //  SharedPreference for maxResults
    SharedPreferences maxResultsSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String maxResults = maxResultsSharedPreferences.getString(getString(R.string.settings_default_result_key),
            getString(R.string.settings_default_value_of_result));

    //  SharedPreference for OrderBy
    SharedPreferences orderBySharedPreference = PreferenceManager
    .getDefaultSharedPreferences(this);

    String orderByValue = orderBySharedPreference.getString(getString(R.string.settings_order_by_key),
            getString(R.string.settings_order_by_default));

    //  passing the minResults with query
    return new CustomLoader(this, query, maxResults, orderByValue);
}

@Override
public void onLoadFinished(@NonNull android.support.v4.content.Loader loader, String s) {
    Log.d(TAG, "onLoadFinished: ");

    //  clearing the adapter
    adapter.clear();

    //  after getting the raw json we are parsing it here
    try {
        JSONObject rootObject = new JSONObject(s);
        JSONArray itemsArray = rootObject.getJSONArray("items");

        for(int i = 0;i < itemsArray.length();i++){
            //  getting each object in the array itemsArray
            JSONObject booksInfo = itemsArray.getJSONObject(i);

            //  getting book id
            id = booksInfo.getString("id");

            //  getting the volumeInfo object
            JSONObject volumeInfo = booksInfo.getJSONObject("volumeInfo");

            //  getting title of the book
            title = volumeInfo.getString("title");
            //  getting the author

            JSONArray author = volumeInfo.getJSONArray("authors");

            //  getting all the members of author array
            for(int j = 0;j < author.length();j++){
                authorsList.add(author.getString(j));
            }

            if(title == null) {
                //  if no title matches
                titleTextView.setText("No title matches");
            }

            //   adding details in the ArrayList bookDetails
            booksDetails.add(new BooksDetails(id, title, authorsList.get(0)));

        }

        adapter.addAll(booksDetails);
    }
    catch(Exception e){
        Log.e(TAG, "onLoadFinished: exception in json parsing", e);
    }
}

@Override
public void onLoaderReset(@NonNull android.support.v4.content.Loader loader) {
    Log.d(TAG, "onLoaderReset: ");

    //  clearing the adapter
    adapter.clear();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.settings_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.action_settings){
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Log.d(TAG, "onSharedPreferenceChanged: ");

    if(key.equals(getString(R.string.settings_order_by_key)) || key.equals(getString(R.string.settings_default_result_key))){

        //  clearing the adapter
        adapter.clear();

        getSupportLoaderManager().restartLoader(LOADER_INIT_KEY, null, this);
    }
}

@Override
protected void onRestart() {
    super.onRestart();

    adapter.clear();
}

}

A: You need to reset you source list which you've passed to the adapter. because you placed initial code inside of onCreate method which has been called once while activity created.
Instead of
adapter = new CustomAdapter(this, new ArrayList<BooksDetails>());
try this:
CustomAdapter adapter;
List<BooksDetails> srcList;

public void onCreate() {
srcList = new ArrayList<BookDetails>();
adapter = new CustomAdapter(this, srcList);
}

and when you need to clear your adapter try this
srcList().clear();
adapter.clear();
adapter.notifyDatasetChanged();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing webforms inputs to class that isn't codebehind asp.net vb I have some data on a webform that I don't want to write to variables in the codebehind, I want it to pick up the fields in a separate class within the App_Code. I've tried Request.form and using a Post on the webform but it can't find the method for Request.form possibly because it isn't linked.  Currently the below code is pulling in the data from the codebehind but I'm having trouble running functions in a separate class as I am unable to call the data from the codebehind without passing through variables to the function. Is this even possible can you create the form as an object?
Public Sub DeclareInputFields()
    input1.CalcReference = inCalcRef.text
    input1.DOL = If(String.IsNullOrEmpty(indol.text), Nothing,    DateTime.Parse(indol.text))
    input1.APP = If(String.IsNullOrEmpty(inAPP.text), Nothing, Decimal.Parse(inAPP.text))
    input1.CPD = If(String.IsNullOrEmpty(inCPD.text), Nothing, Decimal.Parse(inCPD.text))
End Sub

A: A class defined in a file in App_Code still has to be called from somewhere.  You can instantiate the class in your code behind or use one of the other types of files in ASP.NET.
The request has to go somewhere.  Some other options to look at
An ashx file if your call is something like an AJAX call from JavaScript.
A handler, if you want to do something with the form in addition to the handling of the request.  Look at IHttpModule (which you will also need to register in web.config to do additional handling).

A: Here's a "shell" of how a VB class in App_Code might define functions to take the Form collection, the Request object, or the Controls collection:
Imports Microsoft.VisualBasic
Imports System.Collections.Specialized
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Public Class VBDemoClass

   Sub DemoMethod(MyCollection As NameValueCollection)
      ' Do stuff here
   End Sub

   Sub DemoMethod(MyRequest As HttpRequest)
      ' Do stuff here
   End Sub

   Sub DemoMethod(MyControls As ControlCollection)
      ' Do stuff here
   End Sub
End Class

In your codebehind, just instantiate the VBDemoClass, then call one of the functions as desired...you could also skip the instantiation if you made the methods static, but that's an implementation detail I'll leave to your purposes.
In your web page codebehind, instantiate your class and call your method with one of the objects already available to you as the codebehind fires:
Public Class Page1

    Sub Page_load(ByVal Object as Sender, ByVal e as EventArgs)
       Dim foo as New VBDemoClass
       Foo.DemoMethod(Request.Form)
       ' or
       Foo.DemoMethod(Request)
       ' or
       Foo.DemoMethod(Page.ControlsCollection)
    End Sub
End Class


text:
Q: Does Mozilla Fennec supports Addons in Mobile Platform? Looking if Fennec supports Addons compatibility in Mobile Platforsm like iOs for iphone, Android or Windows.
Also looking forward for guidelines to develop extensions development to use it in Fennec for mobile platforms.

A: Yes, Fennec supports add-ons. In general, you develop you add-on just like for the desktop Firefox: How do I write a Firefox Addon?
There are currently two Fennec variants around. The "old" one uses a XUL-based user interface and multiple processes. Here is a good entry point if you are looking for documentation.
The "new" one uses a native Android user interface - it will soon replace the XUL-based variant on the mobile phones, tablets should follow a bit later. It uses a single process like the desktop Firefox. There is very little documentation at the moment, it's mostly this text.


text:
Q: MySql select query in Entity inheritence model, how? Actually i m creating a kind of social network for learning, where user can share photo and links, i m using mysql as datastore, both types of post(later i can add more types as well ex- videos etc) can be liked and can have comments, so i created a parent entity table,
Table : Entity
  id : 'Primary key'

and
Table : Links
  id : 'Primary key'
  entity_id : 'FK'

now when i create newsfeed, how i will be able to fetch links and photos by entity table ?
mean
Select * from Entity

will just give entity ids, but how to know is that link or photo or which table to query next ??
Will I have to add a Type column to Entity table? Or another solution join etc? I don't know about them, so just give me that term i will check that on internet, thanks


text:
Q: Error in streaming dynamic resource.: WELD-001303: No active contexts for scope type ViewScoped when trying to display PDF with PrimeFaces I'm trying to display a PDF through Primefaces. The PDF belongs to some item that the user picks from a list, and is supposed to be displayed on the detail page corresponding to that item. The item gets passed from the list bean to the detail bean via flash memory.
I'm providing the PDF as a StreamedContent through a @ViewScoped bean:
@Named
@ViewScoped
public class ItemDetailPageBean implements Serializable {

    private StreamedContent pdf;

    @PostConstruct
    public void init() {

        detailItem = (Item) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("detailItem");

        if (detailAntrag != null) {
            pdf = loadPdf(detailItem.getPdf());
        }
    }

    public StreamedContent loadPdf(byte[] byteArray) {
        if (byteArray != null) {
            ByteArrayInputStream stream = new ByteArrayInputStream(byteArray);
            stream.mark(0);
            return new DefaultStreamedContent(stream, "application/pdf");
        } else {
        return null;
        }
    }

    public StreamedContent getPdf() {
        if (FacesContext.getCurrentInstance().getRenderResponse()) {
            return new DefaultStreamedContent();
        } else {
            if (pdf != null)
            {
                try {
                    pdf.getStream().reset();
                } catch (IOException e) {
                    logger.debug("Error while resetting PDF stream: ", e);
                }
            }
            return pdf;
        }
     }

    public void setPdf(StreamedContent pdf) {
        this.pdf = pdf;
    }
}

Marking and resetting the stream happens since I've read that it's a problem if the stream gets read from multiple times.
However, when I'm trying to display the PDF through itemDetailPageBean.pdf I'm getting an error:
Error in streaming dynamic resource.:
org.jboss.weld.contexts.ContextNotActiveException:
WELD-001303: No active contexts for scope type javax.faces.view.ViewScoped

I tried to provide the PDF through a @ApplicationScoped bean, but the problem stands that this bean needs to know which PDF to use. And when I'm trying to pass the PDF, or even the ID of the corresponding item, from my ViewScoped bean, I'm getting that same error.
I've read about how there are different requests for the page itself and for the PDF, and how there are two different ViewScoped beans - but my understanding ends there. Would be very grateful if you could clear things up a bit! I'm still a bit confused by faces request lifecycles tbh.
Thanks in advance!


text:
Q: Column with the same values across rows as a MultiIndex Pandas I have pandas df like below:

Id
Period
Value1
Value2

1
3
20
60

1
4
30
70

2
3
40
80

2
4
50
90

How can I use Period as additional column, like this: (to have Period 3, 4 as separate columns and under each column with periods I have subcolumns Value1 and Value2)?

A: You can try pivot then swaplevel and sort_index
out = (df.pivot(index='Id', columns='Period', values=['Value1', 'Value2'])
       .swaplevel(0,1,1)
       .sort_index(axis=1))

print(out)

Period      3             4
       Value1 Value2 Value1 Value2
Id
1          20     60     30     70
2          40     80     50     90


text:
Q: Legend for geom_text with variable font family I'd like to have geom_text() labels take on a font family according to a variable.
As per the example on the ggplot2 docs (scroll down to the bottom), I have done this (same as in ggplot docs example):
library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))
p + geom_text(aes(family=c("serif", "mono")[am+1]))

Yielding:

That's all fine and dandy – but how do I get the font family in the legend?

A: Its not pretty: You can change the font family of the legend labels at the grob level (i dont know another way, but i expect there is).
First add colour to the aesthetic so that a legend is automatically produced, then set the colours manually, with scale_colour_manual to keep them as before. Then tweak the legend details, to change the labels and fonts in the key.
library(ggplot2)
library(grid)

p <- ggplot(mtcars, aes(x=wt, y=mpg, colour=factor(am), label=rownames(mtcars))) +
         geom_text(aes(family=c("serif", "mono")[am+1])) +
         scale_colour_manual(values=c('0'= "#000000FF", '1'="#000000FF"),
                             name="am") +
         theme(legend.text=element_text(size=16),
               legend.key.width=unit(2, "cm"))

g <- ggplotGrob(p)

# change labels and fonts
g$grobs[[8]]$grobs[[1]]$grobs[[4]]$label <- "mono"
g$grobs[[8]]$grobs[[1]]$grobs[[4]]$gp$fontfamily <- "mono"
g$grobs[[8]]$grobs[[1]]$grobs[[6]]$label <- "serif"
g$grobs[[8]]$grobs[[1]]$grobs[[6]]$gp$fontfamily <- "serif"

grid.newpage()
grid.draw(g)


text:
Q: How to post data to mySQL database through PHP form? I am new to PHP and I am following a tutorial that gets information from a mySQL database table by the row and outputs a form to create new table rows. For some reason I can't figure out what is wrong with my code? The page is blank when I refresh the page and I have been staring at this code forever. Does anybody know what I am doing wrong? The database connection is fine as it is used on another page and i have checked.
The mySQL database I have is extremely simple, with 1 table called users that has 5 columns (ID, username, firstName, lastName, title) with the ID being a unique field.
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
    mysql_select_db($db_database, $db_server)
    or die("Unable to select database: " . mysql_error());

if (isset($_POST['delete']) && isset($_POST['ID']))
{
    $id = get_post('ID');
    $query = "DELETE FROM users WHERE ID='$id'";
    if (!mysql_query($query, $db_server))
    echo "DELETE failed: $query
" .
    mysql_error() . "

";
}

if (isset($_POST['ID']) &&
    isset($_POST['username']) &&
    isset($_POST['firstName']) &&
    isset($_POST['lastName']) &&
    isset($_POST['title']))
{
    $id = get_post('ID');
    $username = get_post('username');
    $firstName = get_post('firstName');
    $lastName = get_post('lastName');
    $title = get_post('title');
    $query = "INSERT INTO users VALUES" .
    "('$id', '$username', '$firstName', '$lastName', '$title')";

    if (!mysql_query($query, $db_server))
        echo "INSERT failed: $query
" .
        mysql_error() . "

";
}

echo <<<_END
<form action="sqltest.php" method="post">

ID <input type="text" name="ID">
username <input type="text" name="username">
firstName <input type="text" name="firstName">
lastName <input type="text" name="lastName">
title <input type="text" name="title">
<input type="submit" value="ADD RECORD">

</form>
_END;

$query = "SELECT * FROM users";

$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());
    $rows = mysql_num_rows($result);
    for ($j = 0 ; $j < $rows ; ++$j)
{
    $row = mysql_fetch_row($result);
    echo <<<_END

    ID $row[0]
    username $row[1]
    firstName $row[2]
    lastName $row[3]
    title $row[4]

    <form action="sqltest.php" method="post">
    <input type="hidden" name="delete" value="yes">
    <input type="hidden" name="title" value="$row[4]">
    <input type="submit" value="DELETE RECORD"></form>
    _END;
}

mysql_close($db_server);
function get_post($var)
{
    return mysql_real_escape_string($_POST[$var]);
}

Any help would be super awesome!

A: You are trying to retrieve variables with the wrong way.
Example
$username = get_post('username');

should be
$username = $_POST['username'];

You should do the same with the same code that you are trying to retrieve post variables.
And the query to insert values should be
$query = "INSERT INTO users VALUES('".$id."', '".$username."', '".$firstName."', '".$lastName."', '".$title."')";


text:
Q: How do the Averages Work? I am trying to figure out the average items sold per customer for the year 2019
I have multiple customers per day, who each have a random number of items. Sometimes a customer makes more than one purchase a day - about 6% of the time. In that case - all sales for that customer are considered to be 1 sale.
I have calculated this in 2 fashions - The 1st:

*

*Total # Items Sold ( 27,427,131 ) / Total # customers ( 6,556,133 ) = 4.18

*AVG(Items Sold Per Customer who make a purchase Per Day) = 4.21

The second way I did using an SQL function on an MS SQL Server
The first way I did by getting the total # from the same SQL Database
With > 1 million customers - I can't replicate the 2nd method in Excel - and so I can't step it through and confirm the data.
I don't quite understand why the 2 avgs are different - but I suspected they would be and would like to use the # I think is more accurate - the 2nd one: 4.21
My boss has asked me to provide the formula used, and wants me to "prove" my answer.  Not an unreasonable request, but I'm a little lost in explaining why I am getting 2 different averages.  How do I explain this?
OR - and this is a real possibility - The numbers SHOULD be exactly the same and I am doing something wrong in one of my steps to calculate this.

A: You're running into weighted averages on unequal sample sizes. The second formula is incorrect.
Suppose there's only the following two days:

*

*2 items sold, 1 customer

*2 items sold, 2 customers

It's obvious the first formula generates the correct result ($4/3$, 4 items/3 customers), the second is $\mathrm{AVG}(2,1)$ which is not $4/3$.
See Simpson's paradox for how bad it can get.


text:
Q: LeviCivita::shdw when I am loading FeynCalc I have downloaded FeynArts-3.9 and put it in Applications already. Then, I downloaded FeynCalc using Import[].
After that, I used << FeynArts` to load FeynArts-3.9 package and then << HighEnergyPhysics`FeynCalc` to load FeynCalc. There is a pop-up asked me to merge FeynCalc with FeynArts-3.9 (I think) and I type "yes". I got a lot of red messages, hence I close the Mathematica and start it again.
This time I use only << HighEnergyPhysics`FeynCalc`. However, I got the red message

"LeviCivita::shdw: Symbol LeviCivita appears in multiple contexts {HighEnergyPhysics`FeynArts`, HighEnergyPhysics`FeynCalc`LeviCivita`}; definitions in context HighEnergyPhysics`FeynArts` may shadow or be shadowed by other definitions."

What should I do?
Thank you.

A:
What should I do?

Read the Wiki and install the latest version of FeynCalc
https://github.com/FeynCalc/feyncalc/wiki/Installation#st_automatic_installation
HighEnergyPhysics`FeynCalc is version 8.2 that is 4 years old ...


text:
Q: Is there a way to programatically trigger google voice to text functionality available via android keyboard? I'm working on a React Native app and want to programmatically trigger google speech to text on click of a button. Is there a way to do it? I need a solution for both Android and ioS.
Note: Tried https://github.com/react-native-community/voice, but it doesn't work.


text:
Q: Python: Static variable (or, difference between class.some_var and inst.some_var) I have simple class written
class Test:

    stat = 0

    def __init__(self):
        self.inst = 10

    def printa(self):
        print Test.stat
        print self.inst

Now I've created two object of this class
$ a = Test()
$ b = Test()

When I say a.printa() or b.printa() it outputs 0 10 which is understandable.
But when I say
$ a.stat = 2
$ print a.stat

It'll output
2

But when I say a.printa()
It'll output
1
10

What's the difference between saying objInstance.staticVar and ClassName.staticVar?? What it is doing internally?

A: Unless you do something to change how attribute assignment works (with __setattr__ or descriptors), assigning to some_object.some_attribute always assigns to an instance attribute, even if there was already a class attribute with that name.
Thus, when you do
a = Test()

a.stat is the class attribute. But after you do
a.stat = 2

a.stat now refers to the instance attribute. The class attribute is unchanged.

A: By
1
10

I assume you mean
0
10

since the class variable stat was never changed.
To answer your question, it does this because you added an instance member variable stat to the a object. Your objInstance.staticVar isn't a static variable at all, it's that new variable you added.


text:
Q: Unexpected token error on I am getting an error on my script below.  It says Uncaught SyntaxError: Unexpected token :
I am not sure why that is or what I am missing
        <script> //[CDATA[
if (%%GLOBAL_Availability%% == "") {'error is here
    document.getElementById("ShopButton").style.display = "block";
    document.querySelector("#ShopButton").addEventListener("click",function(){
      window.location.href='%%GLOBAL_Availability%%';
    },false);
}
    //]]> </script>

Here is how it shows on Chrome:

Any help is appreciated

A: The error is because you haven't put %%GLOBAL_Availability%% inside quotation marks.
if ('%%GLOBAL_Availability%%' == "") {
    document.getElementById("ShopButton").style.display = "block";
    document.querySelector("#ShopButton").addEventListener("click",function(){
      window.location.href='%%GLOBAL_Availability%%';
    },false);
}

I am not sure what you mean by %%GLOBAL_Availability%%. It is not a valid variable name nor a valid url.

A variable name must start with $, _, or any character in the Unicode categories "Uppercase letter (Lu)", "Lowercase letter (Ll)", "Titlecase letter (Lt)", "Modifier letter (Lm)", "Other letter (Lo)", or "Letter number (Nl)".
The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories "Non-spacing mark (Mn)", "Spacing combining mark (Mc)", "Decimal digit number (Nd)", or "Connector punctuation (Pc)".


text:
Q: PHP change array values to create new array this way how i get array from db:
$sql = "SELECT * FROM table_name";
$query = mysqli_query($conn, $sql);

$db_array = array();
// start fetch for words
if (mysqli_num_rows($query) > 0){
    while ($row = mysqli_fetch_assoc($query)){
        $db_array[] = $row;
    }
}

My array looked like this:
Array
(
    [cat cute] => animal#cute animal
    [cat women] => film
)

How to add '{' and '}' to all values?
I wish i can get new array like this:
Array
(
    [cat cute] => {animal#cute animal}
    [cat women] => {film}
)

It's hard for me, i am new in php development.

A: Try this,
$arr =  array
(
    'cat cute' => 'animal#cute animal',
    'cat women' => 'film'
);
array_walk($arr, function(&$item){
   $item = '{'.$item.'}';
});
print_r($arr);

Here is the link for array_walk()

A: Since you want a new array, try this:
<?php
array_map(function($value)
{
    return '{' . $value . '}';
}, $arr);

array_walk() in rahul_m's answer modifies your array, while array_map() creates a new one.


text:
Q: Pass variable from a form to other when closing I am developing an app which requires to close and open different winforms over time. I faced a problem, how can I pass a variable, in this case a SerialPort that has been opened in an initial form?
Forms are opened from Program.cs
Application.Run(new Auth());
Application.Run(new Main());

Auth.cs code includes this:
SerialPort RCU = new SerialPort();
RCU.PortName = textbox.Text; //Port name is get from user input

And I want to use this port in the other form "Main".
Is there any possibility to do this?
Thanks

A: Just ask for a Auth object in your Main constructor and then initialize them in that order:
Auth auth = new Auth();
Main main = new Main(auth);
Application.Run(auth);
Application.Run(main);

Then in Main you can save that object and get the property once set:
public Main(Auth auth)
{
  AuthWindow = auth;
}

public Auth AuthWindow {get; set;}

// later..
AuthWindow.RCU

Note though, two Application.Run calls isn't the way you want to go, just create a new Auth form and show it the moment the main form is loaded.


text:
Q: grok, parse iptables remote log I am new with grok and haven't work with grok before, but now, I need a help.
I have remote log message from remote system which contains iptables rules.
May 11 09:37:05 zabbix kernel: [1607613.428683] FW_F_IN_DROP: IN=ens18 OUT= MAC=3a:e9:5f:c7:41:78:d0:07:ca:8c:10:01:08:00 SRC=104.16.55.12 DST=9.0.20.11 LEN=40 TOS=0x00 PREC=0x00 TTL=243 ID=36679 PROTO=TCP SPT=58399 DPT=8427 WINDOW=1024 RES=0x00 SYN URGP=0
I found a rule:
((%{SYSLOGTIMESTAMP:nf_timestamp})\s*(%{HOSTNAME:nf_host})\s*kernel\S+\s*(%{WORD:nf_action})?.*IN=(%{USERNAME:nf_in_interface})?.*OUT=(%{USERNAME:nf_out_interface})?.*MAC=(%{COMMONMAC:nf_dst_mac}):(%{COMMONMAC:nf_src_mac})?.*SRC=(%{IPV4:nf_src_ip}).*DST=(%{IPV4:nf_dst_ip}).*PROTO=(%{WORD:nf_protocol}).?*SPT=(%{INT:nf_src_port}?.*DPT=%{INT:nf_dst_port}?.*))
I like this rule, but output of this rule doesn't contain a string from iptables:
-j LOG --log-prefix "my log prefix"
which in this case equal to: FW_F_IN_DROP
also, what is the best solution to parse: [1607613.428683], looks like this is a kernel pid, but included also point in the middle
Can someone help me to modify this rule to include also log prefix information.
Thank you.

A: You grab an additional word in your pattern with %{WORD:log_prefix}:
The modified filter would look like this:
((%{SYSLOGTIMESTAMP:nf_timestamp})\s*(%{HOSTNAME:nf_host})\s*kernel\S+\s*(%{WORD:nf_action})?.*%{WORD:log_prefix}: IN=(%{USERNAME:nf_in_interface})?.*OUT=(%{USERNAME:nf_out_interface})?.*MAC=(%{COMMONMAC:nf_dst_mac}):(%{COMMONMAC:nf_src_mac})?.*SRC=(%{IPV4:nf_src_ip}).*DST=(%{IPV4:nf_dst_ip}).*PROTO=(%{WORD:nf_protocol}).?*SPT=(%{INT:nf_src_port}?.*DPT=%{INT:nf_dst_port}?.*))

The parsing of your log will add the following field:
"log_prefix": "FW_F_IN_DROP"


text:
Q: How to hyphenate "corned beef filled"? "Tuna-filled" is hyphenated correctly, right?
If we were to fill something with "corned beef", how would we write "corned beef filled"? Where would the hyphen go?

A: The Chicago Manual of Style would recommend corned beef–filled, with an en dash, not a hyphen. Section 6.80 of the 17th edition:

The en dash can be used in place of a hyphen in a compound adjective when one of its elements consists of an open compound or when both elements consist of hyphenated compounds (see 7.82). Whereas a hyphen joins exactly two words, the en dash is intended to signal a link across more than two. Because this editorial nicety will certainly go unnoticed by the majority of readers, it should be used sparingly, when a more elegant solution is unavailable.

CMOS provides country music–influenced lyrics as an example but also suggests the rephrasing lyrics influenced by country music, because "the relationship [...] depends to some small degree on an en dash that many readers will perceive as a hyphen connecting music and influenced."


text:
Q: GeoServer CSS categorized marks with different size I am doing categorized marks with GeoServer. The color is fine. I use same template of this question: geoserver css categorized marks  but I can't figure out how to change the size of my points.
This is what I've tried but my points displaying with the same size
* {
  mark: symbol(circle);
}

:mark [total < 500000]{
  mark-size: 2px;
  fill: yellow;
  stroke: yellow;

}
:mark [total >= 500000] [total < 1000000]{
  mark-size: 5px;
  fill: blue;
  stroke: blue;
}

A: You are mixing styles that apply to the mark automatically (mark-size) and style items that must be applied to the mark (fill, stroke). The second type must be inside a :mark block but the first don't. So your style should look something like:
* {
  mark: symbol(circle);

}

[PERSONS < 5e6]{
  mark-size: 20px;
  :mark{
    fill: yellow;
    stroke: yellow;
  }
}
[PERSONS >= 5e6] {
  mark-size: 10px;
  :mark{
    fill: blue;
    stroke: blue;
  }
}

giving this map of US States:


text:
Q: How to have 2 semaphores acquired by one thread? (Only simple counting semaphores) I am working on a typical homework about semaphores in Java/Linux. There is a table of coffee, milk and sugar and there are different types of participants who are looking for specific combination of those materials and of course waiters who are responsible for refilling not-full-containers.
Imagine a participant wants coffee & milk and he should wait (get blocked), for instance, if coffee is available but not milk. Is there any way that I can block his thread, using (acquiring) 2 semaphores (s_anyMilk, s_anyCoffee) simultaneously?
Without having that, I only have this stupid dead-end in mind:
if(Main.s_anyCoffee.availablePermits()!=0 &&
       Main.s_anyMilk.availablePermits()!=0)
    {
        Main.s_anyCoffee.acquire();
        Main.s_anyMilk.acquire();
        //do something here
        //Waiters will come later in their threads and refill containers
    }
else
{
//NO IDEA HERE!
}


text:
Q: Sending multiple data with jquery Ajax in php I'm unable to understand these answers Question1 Question2 Question3 so posting my question.
I'm sending an Ajax request in PHP file:
$(document).ready(function(){
    $(document).on('click','.show_more',function(){
        var ID = 10;
        var USERID =1;
        $('.show_more').hide();
        $('.loding').show();
        $.ajax({
            type:'POST',
            url:'/ajaxload.php',
            data:'id='+ID & 'user_id=' + USERID,
            success:function(html){
                $('#show_more_main'+ID).remove();
                $('.post_list').append(html);
            }
        });
    });
});

while receiving Ajax URL
id is received successfully but user_id is not getting received
<?php
if(isset($_POST["id"]) && ($_POST["user_id"]) && !empty($_POST["id"])){
    echo $_POST["id"];
    echo $_POST["user_id"];
}
?>

A: Replace :
data:'id='+ID & 'user_id=' + USERID,

with:
data: {id:ID, user_id:USERID}

so your code will look like this :
$(document).ready(function(){
    $(document).on('click','.show_more',function(){
        var ID = 10;
        var USERID =1;
        $('.show_more').hide();
        $('.loding').show();
        $.ajax({
            type:'POST',
            url:'/ajaxload.php',
            data: {id:ID, user_id:USERID},
            success:function(html){
                $('#show_more_main'+ID).remove();
                $('.post_list').append(html);
            }
        });
    });
});

A: pass the data as javascript objects
data:{
  id:ID,
  user_id:USERID
}


text:
Q: SOQL query- for querying two object tables I have used the following query in my custom controller, but apex compiler is not allowing this. How can I recreate this query?

Error: Compile Error: expecting a colon, found EventSchedule__c.Name

Integer capacity= [
    SELECT EventSchedule__c.Capacity__c
    FROM EventSchedule__c, Ticket__c
    WHERE Ticket__c.EventSchedule__c = EventSchedule__c.Name
    AND Ticket__c.Date_Time__c=:listStrings.get(i)
    AND Ticket__c.Events__c=:listStrings2.get(j)
];

A: SOQL fieldExpression Syntax and SOSL WHERE conditionExpression terms can only have this form:
fieldName comparisonOperator value

and value has to be:

A value used to compare with the value in fieldName. You must supply a
  value whose data type matches the field type of the specified field.
  You must supply a native value—other field names or calculations are
  not permitted. If quotes are required (for example, they are not for
  dates and numbers), use single quotes. Double quotes result in an
  error.

This means you cannot compare two fields: you can only compare a field with a value that is a constant or a bound external value (using the :).
So you will have to change your approach and inject the name via an Apex bind variable.

A: Between objects EventSchedule__c and Ticket__c needs a Lookup relationship or Master-Detail relationship,as Ticket__c.EventSchedule__c(Lookup field) = EventSchedule__c.Id.
Now you can run apex like the following code:
List<Ticket__c> tickets = [
  SELECT EventSchedule__r.Capacity__c
  FROM Ticket__c
  WHERE Ticket__c.Date_Time__c=:listStrings.get(i)
  AND Ticket__c.Events__c=:listStrings2.get(j)
  LIMIT 1
];
if(!tickets.isEmpty()) {
    Integer capacity = (Integer)tickets[0].EventSchedule__r.Capacity__c;
}


text:
Q: Convert from ER to Relational Database - Mapping Weak entity types I am trying to map the weak entity CatalogueEntry into a relational schema, and I am unsure which of the entities are the owner of this weak entity type. So, I don't know what the primary key of the relation in the relational schema is.
Anyone have any ideas? I have added an image below, thanks.

A: What is a Catalogue?  Why doesn't catalogue appear on the diagram?
Sorry to ask stupid questions, but you learn to do that when you do data analysis.
It's useful to understand the data pretty well at the conceptal (ER) level, before switching to the relational level.

A: From the figure it shows that the weak entity CatelogueEntry depends on the Album strong entity by an identifying relationship (HasEntry).
For each catelogueEntry there must be an albumid. So here there are two tables. One is for Album and another table is for catelogueEntry. The catelogueEntry must contain a foreign key from album entry.


text:
Q: Dynamically grow UIView containing a non-scrollable vertical UICollectionView I am looking for a way to build a UICollectionView with a vertical flow layout that is embedded in a UIView. the UIView acts as the datasource/delegate for the containing collectionview. The behavior I am looking for is that the collectionview itself has its scroll disabled and the containing UIView grows as you add more rows to the collectionview. How can this be achieved?

A: I think you can achieve this by following steps,

*

*Embed the UIView which you currently have into a UIScrollView(Make its constraint respective to its super view).

*Then add height constraint to your UIView and create an outlet for that height constraint in our view controller, so as of now when the height of UIView gets increased the scrollView content size will also get increased.

*Then place the UICollectionView inside the UIView and make its top, bottom, left & right constraints to UIView.

*Now increase the height constraint constant value based on the number of collection view cells in the collection view.

I hope this will work for your scenario.
But if in case you are free to explain why you need to achieve this kind of behaviour it would be nice, because I cannot able to figure out the need for it.

A: This kind of scenario could be achieved. Here is rule of the thumb:
You should not specify height of you view, that will be contains unscrollable collection, pinned to it, and it should be embedded in UIScrollView using equals width, and pinned to all sides with margin. Auto layout makes things work.
Otherwise, is there any important reason to disable scrolling and make UIView delegate / data source for collection?


text:
Q: integral of spectral measure I have the following question: let $(X,\mathcal B,\mu)$ be a finite measure space and consider the operator $T_{\varphi} \colon L^2(X,\mu)\to L^2(X,\mu)$ given by $Tf(x)=\varphi(x)f(x)$, where $\varphi \in L^{\infty}(X,\mathcal{S},\mu)$. Consider the canonical spectral measure E induced by T. How we defined is as follows if $S \in B_{\sigma(T_{\varphi})}(T)$ then we define $E(S) = T_{1_{\varphi^{-1}}(S)}$ recall here $1_{\varphi^{-1}}(S)$ is the characteristic function.
I want to verify that $T_{\varphi} = \int_{\sigma(T)} z dE(z)$.
My attempt:
Suppose we have measurable partition $M_1,\ldots,M_n$ of $B_{\sigma(T_{\varphi})}(T)$ such that $|z_1 - z_2| < \epsilon$ for all $z_1,z_2 \in S_i$:
$$\|T_{\varphi} - \Sigma z_i E(M_i)\|$$
I am not sure why this is less than $\epsilon$. This is where I am stuck.

A: Note that $\sigma(T_\varphi)=\operatorname{ess ran}\varphi$. Given $x\in X$, there exists $j$ with  with $\varphi(x)\in M_j$. Then $|\varphi(x)-z_j|<\varepsilon$. Thus $x\in\varphi^{-1}(M_j)$ and then
$$
|\varphi(x)-\sum_kz_k\, 1_{\varphi^{-1}(M_k)}(x)|=|\varphi(x)-z_j|<\varepsilon.
$$
So
\begin{align}
\|T_\varphi f-\sum_kz_k\, 1_{\varphi^{-1}(M_k)}\,f\|_2^2&=\int_{\sigma(T_\varphi)}|T_\varphi(x) f(x)-\sum_kz_k\, 1_{\varphi^{-1}(M_k)}(x)\,f(x)|^2\,d\mu\\[0.3cm]
&=\int_{\sigma(T_\varphi)}|T_\varphi(x) -\sum_kz_k\, 1_{\varphi^{-1}(M_k)}(x)|^2\,|f(x)|^2\,d\mu\\[0.3cm]
&\leq\varepsilon \|f\|_2^2.
\end{align}
As this works for all $f\in L^2$, we get that
$$
\|T_\varphi -\sum_kz_k\, 1_{\varphi^{-1}(M_k)}\|<\varepsilon.
$$


text:
Q: Is there any row limit for excel using BIFF? I have a code to export my data grid to excell using BIFF4. The problem is it cant accept rows beyond 65536. I asuume it is because the row index is word and it is of 2 bytes. Is there any way i could write more than the available row count? any workaround is possible? any help will be appreciated.

A: If you have to use BIFF, the best thing to do is split the data into multiple sheets.

A: In Excel 97-2003, the row limit is 65535 per sheet. It should be the default BIFF row limit.


text:
Q: numpy, recarray: Methods to convert a list of dict's to a np.recarray? What methods are available to convert a loosely coupled list of dictionaries to a np.recarray (where import numpy as np)?
I looked around here on SO, but namely saw things where the data was already well-structured.
I've prototyped a simple method here: dict_list_to_recarray.py
Thank you!

A: @DSM beat me to it when I am preparing a full answer. But yes, it is sort-of already there. Only that you have to use Pandas (imported as pd) to convert it to a DataFrame and then convert it to a recarray
In [8]:

print pd.DataFrame(raw)
   age             extra has_money   name
0   45               NaN      True  Billy
1   32  Something wicked     False  Tommy
2   31               NaN      True     Al
In [9]:

pd.DataFrame(raw).to_records()
Out[9]:
rec.array([(0, 45, nan, True, 'Billy'),
       (1, 32, 'Something wicked', False, 'Tommy'),
       (2, 31, nan, True, 'Al')],
      dtype=[('index', '<i8'), ('age', '<i8'), ('extra', 'O'), ('has_money', '?'), ('name', 'O')])


text:
Q: Complicated PHP Error : Trying to escape an array I'm trying to mysqli escape an array mysqli_real_escape_string function.
But it won't work because it expects a string.
So I use this :
$items = array_map('mysqli_real_escape_string', $link, $_POST['items']);

where $link is my database connection and $_POST['items'] is the array.
But I get this error :
Warning: array_map(): Argument #2 should be an array

So I changed it to :
$items = array_map('mysqli_real_escape_string', $_POST['items']);

where the 2nd argument is an array and then I get this message :
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given

So I changed it again to :
$items = array_map('mysqli_real_escape_string', $_POST['items'], $link);

but now I got this :
Warning: array_map(): Argument #3 should be an array

After some research, I tried this codes :
$items = array_map('mysqli_real_escape_string', $_POST['items'] [,$link]);
$items = array_map('mysqli_real_escape_string($link)', $_POST['items']);

but none of the worked.
Any help is appriciated.
Thanks.
EDIT :
I've tried this :
function escape_array($array){
    global $link;
    mysqli_real_escape_string($link, $array);
    return;
}

$items = array_map('escape_array', $_POST['items']);
echo $items;

which should call the mysqli_real_escape_string with the connection but I get this error instead :
( ! ) Notice: Array to string conversion in D:\wamp64\www\sellerpanel\test.php on line 21
Call Stack
#   Time    Memory  Function    Location
1   0.0007  370968  {main}( )   ...\test.php:0
Array

A: You can do it with an anonymous function that imports the $link variable.
$items = array_map(function($x) use ($link) {
    return mysqli_real_escape_string($link, $x);
}, $_POST['items']);

However, you really shouldn't be using mysqli_real_escape_string in the first place. Use a prepared statement and mysqli_stmt_bind_param().


text:
Q: TinyMVC Model / Plugin how to implement? recently i started working with TinyMVC wrote a simple menu model and i have few questions for those who are using it .. or used before.
1. For the following code should i keep it as Model or as a Plugin?
2. How should i implement it in the view and use it on every page that is required without breaking the ideea of mvc and without rewriting again and again for each controller?
3. Any improvements to the code?
4. Need the mysql tables ?
Code Here:
<?php
class Menu_Model extends TinyMVC_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    public function listMenu()
    {
        return $this->db->query_all("SELECT * FROM menu_links WHERE is_deleted = 0 ORDER BY position");
    }

    public function listCategorys($menuLinkId)
    {
        return $this->db->query_all("SELECT * FROM menu_subcategorys WHERE menuLinkId = ? AND is_deleted = 0 ORDER BY position", array($menuLinkId));
    }

    public function buildMenu()
    {
        $this->listMenu = $this->listMenu();
        foreach($this->listMenu as $this->listMenuKey => $this->listMenuValue)
        {
            $this->listCategorys = $this->listCategorys($this->listMenuValue['menuLinkId']);
            if(!empty($this->listCategorys))
                $this->listMenu[$this->listMenuKey]['child'] = $this->listCategorys;
        }

        return $this->listMenu;
    }
}


text:
Q: Uniform convergence on compact sets and limits at infinity Suppose that we have a sequence of continuous functions $(f_n)_{n \in \mathbb{N}}$,
$f_n: \mathbb{R} \rightarrow \mathbb{R}$,
which converges uniformly on compact sets to a function $f$, and that we have moreover that all that limits $a_n:=\lim_{x \rightarrow \infty} f_n(x)$, as well as $a:= \lim_{x \rightarrow \infty} f$ exist. Can we necessarily conclude that $\lim_{n \rightarrow \infty} a_n=a$?

A: No. Consider a sequence of function $f_n$ defined as follows: $f_n$ is $1$ on the interval $[-n,n]$, it is zero outside $[-n-1,n+1]$ and continuous on $[-n-1,-n]\cup [n,n+1]$.
For example $$f_n(x)=\left\{\begin{array}{ll} 1 & \text{ for } |x| < n\\
0 & \text{ for } |x|>n+1\\
-x+n+1 &\text{ for } n\leq x\leq n+1\\
x+n+1 &\text{ for } -n-1<x<-n  \end{array}\right.$$
The functions $f_n$ converge to the constant function $1$ on compact sets. Buth with your terminology we have $a_n=0$ forall $n$ and $a=1$.


text:
Q: check for time difference in javascript I have an array of times in the format "2021-02-25T12:30:00" and I need to put them into a new array only if the day and time is at least 24 hours ahead. I tried this code to check for the condition, but there is some error.

date2 = "2021-02-26T12:30:00"

function getFormattedDate() {
  var date = new Date();
  var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "T" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  return str;
}

if ((Math.abs(new Date(date2.slice(-8)) - new Date(getFormattedDate().slice(-8))) / 36e5) >= 24) {
  console.log("Enough time")
} else {
  console.log("Not enough time")
}
console.log(date2.slice(-8))

Can someone see the error?

A: You can try something like this
const hrs24 = 1000 * 60 * 60 * 24; // 24 hrs in ms
const date2 = "2021-02-26T12:30:00";

if (new Date(date2).getTime() - Date.now() >= hrs24)
    console.log("Enough time");
else
    console.log("Not enough time");


text:
Q: working with php and redis I am new to redis and predis. I want to create a simple sign up form and want to send data to user email id. I have written the script for sign up and email sending. Now I want to make a queue in which i want to put both of the jobs. and as the user click on submit then processor should not wait for sending email. sending email should be put in a queue. and should be processed in background. please guys can anyone give me a reference of such script in php using redis.

A: What you can do is, push the data to a redis list and pick data from the worker which is polling the list for any data and then send it by email.
Steps:
Make a new predis client $redis = new Predis\Client("parameter");
A predis list $redis->lpush(listname, "Data");
and finally a worker(Cron) which is taking data from the same list
$redis->rpop(listname, variable);

Other work around way is to use pub/sub of redis.
Try redis here and documentation- redis commands
Predis examples. In examples folder.


text:
Q: How can i get any database structure into xml using one sql query? please any body knows how can i get my database structure as xml
i have database : exdb
i have table    : extbl1
i have column   : excol1
i have column   : excol2
i have column   : excol3
& have column   : excol4
.... etc
how can i get the following structure
<DataBase DataBaseName="exdb">

  <Column ColumnName="excol1"/>
  <Column ColumnName="excol2"/>
  <Column ColumnName="excol3"/>
  <Column ColumnName="excol4"/>

  <Column ColumnName="excol1"/>
  <Column ColumnName="excol2"/>
  <Column ColumnName="excol3"/>
  <Column ColumnName="excol4"/>

</DataBase>

A: Using for xml and subqueries it is pretty simple:
select
'exdb' [@DataBaseName],

(select t.table_name [@TableName],

 (select c.COLUMN_NAME [@ColumnName]
    from INFORMATION_SCHEMA.COLUMNS c
    where c.TABLE_NAME = t.TABLE_NAME
  for xml path('Column'), type)

 from INFORMATION_SCHEMA.TABLES t
for xml path('Table'), type)

for xml path('DataBase')


text:
Q: PKCS#12 Keystore creation on Android device I'm currently developing an Android app that generates an RSA key pair, builds and sends an PKCS#10 certification request to one CA, waits for the CA's response (which contains the certificate-chain including the issued for the end-entity), and then builds the PKCS#12 KeyStore to be installed within the Android KeyStore.
I just show you below some piece of code:
// It removes Android-BC
Security.removeProvider("BC");
// I've tried with SpongyCastle but it also fails.
// I've previously imported BC jars.
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance("PKCS12","BC");
ks.load(null);

// KeyPair generated by RSA with BC, and certificates obtained from CA.
PrivateKey prvK;
Certificate eeCert, caCert;

PKCS12BagAttributeCarrier caCertBagAttr =
   (PKCS12BagAttributeCarrier) caCert;
caCertBagAttr.setBagAttribute(
   PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
   new DERBMPString("CA"));

PKCS12BagAttributeCarrier certBagAttr =
   (PKCS12BagAttributeCarrier) eeCert;
certBagAttr.setBagAttribute(
   PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
   new DERBMPString("EE Certificate"));
certBagAttr.setBagAttribute(
   PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
   new SubjectKeyIdentifierStructure(eeCert.getPublicKey()));

Certificate[] chain = new Certificate[2];
chain[1] = caCert;
chain[0] = eeCert;

PKCS12BagAttributeCarrier privBagAttr =
   (PKCS12BagAttributeCarrier) prvK;
privBagAttr.setBagAttribute(
   PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
   new DERBMPString("EE Certificate Key"));
privBagAttr.setBagAttribute(
   PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
   new SubjectKeyIdentifierStructure(eeCert.getPublicKey()));

// Finally, keystore is saved to file.
ks.setKeyEntry("P12", prvK, null, chain);
saveP12File(ks);

The thing is that everything is working OK when I run it on my Windows PC (BouncyCastle 1.49), but that PKCS#12 file created when I run it on Android cannot be used on SSL handshake or signing because Logcat says that it doesn't have any associated PrivateKey.
If I print the full content of the KeyStore on Java after loading the file, it seems that everything is right, but when I use on Android Browser or when I take it and install on Windows, its private key can't be used.
Same code on Android and PC, same version of BC, PKCS#12 doesn't seem to be malformed.
Can anybody help me?
Thanks in advance.
EDIT
I have built a servlet that generates an RSA Key Pair and sends back to my app in PEM format.
All seems work OK:

*

*I can generate a valid (encrypting with public and decrypting test works good) RSA keypair either on Android device or through the external servlet.

*I receive both CA and EE certificates from the CA.

*I'm able to build a "valid" PKCS12 (I called it valid because it can be read by Android, Windows)

But:

*

*I'm not able to open an SSL channel using the EE certificate as client-certificate for handshake. Either on Windows or Android.

I have uploaded to my Dropbox:

*

*CA certificate

*EE certificate issued by the CA

*Private Key for the EE certificate

*Public Key for the EE certificate

*PKCS12 created on Android

*Java Android Code
Tested against Tomcat with empty trustStore (doesnt' matter which CA issued client-certificate) unsuccessfully.
Does anybody see something that could explain it?


text:
Q: Integrating spring-boot with RESTEasy I am trying to prototype a Spring Boot application.  I'm coming from a Guice JAX-RS application, so I prefer the standard JAX-RS annotations to Spring MVC.  I've gotten Jetty up and serving:
@Configuration
@Import({ResteasyBootstrap.class, SpringBeanProcessorServletAware.class, HttpServletDispatcher.class})
public class EmbeddedJetty {
    @Bean
    @Singleton
    public EmbeddedServletContainerFactory servletContainer() {
        JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
        factory.setPort(9000);
        factory.setSessionTimeout(10, TimeUnit.MINUTES);
        return factory;
    }
}

However, I just can't figure out how to get RESTEasy hooked up correctly.  With the above SpringBeanProcessorServletAware it bails, seemingly the ServletContext is not injected through ServletContextAware before it ends up being used:
java.lang.NullPointerException: null
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessorServletAware.getRegistry(SpringBeanProcessorServletAware.java:30)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:247)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:680)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)

I also tried using the SpringContextLoaderListener, but that seems to conflict with the spring-boot AnnotationConfigEmbeddedWebApplicationContext class.
I'm using spring-boot 1.3.3 and spring-framework 4.3.0.rc1

A: The other answer won't have your resources as spring beans, this autoconfiguration will integrate them properly:
The Configuration class:
@Configuration
@ConditionalOnWebApplication
public class RestEasyAutoConfigurer {

    private Environment environment;

    @Bean(name = "resteasyDispatcher")
    public ServletRegistrationBean resteasyServletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HttpServletDispatcher(), getPrefix()
                + "/*");
        registrationBean.setInitParameters(ImmutableMap.of("resteasy.servlet.mapping.prefix", "/rs/")); // set prefix here
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean(destroyMethod = "cleanup")
    public static RestEasySpringInitializer restEasySpringInitializer() {
        return new RestEasySpringInitializer();
    }

    @Bean
    // use Spring Boot configured Jackson
    public CustomResteasyJackson2Provider jackson2Provider(ObjectMapper mapper) {
        return new CustomResteasyJackson2Provider(mapper);
    }

    public static class RestEasySpringInitializer
            implements
                ServletContextInitializer,
                ApplicationContextAware,
                BeanFactoryPostProcessor {

        private ResteasyDeployment deployment;

        private ConfigurableApplicationContext applicationContext;

        private ConfigurableListableBeanFactory beanFactory;

        public void cleanup() {
            deployment.stop();
        }

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            ListenerBootstrap config = new ListenerBootstrap(servletContext);
            deployment = config.createDeployment();
            deployment.start();

            servletContext.setAttribute(ResteasyProviderFactory.class.getName(), deployment.getProviderFactory());
            servletContext.setAttribute(Dispatcher.class.getName(), deployment.getDispatcher());
            servletContext.setAttribute(Registry.class.getName(), deployment.getRegistry());

            SpringBeanProcessor processor = new SpringBeanProcessor(deployment.getDispatcher(),
                    deployment.getRegistry(), deployment.getProviderFactory());
            processor.postProcessBeanFactory(beanFactory);
            applicationContext.addApplicationListener(processor);
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            this.beanFactory = beanFactory;
        }

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = (ConfigurableApplicationContext) applicationContext;
        }
    }
}

And the Jackson provider:
@Provider
@Consumes({"application/*+json", "text/json"})
@Produces({"application/*+json", "text/json"})
public class CustomResteasyJackson2Provider extends ResteasyJackson2Provider {
    private ObjectMapper mapper;

    public CustomResteasyJackson2Provider(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public ObjectMapper locateMapper(Class<?> type, MediaType mediaType) {
        return Optional.ofNullable(_mapperConfig.getConfiguredMapper()).orElse(mapper);
    }
}

NOTE: this is a working configuration for Spring Boot 1.3.3 / RESTEasy 3.0.16

A: You can use RESTEasy Spring Boot starter. Here is how you do it:
Adding POM dependency
Add the Maven dependency below to your Spring Boot application pom file.
<dependency>
   <groupId>com.paypal.springboot</groupId>
   <artifactId>resteasy-spring-boot-starter</artifactId>
   <version>2.1.1-RELEASE</version>
   <scope>runtime</scope>
</dependency>

Registering JAX-RS application classes
Just define your JAX-RS application class (a subclass of Application) as a Spring bean, and it will be automatically registered. See the example below. See section JAX-RS application registration methods in How to use RESTEasy Spring Boot Starter for further information.
package com.test;

import org.springframework.stereotype.Component;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@Component
@ApplicationPath("/sample-app/")
public class JaxrsApplication extends Application {
}

Registering JAX-RS resources and providers
Just define them as Spring beans, and they will be automatically registered. Notice that JAX-RS resources can be singleton or request scoped, while JAX-RS providers must be singletons.
Further information at the project GitHub page.

A: Here is fully working example.

*

*First, a sample JAX-RS endpoint:
@Path("/api")
public class SampleResource {
    @GET
    @Path("/sample")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSample() {
        return "Some JSON";
    }
}

*Next, a JAX-RS configuration class that loads all endpoints.
import javax.ws.rs.core.Application;

public class RestEasyConfig extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(SampleRest.class);
        return classes;
    }
}

*Finally, in your Spring configuration, initialize RESTEast filter and inform the framework about its existence.
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.jboss.resteasy.plugins.server.servlet.FilterDispatcher;
...

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    Map<String, String> initParams = new HashMap<>();
    initParams.put("javax.ws.rs.Application", RestEasyConfig.class.getCanonicalName());

    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new FilterDispatcher());
    registrationBean.setInitParameters(initParams);
    return registrationBean;
}

Your endpoint should be up and running. If you are missing the FilterDispatcher class on your class path, add the resteasy-jaxrs library to your build descriptor.


text:
Q: need to replace map with variable value I have xslt and below code works fine, however I need to replace "map{"abc": "yes","dDEF": "Yes","RMT": "dsfdf","PPAS": "Yes","UNITE": "Yes"}"  with variable
<xsl:variable name="var_res">
        <xsl:value-of select='map:for-each(map{"abc": "yes","dDEF": "Yes","RMT": "dsfdf","PPAS": "Yes","UNITE": "Yes"}, function($k, $v){
          {
            if($v!="Yes" and $v!="No")
            then $k else ""})' />
        </xsl:variable>

as below :
        <xsl:variable name="var_mapValue" >
            <xsl:value-of select="/root/input/collective_barg"></xsl:value-of>

        </xsl:variable>

      <xsl:variable name="var_res">
        <xsl:value-of select='map:for-each(map(var_mapValue)}, function($k, $v){
          {
            if($v!="Yes" and $v!="No")
            then $k else ""})' />
        </xsl:variable>

map(var_mapValue) doesn't work not sure what is missing here
and my input xml
 <?xml version="1.0" encoding="UTF-8"?>
<root>
<input>
<collective_barg>
{"abc": "yes","dDEF": "Yes","RMT": "dsfdf","PPAS": "Yes","UNITE":
"Yes"}
</collective_barg>
</input>
</root>

A: To parse the JSON and turn it into what the XML Data Model defines as a "map", you should use the XPath 3.1 function parse-json() https://www.w3.org/TR/xpath-functions-31/#func-parse-json
<xsl:variable name="map" select="parse-json(/root/input/collective_barg)"/>

Also NB string comparison in XSLT is case sensitive; the string value Yes is not equal to yes. I suggest you use the upper-case() (or lower-case()) function to normalize the text and then compare it to "YES" (or "yes").
By the way, when you are declaring a variable, you can just assign its value using the select attribute; you don't need to enclose an xsl:value-of element. Using xsl:value-of just has the effect of converting the data to a string. If you really do want to convert it to  a string, you can use the string() function. e.g. don't do this:
<xsl:variable name="var">
        <xsl:value-of select="blah"/>
        </xsl:variable>

do this:
<xsl:variable name="var" select="blah"/>

or if you do want to convert the input to a string, do this:
<xsl:variable name="var" select="string(blah)"/>

A: mange to fix the issue by using ParseJson
    <xsl:variable name="var_mapValue" >
          <xsl:value-of select="Parse-json(/root/input/collective_barg)">
  </xsl:value-of>

    </xsl:variable>

  <xsl:variable name="var_res">
    <xsl:value-of select='map:for-each($var_mapValue, function($k, $v){
      {
        if($v!="Yes" and $v!="No")
        then $k else ""})' />
    </xsl:variable>


text:
Q: How to strip a part of the text obtained from web harvest I am new to webharvest and am using it to get the article data from a website, using the following statement:
let $text := data($doc//div[@id="articleBody"])

and this is the data that I get from the above statement :
The Refine Spa (Furman's Mill) was built as a stone grist mill along the on a tributary of Capoolong Creek by Moore Furman, quartermaster general of George Washington's army

Notable people

Notable current and former residents of Pittstown include:

My question is that, is it possible to remove the entire content which is after "Notable people" using the configuration. Is it possible to do this way? If its possible please let me know how. Thanks.
Edit:
The desired output:
The Refine Spa (Furman's Mill) was built as a stone grist mill along the on a tributary of Capoolong Creek by Moore Furman, quartermaster general of George Washington's army

Notable people

A: you just need to change your let statement like:
let $text := substring-before(data($doc//div[@id="articleBody"]/text()), 'Notable people')
to get your desired output


text:
Q: Secure Webscoket Connection using wss is never established i want to build an architecture with wss, i implement my certificates and they work. But now, when i'm connect on the browser, my program create websocket and close it directly, i don't understand why, this is my code which is running at port 5005
 window.onload=function(){
   if (!window.WebSocket) {
    window.WebSocket = window.MozWebSocket;
   }
  if (window.WebSocket) {

    socket = new WebSocket("wss://localhost:7575/websocket");

    socket.onopen = function(){
        alert("opened the connection");
        socket.send("Hello");
    };

    socket.onmessage = function(message){
        var json = jQuery.parseJSON(message.data);
        notifyApplication(json);
    };
    socket.onclose=function(){
     alert("Websocket coonection is closed");
    };
}
else {
    alert("Your browser doesn't support websocket");
}

};
and the webscoket server is implemented using netty and it is running at the port 7575.
which offers an SSL3.0 enabled https connection.


text:
Q: Find the smallest positive integer that gives remainder 1 when divided by 2,3,4,5,6,7,8 The question states:

Find The smallest positive integer that gives the remainder 1 when it is divided by each of the numbers 2, 3, 4, 5, 6, 7, 8.

Any ideas on how to begin?

A: Call the number you're looking for $x$. Then by definition, $x-1$ is a multiple of $2,3,...,8$. To find the smallest such $x-1$, find the least common multiple of these numbers.

A: Let $x $ be the number.
The $x -1 $ is a common multiple of 2,3,4,5,6,7,8.  To be the smallest number you somehow have to find the smallest common multiple.  The least common one, if you will.


text:
Q: How to use a shape drawable for actionbar shadow (no intrinsic height?) I want to supply my own drawbable for my ActionBar. I know you can do it via:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    <item name="android:windowContentOverlay">@drawable/my_drawable</item>
</style>

but I want to use a shape drawable, which doesn't have an intrinsic width or height. I tried  specifying the width/height:
// my_drawable
<shape
  android:shape="rectangle"
  android:height="10dp"
  android:width="100dp">
  <solid android:color="#ffff0000" />
</shape>

but nothing gets rendered. If I swap in a 9 patch png, it shows up ok. Even if this does work, I would also need the width to not be an explicit integer, rather something like "fill_parent".
Thanks


text:
Q: Is it possible to change username and all configuration (filenames, ...) for Windows user? I have a Lenovo laptop with Windows 10, and when I first started it 2 years ago, it asked me for my name to set up default user. My name is Róbert (notice the ó).
Now, in my file system I have C:\Users\Róbert. Seems neat. However, over the years I became somewhat of a coder, and the weird letter ó started causing some problems. It first happened when I started using Android Studio and Java, more recently (today) when I reinstalled Anaconda (distribution for Python).
I am sure it was problem with the ó, because it throws errors like can't read non-ascii character 0xf3 and so on.
Is there a way to solve this (reconfigure everything)? I believe setting up a new user is a possibility, but I would prefer other solution.

A: Changing the name of the user folder can be tricky.  See this article:
https://www.groovypost.com/howto/change-account-name-windows-10/
Note the warning:

Renaming it can be risky—sometimes sticking with it or just creating a
  new user account then copying your files to the new account is a
  better option. Yes, it's annoying, but its better than ending up with
  a corrupt user profile

You may truly be better to make a new User Profile and that is what I recommend


text:
Q: UIView.animateWithDuration stops after scrolling uitableviewcell i have added a infinite animation in uiTableViewCell which just blinks a UILabel inside the table view cell.
my problem is, when i scrolls the tableview it just stops the blinking
my code is
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TripListCell", forIndexPath: indexPath) as! TripListCell

    let trip = tripList[indexPath.section]
    cell.lblTripDirection.textColor = UIColor(red: 51/255, green: 210/255, blue: 123/255, alpha: 1.0)

    UIView.animateWithDuration(0.5, delay: 0.0, options: [.CurveEaseInOut, .Repeat, .Autoreverse, .AllowUserInteraction], animations: {

        cell.lblTripDirection.alpha = 0.0
        }, completion: {
            bool in
        cell.lblTripDirection.alpha = 1.0
        cell.lblTripDirection.textColor = UIColor.blackColor()
    })
    return cell
}

Update:
UIView.commitAnimations() before returning the cell worked for me.
Thank you everyone :)

A: You can override prepareForReuse method of the UITableViewCell in your custom cell TripListCell.
prepareForReuse is called every time whenever dequeueReusableCellWithIdentifier is called.

A: It is because cellForRowAtIndexPath resuse the same cell to display other data. so you shouln't write your animation in cellForRowAtIndexPath.
You should try to write in awakeFromNib of custom cell class or you should use willDisplayCell method to write animation.
hope this will help :)

A: You should put your code in this UITableViewDelegate method :
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath);

A: TableViews reuse their cells so inevitably your label stop their animation.
You can restore the reused cell to its default state either in prepareForReuse: on the custom table view cell or in the tableView:willDisplayCell:forRowAtIndexPath: delegate method.
In this case you use UIView animations, you only need to change the value of the animated property to cancel the animation and return to the default state.
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    //declaring the cell variable again

    var cell: TripListCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TripListCell
    UIView.performWithoutAnimation {
        cell.lblTripDirection.layoutIfNeeded()
    }
    // do your animation..
    ...
}

A: UIView.commitAnimations() before returning the cell worked for me.


text:
Q: Cycle2 Slideshow multiple pager not working I am trying to get the pager for Cycle2 to show up in a couple of different locations. I am using the example from the Cycle2 site for multiple pagers. Since no luck in my application I tried stripping everything out and doing in a fiddle. My fiddle gives me the same results as my web application. The pager is tiny and not styled.
I've looked at the source of the Cycle2 example page as well. I can't seem to make the example with no modifications at all work for me like it does on there site. What am I doing wrong.
My fiddle which I believe is exact copy of Cycle2 site:

http://jsfiddle.net/rplace/uLb8u/1/
Cycle2 site showing pager examples...I am interested in multiple pager example (2nd) one down.
http://jquery.malsup.com/cycle2/demo/pager.php

A: Try adding "height:40px;" to the .cycle-pager class.


text:
Q: Converting results of a MySQL query into a string My query is:
$orderitemsattributes_query = "SELECT products_options_values
FROM orders_products_attributes oa
WHERE oa.orders_id
IN (
SELECT DISTINCT o.orders_id
FROM orders o
WHERE o.exported =  '0'
AND o.orders_id >  '0')";
$orderitemsattributes_result = mysql_query($orderitemsattributes_query);
while($row = mysql_fetch_array($orderitemsattributes_result)) {

echo $row['products_options_values'];
}

gives me the following:
 6 period day (TP6)NavyGold (j)Gold Lamé (17)LJD1 at back (free)

I want to be able to convert this to a single string for insertion into another field on the database.
I tried:
$tradebox_attributes_list = implode (',', $row);`

but i either don't get anything, or i get incomplete results stored in $tradebox_attributes_list depending where i put the implode.
I need to be able to read this variable some way further along the code, well after the closing }.
Table Structure is:
CREATE TABLE IF NOT EXISTS `orders_products_attributes` (
  `orders_products_attributes_id` int(11) NOT NULL AUTO_INCREMENT,
  `orders_id` int(11) NOT NULL DEFAULT '0',
  `orders_products_id` int(11) NOT NULL DEFAULT '0',
  `products_options` varchar(32) NOT NULL DEFAULT '',
  `products_options_values` text NOT NULL,
  `options_values_price` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `price_prefix` char(1) NOT NULL DEFAULT '',
  `product_attribute_is_free` tinyint(1) NOT NULL DEFAULT '0',
  `products_attributes_weight` float NOT NULL DEFAULT '0',
  `products_attributes_weight_prefix` char(1) NOT NULL DEFAULT '',
  `attributes_discounted` tinyint(1) NOT NULL DEFAULT '1',
  `attributes_price_base_included` tinyint(1) NOT NULL DEFAULT '1',
  `attributes_price_onetime` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_factor` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_factor_offset` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_factor_onetime` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_factor_onetime_offset` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_qty_prices` text,
  `attributes_qty_prices_onetime` text,
  `attributes_price_words` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_words_free` int(4) NOT NULL DEFAULT '0',
  `attributes_price_letters` decimal(15,4) NOT NULL DEFAULT '0.0000',
  `attributes_price_letters_free` int(4) NOT NULL DEFAULT '0',
  `products_options_id` int(11) NOT NULL DEFAULT '0',
  `products_options_values_id` int(11) NOT NULL DEFAULT '0',
  `products_prid` tinytext NOT NULL,
  `tradebox_attributes_list` text NOT NULL,
  PRIMARY KEY (`orders_products_attributes_id`),
  KEY `idx_orders_id_prod_id_zen` (`orders_id`,`orders_products_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=77065 ;

Sample of one entry is:

(76569, 22959, 34813, 'Lesson format', '6 period day (TP6)', 0.0000, '+', 1, 0, '+', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 5, 55, '30:499bc45895cd0baaef055a57cb36df5d', ''),
(76570, 22959, 34813, 'Cover', 'Navy', 0.0000, '+', 1, 0, '+', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 1, 2, '30:499bc45895cd0baaef055a57cb36df5d', '1 at back (free)'),
(76571, 22959, 34813, 'Wire', 'Gold (j)', 0.0000, '', 1, 0, '', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 4, 49, '30:499bc45895cd0baaef055a57cb36df5d', ''),
(76572, 22959, 34813, 'Ribbon', 'Gold Lamé (17)', 0.0000, '+', 1, 0, '+', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 3, 29, '30:499bc45895cd0baaef055a57cb36df5d', ''),
(76573, 22959, 34813, 'Initials (Max 4)', 'LJD', 3.3000, '+', 1, 0, '+', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 2, 0, '30:499bc45895cd0baaef055a57cb36df5d', ''),
(76574, 22959, 34813, 'Plastic pockets', '1 at back (free)', 0.0000, '+', 1, 0, '+', 1, 1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, '', '', 0.0000, 0, 0.0000, 0, 6, 84, '30:499bc45895cd0baaef055a57cb36df5d', ''),

I need to be able to take all the results stored in the products_options_values field (note, there are six just for this order) and store them as a comma separated list in the tradebox_attributes_list field.
EDITED AS REQUIREMENTS JUST BEEN CHANGED:
I'm about to throw a spanner in the works now. group_concat() will work, but i have just been asked to display one of the attributes on a separate line. For instance, we want the following:
  6 Period Day, Navy, 1 at back (free) NEW LINE
  LJD  £3.30
Not so simple now as i need to select specific products_options_values, then on a separate line, select a different option and it's associated price from the options_values_price field.

A: Can you use a group_concat() to get the values group by order id. Wish we could see the table though..
SELECT group_concat(products_options_values)
FROM orders_products_attributes oa
WHERE oa.orders_id
IN (
SELECT DISTINCT o.orders_id
FROM orders o
WHERE o.exported =  '0'
AND o.orders_id >  '0')
group by oa.orders_id;


text:
Q: Using digital input pin to read variable resistance from sensor requiring supply voltage I intend to use air contaminants sensor TGS 2602. The internal resistance changes if a given gas is detected. It requires an input voltage V_C = 5V to operate.
According to the specs, the basic measurement circuit is:

simulate this circuit – Schematic created using CircuitLab
The problem I am facing is I want to read the measurements with digital IO pins, specifically I want to use Raspberry Pi for this. I found a simple solution to a similar problem here:
Reading Analogue Sensors With One GPIO Pin. Essentially it involves using an RC circuit and measuring time lapsed until "high" voltage occurs on our digital pin.

In this case I would then be inclined to simply switch R_L with a capacitor but by doing this I would quickly cut off the supply voltage for the sensor (it requires V_C). I then thought I should maybe add the capacitor in parallel with R_L. But the R_L voltage drop is low, so I would never reach the "high" voltage on the capacitor to be able to read it with my digital pin. Should I perhaps use op-amp to drive the V_RL up? But is it not over-complicating things?
My question is then how should I measure value of R_S with a digital reader?

A: First, be aware that your sensor does require a 5v +-0.2 supply, both for the heater and sensor. The RPI should have +5v available.
The capacitor discharge method that you propose is one of very few available to RPI to convert an analog signal to a digital representation. RPI GPIO pins require a voltage range between 0 to +3.3v.
Data sheet says load resistor minimum is 450 ohms. No maximum, so a capacitor load might be acceptable:

simulate this circuit – Schematic created using CircuitLab
This circuit at left might work, if you let the circuit idle with GPIO as output, programming a logic zero forcing R1 to pull down the cell resistor R2 toward ground, until you wish to input a reading. Reading may go quickly enough not to disturb R2 cell resistance too much.
If you are reluctant to disturb cell operation from the prescribed load circuit, the amplifier at right might allow a similar capacitor charging/timing method. A quick run with LTSPICE suggests a timing range between 800 uS for a sensor resistance of 100k ohm, and about one second for sensor resistance of 10k ohm. Cell resistor R4 remains always near 5v.
However, be aware that the GPIO measurement sequence requires a polarity switch: C2 must be discharged by setting GPIO to logic high, then transistor Q1 pulls it down slowly towards logic 0

A: Fairly easy. Your sensor is more like a CCS whose output current varies with the gas it detects.
So use the CCS to charge up a capacitor, and the time it takes the gpio goes high varies with the CCS current, thus it's resistsnce.
The procedure goes like thi, assuming the gpio is connected to the capacitor and your sensor.
1.output a low on the gpio and turn it as output. wait a little bit. This discharges the capacitor.

*Turn the gpio as input. This allows the capacitor to be charged up.

*Count the time until the gpio goes high.

*The time measurement is a function of the current.
The oldest trick there is for MCU to read analog with an ADC.


text:
Q: Google Apps Script for Spreadsheet - Keep getting the function () { [native code] } error I execute my function, and it returns a function () { [native code] } error alongside the proper outputs. Example: Input Output
My code:

function SubmitInput() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var inputS = ss.getSheetByName("FORM");
  var outputS = ss.getSheetByName("ARCHIVE")

  var values = [[inputS.getRange("C7").getValue,
                inputS.getRange("C9").getValue(),
                inputS.getRange("C11").getValue(),
                inputS.getRange("F7").getValue(),
                inputS.getRange("F9").getValue(),
                inputS.getRange("F11").getValue(),
                inputS.getRange("I7").getValue(),
                inputS.getRange("I9").getValue()]];
 outputS.getRange(outputS.getLastRow()+1, 1, 1, 8).setValues(values);
 ClearCell();
}

A: you have a typo in your code
inputS.getRange("C7").getValue,¸

should be
inputS.getRange("C7").getValue(),¸


text:
Q: How to change string to integer How can I change a string input to integer-
for example-
read_line_to_codes(user_input,L),
atom_codes(C,L).

In this C is storing a string.Suppose the user entered 18.So I want to use this 18 as an integer so that I can use operations like >= with C.Is this possible in Prolog?

A: Prolog datatypes don't include 'strings'. SWI-prolog added it recently, but you can stay on ISO safety lane with number_codes

A: You can forcefully assigned an int datatype to the user input, you are letting the JVM know that you know what you are doing and this will let the program compile in case if the int data type is smaller than the user input string size. Here is an example code to help you.
public class stringToInt{

  public static void main(String []args){

    string C = 18; //User input, make sure to use the scanner class to get the user input value
    int int_C = (int) C;

    /**Your new value is now in int datatype and you can go ahead and use int_C for your arithmetic
            opreation **/
  }

}


text:
Q: Trouble with php cURL library and REST POST request I'm having trouble with a REST POST request after the API to which I'm posting published the final release of their API. It was working without incident, and I've been told that with the new version the server is more strict regarding the type being 'application/json'. The following cli curl command works swimmingly:
cat json.txt|curl -v -k -u user:password -F 'exchangeInstance=@-;type=application/json'  https://my.url.here

However, I need to execute this in code. Using the php curl libraries I've got a simple test script up that looks like this:
  $post = array(
    "exchangeInstance" => $json_string,
    "type" => "application/json",
  );
  $url = 'myurlhere';

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

  $result = curl_exec($ch);
  $info = curl_getinfo($ch);

  var_dump($post);
  var_dump($result);
  echo $result;
  var_dump($info);

As I read the documentation, the Content-type in the header should automatically be set to 'multipart/form' if I pass an array as CURLOPT_POSTFIELDS, and then I'm setting the type for the element pass to 'application/json' in the array.
However, the api has had no POST requests from me. And I'm getting an error from them that clearly indicates that they are receiving a GET request. How can this possibly be? What am I missing?

A: curl -F !== -d
$post = array(
    "exchangeInstance" => sprintf('@%s;type=application/json', $json_string),
);


text:
Q: Java parse XML with many levels I have a complex xml string that i have to parse i retrieve some data, here is the content :
<root1>
    <root2>
        something
        something
        <C>
            <D>
                <GetE>DataE</GetE>
                <GetF>DataF</GetF>
                <G>something</G>
                <H>something</H>

                    <J>
                      <GetK>DataK</GetK>
                      <GetL>DataL</GetL>
                    </J>

            </D>
            <D>
                <GetE>DataE</GetE>
                <GetF>DataF</GetF>
                <G>something</G>
                <H>something</H>

                    <J>
                      <GetK>DataK</GetK>
                      <GetL>DataL</GetL>
                    </J>

            </D>
        </C>
     </root2>
</root1>

I would like to print the content of GetE, GetF, GetK and GetL :
for example :
GetE = DataE,GetF = DataF,GetK = DataK,GetL = DataL
GetE = DataE,GetF = DataF,GetK = DataK,GetL = DataL
...
To convert my String data to an XML, I use this function In Java, how do I parse XML as a String instead of a file?
Any idea please ?

A: First of all, check this answer that's more applicable to your case. XPath is a convenient and easy t-to-use technology to extract the information you seek, but performance requirements may dictate otherwise.
The xpath expressions, in your case, would be, for instance::
"root1/root2/C/D/GetE/text()"
"root1/root2/C/D/GetF/text()"

But as others have commented, "root1/root2/C/D/GetE" doesn't return a single node, so you have to decide how you are going to represent the information too.

A: Maybe there is a simpler way but SAXParser would do the job.


text:
Q: Loop should stop after the 10th click, but it does not I am new to android programming. I am making a small test app which is a simple multiplier.
My app has a Textview and three buttons.Namely
Multiply by 2, Multiply by 3 and Clear.
The code works fine while multiplication ,but I want the loop to end after 10 and the textview should display "Stopped" after the 10th click of the buttons..I have tried various techniques but none seem to work. I am not sure whether "Do-while" is a good idea.
Here's the java code:
public class MainActivity extends Activity {

TextView Display;
Button X2, X3, Clear;
int a = 1, result;
String Over = "Stopped";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // a = 1;
    X2 = (Button) findViewById(R.id.bX2);
    X3 = (Button) findViewById(R.id.bX3);
    Clear = (Button) findViewById(R.id.bClear);
    Display = (TextView) findViewById(R.id.tvDisplay);
    X2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // a = 1;
            // this loop should stop after the 10th click of the button
            // and the text view should display "stopped"
            do {
                result = a * 2;
                Display.setText("2 X " + a + " = " + result);
                a++;
            } while (a == 0);
        }
    });
    X3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // a = 1;
            // this loop should stop after the 10th click of the button
            // and the text view should display "stopped"
            do {
                result = a * 3;
                Display.setText("3 X " + a + " = " + result);
                a++;
            } while (a == 0);
        }
    });
    Clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            result = 0;
            a = 1;
            Display.setText("" + result);
        }
    });
}

}
and the here's the XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="clip_vertical"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/tvDisplay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:hint="Result display"
    android:textSize="25sp" />

<Button
    android:layout_width="250dp"
    android:layout_gravity="center"
    android:id="@+id/bX2"
    android:layout_height="wrap_content"
    android:text="Multiply by 2" />

<Button
    android:layout_width="250dp"
    android:layout_gravity="center"
    android:id="@+id/bX3"
    android:layout_height="wrap_content"
    android:text="Multiply by 3" />

<Button
    android:layout_width="75dp"
    android:layout_gravity="center"
    android:id="@+id/bClear"
    android:layout_height="wrap_content"
    android:text="Clear" />

I am not aware of the posting rules and hence excuse me if I am violating any. I am really stuck here, and any help would be "Great".
Thank you.

A: Your loop is executing for each click
A do-while always executes once before checking the while condition, also I can't see any logic related to the value 10.
You probably want
if (a <= 10) {
   //do some stuff
}

in place of your do-while loops

A: You have to keep a counter and initialize it with 0 initially.
On your onClickListener increase this counter variable value by one and check whether it is is equal to 10. If it so then display stopped.
private int counter; // Instance variable

public void onClick(View v) {
    counter++;
    if(counter == 10) {
        // display the stop on your textview here
    }
    ...do whatever you want here
}

A: A button's onClickListener executes every time the button is clicked. You need to have a variable(s) at the class level that serves as a counter that will count the number of clicks. Each time the button is clicked, you increment this counter by one. Finally, when this counter reaches 10, you will set the TextView to display stopped.
Also, it might be a better option to use the 'if' clause rather than do-while.

A: public class MainActivity extends Activity {

TextView Display;
Button X2, X3, Clear;
int a = 1, result;
String Over = "Stopped";
counter = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // a = 1;
    X2 = (Button) findViewById(R.id.bX2);
    X3 = (Button) findViewById(R.id.bX3);
    Clear = (Button) findViewById(R.id.bClear);
    Display = (TextView) findViewById(R.id.tvDisplay);
    X2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // a = 1;
            // this loop should stop after the 10th click of the button
            // and the text view should display "stopped"
            if(counter<10)

                result = a * 2;
                Display.setText("2 X " + a + " = " + result);
                a++;
               counter++
            }
           else{
                     Display.setText("Stopped");
               }
        }
    });