text:
Q: Display db items in listview android studio i am making app with db and i have created db and all things but i cant recive db column items to display it in listview?
here is my dbadapret.java code for displaying only one column from db
public Cursor listallbarcodes() {
    Cursor mCursor = db.query(DATABASE_TABLE, new String[] {KEY_CONTAINERBARCODE},
            null, null, null, null, null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

and here is the code in myactivity for loading this items in list view
 private void displayListView() {

    Cursor cursor = myDb.listallbarcodes();

    String[] columns = new String[]{
            DBAdapter.KEY_CONTAINERBARCODE
    };

    int[] to = new int[]{
            R.id.product_name,
    };
    dataAdapter = new SimpleCursorAdapter(this, R.layout.mylist, cursor, columns, to, 0);

    ListView listView_ladung = (ListView) findViewById(R.id.listview_ladung);
    // Assign adapter to ListView
    listView_ladung.setAdapter(dataAdapter);
}

what do i wrong?
Thanks


text:
Q: if customer login redirect him to account page i want when a logged customer visit a CMS page he should be redirect to account page and when customer is not login he can see page content.

A: *

*First you need to call a custom template from your cms/page.

{{block type="core/template" name="visitor_page"
  template="YourTemplateFolder/TemplateFileName.phtml"}}

*Then in your .phtml file you can do something like this:

$logged_in = Mage::getSingleton('customer/session' )->isLoggedIn();
if ($logged_in){
$url = Mage::getUrl('customer/account');
Mage::app()->getResponse()->setRedirect($url);
return;
}

?>

MY CMS PAGE CONTENT

MAYBE YOU CAN CALL A CMS BLOCK TO MAKE CONTENT ADMINISTRABLE.

A: This is not an easy one to explain.  To maintain control over all aspects you will probably need to extend the original Customer Account class and handle the redirects yourself.  However you should try to see if some of the built in functionality works that Magento gives you out of the box.
To set where customers go after they login, you can set this value in System->Configuration->Customers->Customer Configuration->Login Options
This drop down will allow you to move customers to their dashboard after logging in.
If this does not offer enough flexibility, do an extension of Mage_Customer is your next option.
First step create the module declaration for example app/etc/modules/Gallup_Customer.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Russell_Customer>
            <active>true</active>
            <codePool>local</codePool>
        </Russell_Customer>
    </modules>
</config>

Next you need to create your local module, in this example we are using the Namespace Russell
Create a folder in
app/code/local/Russell
Then create an etc folder here is the path
app/code/local/Russell/Customer/etc/
Inside that create a file called config.xml here is the path
app/code/local/Russell/Customer/etc/config.xml
that xml file should have something similar to this:
<?xml version="1.0" encoding="UTF-8"?>
    <config>
        <modules>
            <Russell_Customer>
                <version>0.1.0</version>
            </Russell_Customer>
        </modules>
    <frontend>
        <routers>
            <customer>
                <args>
                    <modules>
                        <Russell_Customer before="Mage_Customer">Russell_Customer</Russell_Customer>
                    </modules>
                </args>
            </customer>
        </routers>
    </frontend>
</config>

Next create a controllers folder in app/code/local/Russell/Customer/controllers and create a file called AccountController.php
It may look similar to this.  this version I am showing is very simple, I would assume you have some other logic you need to use but this should give you a head start.
<?php

require_once 'Mage/Customer/controllers/AccountController.php';

class Russell_Customer_AccountController extends Mage_Customer_AccountController
{
        protected function _loginPostRedirect()
    {
        $session = $this->_getSession();

        if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl()) {
        // Set default URL to redirect customer to
        $session->setBeforeAuthUrl($this->_getHelper('customer')->getAccountUrl());
        // Redirect customer to the last page visited after logging in
        if ($session->isLoggedIn()) {
            if (!Mage::getStoreConfigFlag(
                Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD
            )) {
                    $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
                    if ($referer) {
                    // Rebuild referer URL to handle the case when SID was changed
                        $referer = $this->_getModel('core/url')
                        ->getRebuiltUrl( $this->_getHelper('core')->urlDecodeAndEscape($referer));
                        if ($this->_isUrlInternal($referer)) {
                        $session->setBeforeAuthUrl($referer);
                        }
                    }
                } else if ($session->getAfterAuthUrl()) {
                    $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
                }
            } else {
            $session->setBeforeAuthUrl( $this->_getHelper('customer')->getLoginUrl());
            }
        } else if ($session->getBeforeAuthUrl() ==  $this->_getHelper('customer')->getLogoutUrl()) {
            $session->setBeforeAuthUrl( $this->_getHelper('customer')->getDashboardUrl());
        } else {
            if (!$session->getAfterAuthUrl()) {
                $session->setAfterAuthUrl($session->getBeforeAuthUrl());
            }
            if ($session->isLoggedIn()) {
                $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
            }
        }
        // set the redirect URL
        $this->_redirectUrl($this->getUrl('module/controller/action');
    }

}

Now with this in place you can take the customers to any page you want after they log in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could we loop through an API response in Batch Apex rather than a soql result? I have been thinking if Batch Apex could be made to work with an API response rather than a soql query's result (which is usually the case).
Assume that we have a rest API that returns a JSON response that could be deserialized to a List of type custom apex class (List<DeserializableClass>), would we be able to loop through this deserialized List response in Batch Apex's execute method?
I found one interesting reply from @sfdcfox on the following post:
https://developer.salesforce.com/forums/?id=906F00000008yXCIAY
Reading through that post, I got a feeling that this could be made possible, but I'm not quite sure how its done. Please do share your experience if you have done/tried this before.
P.S - this may be a silly question, but I had to ask anyway! :)

A: In your case, since you're getting a list from your callout, you can just do this:
global class MyBatch implements Database.Batchable<MyClass> {
    global class MyClass {
        // Whatever params you need here
    }
    global Iterable<MyClass> start(Database.BatchableContext context) {
        return (Iterable<MyClass>)JSON.deserialize(getCalloutBody(), List<MyClass>.class);
    }
    global void execute(Database.BatchableContext context, MyClass[] scope) {
        // Processing done here
   }
   global void finish(Database.BatchableContext context) {
   }
}

This works because List<X> is also an Iterable<X>.

A: You should be able to do this no problem with an Iterable. Something like:
public class MyBatch
    implements Database.Batchable<MyClass>, Iterable<MyClass>, Iterator<MyClass>
{
    Integer index;
    List<MyClass> deserializedData;
    public MyBatch()
    {
        index = 0;
        deserializedData = JSON.deserialize(/*callout*/, List<MyClass>.class);
    }
    public Iterator<MyClass> iterator()
    {
        return this;
    }
    public Boolean hasNext()
    {
        return index < deserializedData.size();
    }
    public MyClass next()
    {
        return deserializedData[index++];
    }
    public Iterable<MyClass> start(Database.BatchableContext context)
    {
        return this;
    }
    public  void  execute(Database.BatchableContext context, List<MyClass> scope)
    {
        // do stuff
    }
    public void finish(Database.BatchableContext context)
    {
        // do stuff
    }
}


text:
Q: How to ignore an error in Vanilla JavaScript I am running a Tampermonkey script on a website that I do not have the code for.
Sometimes it happens that I have a value that does not exist on the page and I get the following error:
"Cannot read property 'click' of null"
And the entire script stops. How can I tell get my script to ignore the error and just carry on to the next line of code?
Here is an example of a vanilla Javascript line that I work with:
document.querySelector('[value="xyz"]').click();

A: Only execute click() if the selector found something:
if(document.querySelector('[value="xyz"]'))
    document.querySelector('[value="xyz"]').click();

A: You can't, and you shouldn't want to: errors are bad. They're not informative, they are a signal that the code has run into an unrecoverable error and the current code path should be terminated. If you were to ignore it, and keep running, now you're in a state where any subsequent line is just as likely to also throw an error.
Either actually fix things, by making your tampermonkey script not interfere with the way the page it's running on builds its DOM, or as a last resort, you can find out which function is throwing the error for the specific page(s) you're running into this, and then _specifically for those pages, find and rebind the entire function using a try/catch, such as:
const _old_fn = window.theFunctionInvolved;
window.theFunctionInvolved = function(...args) {
    try { return _old_fn(...args); }
    catch (e) {}
};

But of course, all you've now done is moved the buck: you'll have effectively guaranteed different errors later on, with the actual cause now permanently hidden.
So really: don't do this. Fix your tampermonkey script, or stop using it altogether.


text:
Q: How can i embed my OpenSSL certificate in Firefox? How can I embed my OpenSSL certificate in Firefox? When I visit my website it shows an SSL warning, but I want to rebuild Firefox a custom release so it will not show an SSL warning how can I do that?
What do I want?
If someone is using our custom firefox build our build should not show an SSL warning of our certificates generated with OpenSSL.
Is this is possible?

A: You can do this without needing a "custom release" of Firefox. Web browsers maintain a list of certificates that should be trusted by default; many of these certificates are included with the browser when it's installed, but you can add your own. Companies often do this with their own root CA certificates, allowing certificates issued by the company to be trusted across their network.
The following instructions are specific to Mozilla Firefox 24.0 for OS X, but should apply to any recent version of Firefox on any platform.

*

*Open the Firefox preferences window. In OS X, click the Firefox menu and select Preferences...

*Click on the Advanced tab

*Click on the certificates tab

*Click the view certificates button

*Click the authorities tab

*Click the import... button

*Navigate to and select your certificate, then click Ok

*Examine the certificate to be sure it's authentic, then select the appropriate trust options (only you can determine what purposes you'll trust the certificate for) and click ok.

*Visit a site that uses the certificate to make sure it worked.
Each user will need to perform these steps on their own browser. If you really want to bundle extra certificates into your own, installable release of Firefox, you can read Mozilla's Firefox Deployment documentation on the topic.


text:
Q: How to use prefetch_related to retrieve multiple rows similar to SQL result I've a question about the usage of prefetch_related. Based on my understanding I need to use prefetch_related for reverse foreign key relationships
As an example I have a User(id, name) model and SchoolHistory(id, start_date, school_name, user_id[FK user.id]) model. A user can have multiple school history records.
If I'm querying the database using the following SQL query:
SELECT
  user.id,
  name,
  start_date,
  school_name
FROM user
INNER JOIN school_history ON school_history.user_id = user.id

the expected result would be:
| User ID      | Name   | Start Date    | School      |
| 1            | Human  | 1/1/2022      | Michigan    |
| 1            | Human  | 1/1/2021      | Wisconsin   |
| 2            | Alien  |               |             |

This is the current result that I'm getting instead with ORM and a serializer:
| User ID      | Name   | school_history
| 1            | Human  | [{start_date:1/1/2022 , school:Michigan}, {start_date:1/1/2021 , school:Wisconsin}] |
| 2            | Alien  |  []                           |

This is the ORM query that I'm using:
User.objects.prefetch_related(
  Prefetch(
    'school_history'
    query_set=SchoolHistory.objects.order_by('start_date')
  )
)

Is there a way for the ORM query to have a similar result as SQL? I want multiple rows if there are multiple schools associated with that user


text:
Q: RTI DDS reader fails to identify topic and subsequently obviously to read/take the topic. The problematic topic is published under BuiltinQosLibExp::Generic.KeepLastReliable.TransientLocal policy and the message is fired only once at the startup of the publisher application. Few things to consider:
Im not using this policy and taking the default policy configuration in code
dds::sub::qos::DataReaderQos tempQos = inSubScriber->default_datareader_qos();
m_EntitySpecReader = new dds::sub::DataReader<XXX_ICD::Entity_Specification_DT>(*inSubScriber, topicLocal, tempQos, m_EntitySpecListener);

from subscriber

*

*The problem is not Firewall or some connection issue, as I know to receive other cyclic topics without any problem.

*It is frustrating that I see this topic if Im trying to monitor either with rtiddsspy or RTI administration console.

*Last bullet and most frustrating, when I actually felt stuck, is that I have a listener configured with all available callbacks and I thought to receive if not the data at least some callback clue regarding the possible mismatch, lost, something .... but it keeps silence no matter what Im trying to do :)

Will be more than happy to understand if somebody has an answer or potential direction to check :)

A: You are using the default QoS for your DataReader. This means that its Durability policy is VOLATILE. Even though the DataWriter is configured as TRANSIENT_LOCAL, it will not deliver "old" samples to your DataReader since it is not requesting those due to its volatile durability. In this context, "old" samples are samples that were written before the DataWriter discovered the DataReader.
Things should start working as expected when you configure your DataReader with a Durability policy as TRANSIENT_LOCAL as well.
If you instrumented a Listener on the DataReader, it should show you that a match has taken place though, or that it has failed. If you implemented both the on_subscription_matched and on_requested_incompatible_qos callbacks, then at least one of those two should fire if you have both applications started and if they are able to discover each other.

Since you discovered that the problem was a type mismatch, I wanted to show how the AdminConsole tool could have helped you finding that. Reproducing your issue, this is what it showed:


text:
Q: how to calculate numeric precision and other vals from atttypmod I read the wal log from postgres (and that's all I have, can't access the tables of the database such as pg_attribute), and from relation event, I can get the atttypmod
is there a way for me to calculate the numeric precision and scale, and the chars length from that?
for chars, it seems that atttypmod == col_length+4 , is that true?
for numeric precision, it seems more complex to calculate.
I created the following table based on Where are NUMERIC precision and scale for a field found in the pg_catalog tables? , but I want to calculate these values only based on the atttypmod

numeric_precision
numeric scale
atttypmod

5
2
327686

5
1
327685

6
3
393223

4
4
262152

any ideas if / how I can do it only based on the atttypmod?
thanks, nizan

A: found that all we need is the attypmod and the type (numeric), so the code in java is
public int getNumericPrcision(int atttypmod, int atttypid){
    switch(atttypid){
      case 21:
        return 16;
      case 23:
        return 32;
      case 20:
        return 64;
      case 1700:
        if(atttypmod == -1)
          return -1;
        return  ((atttypmod - 4) >> 16) & 65535;
      case 700:
        return 24;
      case 701:
        return 53;
      default:
        return -1;
    }
  }

  public int getNumericScale(int atttypmod, int atttypid) {
    switch (atttypid) {
      case 20:
      case 21:
      case 23:
        return 0;
      case 1700:
        if(atttypmod == -1)
          return -1;
        return (atttypmod - 4) & 65535;
      default:
        return -1;

    }
  }


text:
Q: No suitable driver found for jdbc:mysql

A que otro drivers se hace referencia o bien que no estoy cargando según yo esta cargado todo correcto , ya que si lo hago por una función main esto carga correctamente

A: Debes agregar la libreria del conector:
Revisa esta respuesta
Foro. Conector Base de Datos


text:
Q: Navigating pagination with selenium I am getting stuck on a weird case of pagination.  I am scraping search results from https://cotthosting.com/NYRocklandExternal/LandRecords/protected/SrchQuickName.aspx
I have search results that fall into 4 categories.
1) There are no search results
2) There is one results page
3) There is more than one results page but less than 12 results pages
4) There are more than 12 results pages.
For case 1, that is easy, I am just passing.
results = driver.find_element_by_class_name('GridView')
if len(results)== 0:
    pass

For cases 2 and 3, I am checking if the list of links in the containing element is at least one and then click it.
else:
    results_table = bsObj.find('table', {'class':'GridView'})
    sub_tables = results_table.find_all('table')
    next_page_links = sub_tables[1].find_all('a')
    if len(next_page_links) == 0
        scrapeResults()
    else:
        scrapeResults()
        ####GO TO NEXT PAGE UNTIL THERE IS NO NEXT PAGE

Question for case 2 and 3: What could i possibly check for here as my control?
The links are hrefs to pages 2, 3, etc. But the tricky part is if I am on a current page, say page 1, how do I make sure I a going to page 2 and when  I am on page 2 how do i make sure I am going to page 3? The html for page 1 for the results list is as follows

      Page: 1
      2
      3

I can zero into this table specifically using sub_tables[1] see above bs4 code in case 2.
The problem is there is no next button that I could utilize. Nothing changes along the results pages in the html. There is nothing to isolate the current page besides the number in the span right before the links. And I would like it to stop when it reaches the last page
For case 4, the html  looks like this:

      Page: 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      ...
      Last

The last two links are ... to show that there are more results pages and Last to signify the last page. However, the `Last link exists on every page and it is only on the last page itself that it is not an active link.
Question for case 4, how could i check if the last link is clickable and use this as my stopping point?
Bigger question for case 4, how do i manouver the ... to go through other results pages? The results page list is 12 values at most. i.e. the nearest ten pages to the current page, the ... link to more pages and the Last link. So i don't know what to do if my results have say 88 pages.
I am link a dump to a full sample page : https://ghostbin.com/paste/nrb27

A: First of all you have to know what page are you at. To achieve it:
Find element with current page number, using xpath:
currentPageElement = driver.find_element(By.XPATH, '//table[./tbody/tr/td[text()='Page: ']]//span')

Then extract the number:
currentPageNumber = int(currentPageElement.text)

And then you can do anything: go to next page just adding 1 to current page number, go to last page and read the number, etc

A: What you should do is to count the number of results in a page and use the value from total results to estimate the total number of pages by dividing.
If you will inspect the page you will see: `
Displaying records 1 - 500 of 32563 at 10:08 AM ET on 9/16/2016
Knowing the total number of the page, start navigation and check that page is loaded if needed and knowing the current page you could get a dynamic selector for the page navigation number based on the page for 2 cases:

*

*if pagination number is not a link then you are on that page

*if pagination number is a link you can use it to click

You should't need 4 categories since:
- you can count the number of results and how many can be displayed on a page
- know the number of pages

*

*Create a method to navigate if needed with a for or other control structure

*For each navigation do what you need to do

Or go to the last page and start backwards until page 1 is not a link.

A: It simply worked for me.
driver.find_element_by_link_text("3").click()
driver.find_element_by_link_text("4").click()
....
driver.find_element_by_link_text("Last").click()

A: Click on the "last page" for get his numbers, and then click in each child.


text:
Q: What should I add/remove in this code, in order to receive the correct data from Dynamo and Lex? I have a lambda function that I wrote to receive data from Amazon Lex, that when triggered, will go to a DynamoDB that I have, and will query the Table for the information provided through Lex. However, at the moment I cannot get the query to work, as it doesn't show up the results I am looking for. How do I get the information gathered through lex, and match what they said to some information in Dynamo? (the dynamodb has a list of over 400 possible items they can choose from, a LOT of them are similar)
I tried a scan, and that did not work for what I need it for. It would not give the correct data that was given in the test parameter.
'use strict';

const aws = require('aws-sdk');
const dynamo = new aws.DynamoDB();

module.exports.handler = function(intentRequest, context, callback) {
  console.log(intentRequest);
  dynamo.query({
    TableName:'ServiceOfferings',
    KeyConditionExpression: '#name = :searchName',
    ExpressionAttributeNames: {
      "#name": "name",
    },
    ExpressionAttributeValues: {
      ":searchName":{"S":"PCC"} //PCC is an example of what i need searched through lex. That value needs to be dynamic.
    }
  },(err, data)=>{
    console.log(data);
    callback(err, data);
  });
};

Here is the response i receive from the test parameter:
Response:
{
  "Items": [],
  "Count": 0,
  "ScannedCount": 0
}

Request ID:
"ca1d95ce-161e-487d-8ca5-db80d5799724"

Function Logs:
START RequestId: ca1d95ce-161e-487d-8ca5-db80d5799724 Version: $LATEST
2019-10-03T14:59:00.139Z    ca1d95ce-161e-487d-8ca5-db80d5799724    INFO    { 'dialog-state': 'ReadyForFulfillment',
  'input-transcript': 'PCC',
  slots: { list: 'PCC' },
  'intent-name': 'getServiceOffering' }
2019-10-03T14:59:00.899Z    ca1d95ce-161e-487d-8ca5-db80d5799724    INFO    { Items: [], Count: 0, ScannedCount: 0 }
END RequestId: ca1d95ce-161e-487d-8ca5-db80d5799724
REPORT RequestId: ca1d95ce-161e-487d-8ca5-db80d5799724  Duration: 1034.16 ms    Billed Duration: 1100 ms    Memory Size: 128 MB Max Memory Used: 92 MB  Init Duration: 414.90 ms

A: Replace ":searchName":{"S":"PCC"} with ":searchName":"\"PCC\"" (considering the quotes of the hash key)
You also should fix the data entry on the hash key btw, leaving the ExpressionAttributeValues to ":searchName":"PCC"


text:
Q: Vector notation for a system From my notes:
Consider the following system of first order ODEs for $n$ unknown functions $y_1(t),y_2(t),...,y_n(t)$
\begin{cases} \dot{y_1}=f_1(t,y_1,...,y_n) \\ \dot{y_2}=f_2(t,y_1,...,y_n) \end{cases}
We can write this in vector notation:
$\dot{\underline{y}}=\underline{f}(t,\underline{y})$ where $\underline{y}=\begin{pmatrix}y_1\\y_2\end{pmatrix}$ and $\underline{f}=\begin{pmatrix}f_1(t,y_1,y_2)\\f_2(t,y_1,y_2)\end{pmatrix}$
Now, I can see how $\dot{\underline{y}}=\begin{pmatrix}\dot{y_1}\\\dot{y_2}\end{pmatrix}$
Please explain how $\underline{f}(t,\underline{y})=\begin{cases} f_1(t,y_1,...,y_n)\\f_2(t,y_1,...,y_n) \end{cases}$

A: You "can think of" $f_i(t,y_1,y_2)$ as $f_i(t,y)$, where $y=(y_1,y_2)^T$ with $T$ denoting transposition. This means that you should really use the function $F_i\colon\mathbb R\times \mathbb R^2\to\mathbb R$ defined by $$
F_i(t,y)=f_i(t,y_1,y_2),
$$
so that all is completely rigorous (but we never do that, too much complication).
The system
$$
\begin{cases} \dot{y_1}=f_1(t,y_1,...,y_n), \\ \dot{y_2}=f_2(t,y_1,...,y_n) \end{cases}
$$
is equivalent to
$$
\dot y=F(t,y),\quad \text{where} \ F(t,y)=\begin{pmatrix}F_1(t,y)\\F_2(t,y)\end{pmatrix}.
$$
Almost the same as in your notes, but not quite.

A: You seem to be mixing the case for arbitrary $n$ with $n=2$. For arbitrary $n$, you have equations
$$\dot{y}_1 = f_1(t,y_1, \dots, y_n)\\\dot{y}_2 = f_2(t,y_1, \dots, y_n)\\\vdots\\\dot{y}_n = f_n(t,y_1, \dots, y_n)$$
(I dropped the "cases" bracket, because these are not cases. It is just a list of related equations, and the "cases" bracket was only there because someone wanted to group them together visually.)
Also
$$\underline y :=\begin{pmatrix}y_1\\y_2\\\vdots\\y_n\end{pmatrix}$$
and we can first use this to simplify the notation for the $f_i$:
$$f_i(t, \underline y) := f_i(t, y_1, y_2, \dots, y_n)$$
And $\underline f$ is defined by
$$\underline f(t,\underline y) :=\begin{pmatrix}f_1(t, \underline y)\\f_2(t, \underline y)\\\vdots\\f_n(t, \underline y)\end{pmatrix}$$
Now,
$$\underline{\dot y} =\begin{pmatrix}\dot y_1\\\dot y_2\\\vdots\\\dot y_n\end{pmatrix} = \begin{pmatrix}f_1(t, \underline y)\\f_2(t, \underline y)\\\vdots\\f_n(t, \underline y)\end{pmatrix} = \underline f(t,\underline y)$$


text:
Q: Spring - update java classes base on XML bean definition We are using Spring 3, all of our bean declarations and property mappings are done through XML.  I've been tasked to update the java classes to use the @Resource where needed. We have a lot of classes.
We use Eclipse for the IDE.
I've never written a script to update Java code, so thought I'd ask for some suggestion on how to approach the problem.
Thanks!

A: I had a similar issue converting legacy EJB @Stateless services to Spring beans - hundreds of them and I didn't want to change all just to add @Bean or @Service annotations.
I found the component-scan util to be most useful:
<context:component-scan base-package="com.example.businessservices">
    <context:include-filter type="annotation" expression="javax.ejb.Stateless"/>
</context:component-scan>

See what other options of available for the filter type and expressions, and use one that matches your criteria to identifying your classes that need to be beans.


text:
Q: How to design C++ tree and node classes? What I have done is as below, but with this I am having a lot of problems while destructing the tree, and while trying to print the tree (basically anywhere I need to use recursion on the tree).
This is because while trying to call print recursively on the left of the right subtrees, my method breaks because my left and right subtrees are actually only Nodes and not Trees. So, I need to either typecase my Nodes to Trees or I need to create new trees, both of which are ugly solutions.
I think the problem here is with class design. Can you please comment on the same? Thanks!
class Node {
    int _data;
public:
    Node* left;       // left child
    Node* right;      // right child
    Node* p;          // parent
    Node(int data) {
        _data = data;
        left = NULL;
        right = NULL;
        p  = NULL;
    }
    ~Node() {
    }
    int d() {
        return _data;
    }
    void print() {
        std::cout << _data << std::endl;
    }
};

class Tree {
    Node* root;
public:
    Tree() {
        root = NULL;
    }
    Tree(Node* node) {
        root = node;
    }
    ~Tree() {
        delete root->left; // this is NOT RIGHT as
                           // it only deletes the node
                           // and not the whole left subtree
        delete root->right;
        delete root;
    }

    void print(int);
    void add(int);
};

A: Why don't you just allow Node to be your tree class? A non-empty node, by definition, is the root of some tree. This will substantially simplify your code since you don't need to make different cases for Tree and Node.

A: Change the destructor for Node so that it deletes its left and right children. Then for your Tree destructor just delete root, so:
~Tree() {
   delete root;
}

~Node() {
   delete left;
   delete right;
}

A: public:
~Tree() {
        clear();
        delete root;
    }

    void clear()
    {
        recursive_delete(root);
    }
private:
    void recursive_delete(Node* node)
    {
        if (node!=NULL)
        {
            recursive_delete(node->left);
            recursive_delete(node->right);
            deleteNode(node);
        }
    }
    void deleteNode(Node* node)
    {
        delete node;
        node = NULL;
    }


text:
Q: List WordPress categories and subcategories with posts Hey wonderful programmer peoples!
I have a fully functioning PHP snippet which lists categories and their posts, but we now have subcategories!
I'd like to extend the current script but at a loss where to start, my PHP knowledge is quite basic but I'm learning..
The function of the script below is to:

*

*List categories.

*List link to post within the category

    <?php
    $cat_args = array(
        'taxonomy' => 'products-category',
    );
    $categories = get_categories($cat_args);

    foreach ($categories as $category) {
        $cat_query = null;
        $args = array(
            'order' => 'ASC',
            'orderby' => 'title',
            'posts_per_page' => -1,
            'post_type' => 'products',
            'taxonomy' => 'products-category',
            'term' => $category->slug
        );

        $cat_query = new WP_Query($args);
        ?>
        <?php
        if ($cat_query->have_posts()) {
            echo "
" . $category->name;
            echo "
";
            while ($cat_query->have_posts()) {
                $cat_query->the_post();
                ?>

                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?>

                <?php
            }
            echo "

";
        }
        wp_reset_postdata();
    }
    ?>

What I'd like to achieve is:

*

*List categories.

*If category has subcategory, list subcategories.

*List link to post within the category/subcategory.

FYI: The above is used as a menu, it currently prints as shown below:

For example, I'd like to change the first menu item 'Bars' to include 'front bars' and 'back bars' (both subcategories) and then list their posts in further submenus.
Thank you in advance for your assistance and knowledge, I hope I have provided enough information! :)

A: Spent some time with a friend creating this properly, for anyone in search of this in future please see here:
https://freshlondon.biz/wordpress-menu-from-categories-subcategories-and-posts/
Here's some previews on desktop and mobile:

A: I have tried my best.
On here I just make a menu based on the category.
If the category has no subcategory means, I just listed its own post details under submenu and if it has subcategory means just listed the subcategory as a submenu and then listed the subcategories post under that subcategory.
I hope this will help you and which meets your requirement.
$category = get_categories();

foreach ($category as $value){
    $cat_id = $value->term_id;
    // Check if this category has a child category
    if(!empty(category_has_children($cat_id))){
        $subcategories = category_has_children($cat_id);?>

    <?php echo $value->cat_name;
        foreach($subcategories as $subcategory_data) {
            ?>

            <?php echo $subcategory_data->name;
                // function to list all the post details
                get_category_data_post($subcategory_data->term_id);
            ?>

<?php
        }
        ?>

    <?php
    } else{
        // Category which don't have sub category
        if($value->parent ==0) {
            ?>

                <?php echo $value->cat_name;
                    get_category_data_post($value->term_id);
                ?>

            <?php
        }
    }?>
<?php
}

function category_has_children( $term_id = 0, $taxonomy = 'category' ) {
    $children = get_categories( array(
        'child_of'      => $term_id,
        'taxonomy'      => $taxonomy,
        'hide_empty'    => false
    ) );
    return ( $children );
}

function get_category_data_post($cat_id){
    $args = array(
        'category' => $cat_id
    );
    $posts = get_posts($args);
    foreach ($posts as $val) {
        ?>

            <a href="<?php echo get_post_permalink($val->ID); ?>"><?php echo $val->post_title; ?>

        <?php
    }
}


text:
Q: Equivalent definition of bounded set in topological vector space. I want to know relation between two defination of bounded set in topological vector space : i am using defination that set A is said to be bdd in topological vector space X if it is contain in some nbhd of zero vector.nkw my question is
(1) is my definition is only true for topological vector space whose topology is metrizable(in metrizable tvs by nbhd i mean what we find by some positive radius)?
(2) if Answer of question 1 is "yes" then how it is equivalent to the definition : set A is said to be bounded if For every neighborhood V of the origin there exists a scalar s such that set A is contained in sV.
(3) in metrizable topological vector space  can we say set is bdd if it contain in some nbhd of any point rather than zero vector?
If anyone have relation between other equivalent definition then plz provide with proof.

A: If $X$ is any topological vector space then $X$ is  itself a neighborhood of $0$. According to your definition $X$ (and hence also every subset) is bounded. Whether $X$ is metrizable or nor this definition does not agree with  the usual definition.
If $X$ is a normed linear space then $A$ is bounded (according to the standard definition) if and only if $A$ is contained in  some open ball around $0$: Suppose $A$ is bounded. Then $V\equiv\{x: \|x\| <1\}$ is a neighborhood of $0$ so there exists $s>0$ such that $A\subseteq sV$. But then $A \subseteq B(0,s)$ (the open ball of radius $s$ around $0$).
Conversely, let $A \subseteq B(0,s)$. Let $V$ be any neighborhood of $0$. Then $B(0,r) \subseteq V$ for some $r>0$ (by definition of neighborhood in a metric space). But then $A \subseteq \frac s rV$.


text:
Q: Highlight the words in document in google drive I have a problem with google app script
I was uploading my files to drive using php, The file is inserting in to drive successfully. But when i want to edit my document to highlight the words using google app script I am getting error, The File Id of google drive and google docs are different, So I am unable to edit the file in google docs using app script. Please look in to my code and suggest me
I am using google docs link to edit but the file id I have with me is drive file id, So suggest me how can i get that
   function doGet(param){
            var files = DriveApp.getFilesByName('11008.doc');
            while (files.hasNext()) {
                var file = files.next();
                var url = file.getUrl();
                url = url.replace("?usp=drivesdk","");
                Logger.log(url);
                var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/18CEwLeTLwsQ_xR2BLWqs5E1lQrd9SsNuUwlnBpWLQro/edit');
                var textToHighlight = 'MA';
                var highlightStyle = {};
                highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
                var paras = doc.getParagraphs();
                var textLocation = {};
                var i;

                for (i=0; i<paras.length; ++i) {
                    textLocation = paras[i].findText(textToHighlight);
                    if (textLocation != null && textLocation.getStartOffset() != -1) {
                        textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
                    }
                }
                return doc;
            }
        }

A: Perhaps this will help:
function highLightText(txt,from) {
  var highlight={};
  highlight[DocumentApp.Attribute.BACKGROUND_COLOR]='#ff0000';
  var from=from || '';
  var txt=txt || '';
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  if(from){
    var rgel=body.findText(txt, from);
  }else{
    var rgel=body.findText(txt);
  }
  if(rgel){
    var el=rgel.getElement();
    var start=rgel.getStartOffset();
    var end=rgel.getEndOffsetInclusive();
    if(rgel.isPartial()){
      el.asText().setAttributes(start, end, highlight)
    }else{
      el.asText().setAttributes(highlight);
    }
    highLightText(txt,rgel);
  }
}


text:
Q: Indentation problems in Python when using other people's files I downloaded the source code for the famed book "Python Tkinter" by Grayson from the suggested source and loaded the first file in my Python 3.3 editor. Every line gave an indentation error. I thought it maybe a tab/indent conflict so backspaced every line then pressed enter to convert the tab to an indent – line by line and it cured the problem!
Question: Is there a way to remove tabs and convert them to indents without having to backspace then enter every line?

A: If you are using IDLE, do these:

*

*do a Ctrl+H to invoke Replace.

*Check the Regular expression

*In the Find text field, type \t

*In the Replace with text field, type four spaces

*Click replace all

You can do it with sublime very easily. Look at the lower right corner. There are two buttons, the one on the left is the one you need. Click on it. It will bring up a menu. Click "Convert Indentation to spaces" from the menu. Done!


text:
Q: React ref attribute access with name string that needed to be concatenated In React/javascript, there is a map function like this
{this.state.caseDetails.plaintiff.map((p, i)=>{
  return(
    <div className={`col-lg-${inputWidth}`}>
      <input type="hidden" ref={'plaintiff_id_' + i} value={p.id} />
      <input type='text' ref={'plaintiff_name_' + i} className='form-control' defaultValue={p.name}/>
    </div>
  )
})}

I created the attributes as above plaintiff_id_0 up to the size of array by concatenate the i variable. However, the problem now is that i would like to get the value of those data using ref, So i created a for loop like this:
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
      console.log(this.refs.("plaintiff_id_".concat(i)).value);
      //Tried this.refs.("plaintiff_id_"+i).value etc.
}

And also different kind of version to concat i to the string, but it keeps telling me that this is a syntax error, is there anyway to access these ref as i want?

A: Try this :
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
      console.log(this.refs["plaintiff_id_".concat(i)].value);
  //OR
      console.log(this.refs["plaintiff_id_" + i].value);
}

A: You can use bracket notation and do: this.refs['plaintiff_id_' + i].

A: You should be able to access the DOM element using refs as follows:
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {

  var plaintiffIdRef = "plaintiff_id_" + i;
  console.log(React.findDOMNode(this.refs[plaintiffIdRed]).value)

  var plaintiffNameRef = "plaintiff_name_" + i;
  console.log(React.findDOMNode(this.refs[plaintiffNameRef]).value)

}


text:
Q: Jaspersoft Studio NullPointer connecting to Repository I am trying to connect the new JasperSoft Studio Version 5.5 to the repository of my JasperReports Server 4.5.0. After entering all of the details and clicking test I am presented with the following Nullpointer Exception:
AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException faultSubcode: faultString:
java.lang.NullPointerException faultActor: faultNode: faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.lang.NullPointerException at
org.apache.axis.transport.http.CommonsHTTPSender.invoke(CommonsHTTPSender.java:193) at
org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at
org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at
org.apache.axis.client.AxisClient.invoke(AxisClient.java:165) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at
org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at
org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at
com.jaspersoft.ireport.jasperserver.ws.RepositorySoapBindingStub.list(RepositorySoapBindingStub.java:339) at
com.jaspersoft.ireport.jasperserver.ws.WSClient.getVersion(WSClient.java:155) at
com.jaspersoft.studio.server.protocol.soap.SoapConnection.getServerInfo(SoapConnection.java:29) at
com.jaspersoft.studio.server.protocol.soap.SoapConnection.connect(SoapConnection.java:39) at
com.jaspersoft.studio.server.protocol.ProxyConnection.connect(ProxyConnection.java:24) at
com.jaspersoft.studio.server.WSClientHelper.connect(WSClientHelper.java:63) at
com.jaspersoft.studio.server.WSClientHelper.connectGetData(WSClientHelper.java:87) at
com.jaspersoft.studio.server.ServerProvider.listServer(ServerProvider.java:329) at
com.jaspersoft.studio.server.ServerProvider.access$0(ServerProvider.java:325) at
com.jaspersoft.studio.server.ServerProvider$1.run(ServerProvider.java:278) at
org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) {http://xml.apache.org/axis/}hostname:MtwAtr1
java.lang.NullPointerException at org.apache.axis.AxisFault.makeFault(AxisFault.java:101) at
org.apache.axis.transport.http.CommonsHTTPSender.invoke(CommonsHTTPSender.java:315) at
org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at
org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at
org.apache.axis.client.AxisClient.invoke(AxisClient.java:165) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at
org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at
org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at
com.jaspersoft.ireport.jasperserver.ws.RepositorySoapBindingStub.list(RepositorySoapBindingStub.java:339) at
com.jaspersoft.ireport.jasperserver.ws.WSClient.getVersion(WSClient.java:155) at
com.jaspersoft.studio.server.protocol.soap.SoapConnection.getServerInfo(SoapConnection.java:29) at
com.jaspersoft.studio.server.protocol.soap.SoapConnection.connect(SoapConnection.java:39) at
com.jaspersoft.studio.server.protocol.ProxyConnection.connect(ProxyConnection.java:24) at
com.jaspersoft.studio.server.WSClientHelper.connect(WSClientHelper.java:63) at
com.jaspersoft.studio.server.WSClientHelper.connectGetData(WSClientHelper.java:87) at
com.jaspersoft.studio.server.ServerProvider.listServer(ServerProvider.java:329) at
com.jaspersoft.studio.server.ServerProvider.access$0(ServerProvider.java:325) at
com.jaspersoft.studio.server.ServerProvider$1.run(ServerProvider.java:278) at
org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)Caused by: java.lang.NullPointerException at
org.apache.axis.transport.http.CommonsHTTPSender.invoke(CommonsHTTPSender.java:193) ... 20 more

Does anyone know if this is a version compatibility error or simply a file I need to edit to get it to connect.
P.S I have managed to get the Jaspersoft Studio to connect to my JR Server version 5.2.0 without any errors.

A: I am not sure what is causing the error. But, you will want your versions of Studio and Server to match. Specifically, you want the JRLibrary versions to match. Otherwise you risk creating reports (in Studio) that are not supported on the server.


text:
Q: I have started getting "error -1=ffffffffffffffff Command /usr/bin/codesign failed with exit code 1" in Xcode Everything was working fine and all of a sudden I started getting below error in Xcode while building the project. I have not seen such errors before. And checked the certificates and profile all looks file. Not sure why its occurring.
error -1=ffffffffffffffff Command /usr/bin/codesign failed with exit code 1

A: Try updating your keyChain password. For that try following
If you don't know your old password, the solution is to create a new login keychain.
If you know your old password, use that password to update your existing login keychain:
Open the Keychain Access app, which is in the the Utilities folder of your Applications folder.
From the list of keychains on the left side of the window, select "login."
From the Edit menu in the menu bar, choose "Change Password for Keychain 'login.'"
Enter the old password of your user account in the Current Password field.
This is the password you were using before the password was reset.
Enter the new password of your user account in the New Password field. This is the password you're now using to log in to your Mac. Enter the same password in the Verify field.
Click OK when done, then quit Keychain Access. Quit your Xcode, reopen the project and try building your project it should work.


text:
Q: How to update multiple rows with select statement referencing same table I have a table, Salesperson, and the current name column shows the following:
Undefined - 0
Sam Brett-sbrett
Kelly Roberts-kroberts
Michael Paramore-mparamore
Alivia Lawler-alawler
Ryan Hooker-rhooker
Heather Alford-halford
Cassandra Blegen-cblegen
JD Holland-jholland
Vendor Accounts-VENDOR
Other Accounts-OTHER
Rose Johnson-rjohnson

I've developed the following query to extract the name (minus the ID on the end) with which I want to update this column:
SELECT left(salesperson_name, CHARINDEX('-', salesperson_name) - 1)
FROM Salesperson
------------------------
Undefined
Sam Brett
Kelly Roberts
Michael Paramore
Alivia Lawler
Ryan Hooker
Heather Alford
Cassandra Blegen
JD Holland
Vendor Accounts
Other Accounts
Rose Johnson

I have attempted numerous variations of the following, but get the understandable

Subquery returned more than 1 value...' error.

begin tran
update salesperson
set salesperson_name = (SELECT left(salesperson_name, CHARINDEX('-', salesperson_name) - 1)
FROM Salesperson)

A: why not a simple
update salesperson
set  salesperson_name  = left(salesperson_name, CHARINDEX('-', salesperson_name) - 1)


text:
Q: Magento 1.8 Set Product Image attributes: Base, Thumbnail, Small_Image I am creating simple product on magento programatically. Product creates successfully with image, but problems is that it does not set attributs Base, Thumbnail, Small_Image for image. What I am doing wrong here?
            //Image parameters
            $mediaArray = array('thumbnail', 'small_image', 'image');
            $img = $img_subdir.'/fimage.jpeg';

            //create new product
            $newProduct = new Mage_Catalog_Model_Product();
            $newProduct->setAttributeSetId(9)
                       ->setTypeId('simple')
                       ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
                       ->setTaxClassId(2)
                       ->setCreatedAt(strtotime('now'))
                       ->setName('test product #'.mt_rand().'')
                       ->setSku(mt_rand())
                       ->setWeight(25)
                       ->setStatus(1)
                       ->setPrice(25)
                       ->setCategoryIds(explode(',',10))
                       ->setWebsiteIds(explode(',',1))
                       ->setDescription('test')
                       ->setShortDescription('test')
                       ->setMetaTitle('test')
                       ->setMetaKeyword('test')
                       ->setMetaDescription('test')
                       ->setStockData(array(
                                             'manage_stock'=>0,
                                             'min_sale_qty'=>2,
                                             'max_sale_qty'=>10,
                                             'manage_stock'=> 1,
                                             'is_in_stock'=> 1,
                                             'qty'=> 5,))
                       ->setSetupFee(25)
                       ->addImageToMediaGallery($img, $mediaArray, false, false)
                       ->setsetupCost(25);

                       $newProduct->save();

A: Something like this before save should do it:
// Add three image sizes to media gallery
$mediaArray = array(
    'thumbnail'   => $putPathHere,
    'small_image' => $putPathHere,
    'image'       => $putPathHere,
);

foreach($mediaArray as $imageType => $fileName) {
    $newProduct->addImageToMediaGallery($filePath, $imageType, false);
}


text:
Q: Python split list on delimiter Seems to be a simple question but I tried a dozen of possibilities without result.
I just want to change ['55.00', ['CHF', '0.00']] into [['55.00'], ['CHF'], ['0.00']]
or:
var1 = "55.00"
var2 = "CHF"
var3 = "0.00"

As an example, I tried:
mik = ['55.00', ['CHF', '0.00']]
mik = [s.split(',') for s in ','.join(mik).split(',')]

Result:[['C'], ['H'], ['F'], [' '], ['0'], ['.'], ['0'], ['0']]
What could be the solution in my situation?

A: You can unpack your list. This answer assumes that you always have RHS of the format [el, [el2, el3]]
>>> var1, (var2, var3) = ['55.00', ['CHF', '0.00']]
>>> var1
'55.00'
>>> var2
'CHF'
>>> var3
'0.00'

A: mik = ['55.00', ['CHF', '0.00']]
new_lst = []

for item in mik:
    if type(item) == list:
        for x in item:
            new_lst.append(x)
        continue
    new_lst.append(item)
print(new_lst)

Simply you iterate over the list and if you found the item is itself a list you iterate over it's items and append them to your new_lst object and if it is not a list you just append it.
The output from the above code:
['55.00', 'CHF', '0.00']

A: What you want is basically to flatten your list if I understood correctly.
This question might be helpful.
from collections.abc import Iterable

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

mik = flatten(['55.00', ['CHF', '0.00']])

A: If you only have these 3 elements, you could do this:
mik = ['55.00', ['CHF', '0.00']]

mik[1:] = mik[1]

print(mik) # ['55.00', 'CHF', '0.00']

If there are multiple sublists and/or more than one level of nesting, you can use the same approach in a loop:
for i,_ in enumerate(mik):
    while isinstance(mik[i],list):
        mik[i:i+1] = mik[i]


text:
Q: Command line to return to the GUI after Ctrl-Alt-F1? I'm unable to return to the GUI with Ctrl+Alt+F7 (or any of the 12 function keys). I have some unsaved work and I don't want to lose them. Are there any other key combinations that will allow me to switch back?
Here is what I did:

*

*I pressed Ctrl+Alt+F1 and it showed a text-based login screen as usual

*Then I pressed Ctrl+Alt+F7 and it showed a screen full of text (I can't remember what they were)

*Then I pressed Ctrl+Alt+F8 and it showed log messages that resembles /var/log/messages. Some entries are from automount, some from sendmail, and none are errors.

*Pressing any of the Ctrl+Alt+Fn combinations now has no effect. The cap-lock and num-lock LED no longer respond to their corresponding keys. I can use the mouse to highlight the text on the screen, but nothing else.

Any idea what happened?
I can still login to the system via SSH. GUI applications that I was using (e.g. opera) are still running and consuming tiny amounts of CPU as usual, as reported by top. Is it possible to switch back to the GUI via the command line? If possible, I don't want to restart X, because doing so will kill all the GUI applications.
System info:
 Red Hat Enterprise Linux Client release 5.7
 Linux 2.6.18-238.12.1.el5 SMP x86_64
 gnome-desktop: 2.16.0-1.fc6
 xorg-x11-server-Xorg: 1.1.1-48.76.el5_7.5

Thanks to Shawn I was able to get back using chvt 9.
Further experiments shows that if I go to the 8th virtual terminal (either by Ctrl+Alt+F8 or chvt 8), I will not be able to switch to any other terminals using Ctrl+Alt+Fx keys. Now sure if this is a bug.

A: chvt allows you to change your virtual terminal.
From man chvt:

The command chvt N makes /dev/ttyN the foreground terminal. (The
  corresponding screen is created if it did not exist yet. To get rid of
  unused VTs, use deallocvt(1).) The key combination (Ctrl-)LeftAlt-FN
  (with N in the range 1-12) usually has a similar effect.

A: You can use Alt+F6 to return to your desktop in Fedora 26 and possibly other Wayland based Linux flavors.

A: Use the w command to find out which tty your X session uses, so you won't need to guess which Fn to press.

A: You can simply use Alt+F1 to return to your desktop.

A: Toggle function-keys pressing "F-Lock" (german "F-Umsch")
Stumpling right into the same problem, I've found the reason for - at least - my problem:
Using a ms natural 4000 keyboard sometimes requires to toggle the Function-keys pressing "F-Lock"-key located next to F12.
(Toggling the Function-Key's might help with that type of keyboard too if you don't get hardcopies etc...)


text:
Q: SQL: Insert multiple row with common columns I have a table into which i will insert and it has 4 columns.
While inserting 3 columns will be same and the other one column will be different for each and it will be taken from another table.
How could i do that?
For exmaple;
INSERT INTO sendMsg (Type,Name,SenderName,Message) values(4, 'john','Mike','Hi, blabla')
i will insert same message also for Bob, instead of john.
and the names which i will send are contained in Names table.
Thank you.

A: Use a select statement to build up your insert. Something like this could work (as you didn't provide more details):
INSERT INTO sendMsg (Type,Name,SenderName,Message)
SELECT 4, "name" ,'Mike','Hi, blabla' FROM anothertable
-- WHERE ....

Column names are in ", so don't be confused. It's to ensure difference between string and database object.
Inside optinal WHERE you could do maybe something like
WHERE name in ('Bob', 'John', ...)

or whichever algorithm you need to determine the names.


text:
Q: How to pass variables in Redirect() - But not in URL I have looked all over the internet on how to redirect to a new page on my site, while passing a variable to the new page, but behind the scenes, and not in the URL like:
www.test.com/?variable=dont.want.this.here
I don't really want to use cookies, as they seem difficult to manage, write, and read. Are there any simple solutions to do this?

A: No. There is nothing simpler than cookies for maintaining state across requests from the server.
The other option is sessions, which require a cookie to function.
Cookies are only difficult to manage if you try doing it from scratch. Find a library that will take care of it for you instead.


text:
Q: How can I alter the visible menu according to which level I am on I want to be able to alter what is visible in the menu according to which level in the site structure I am on, for example
on top level page:-
Home
Level 1 page (Current)
    -Level 2 page
-Level 2 page

-Level 2 page

Level 1 page
Level 1 page
Level 1 page
etc
on level 2 page:
Home
Level 1 page (Current page parent)
-Level 2page (Current)

     -- Level 3 page (child of current)

     -- Level 3 page (child of current)

     -- Level 3 page (child of current)

-Level 2page

-Level 2page

-Level 2page

on level 3 page
Level 1 page
-Level 2page (parent)

    --Level 3 page (current)

Is this possible and how do I do it?
Many thanks

A: First you should use the menu builder in the backend to create your menu then use the classes for the different list items to hide or display the UL nested under them. For example
li ul { display: none; }
li.current-menu-item ul { display: block; }
li.current-menu-ancestor li ul { display: none; }
li.current-menu-ancestor li.current-menu-item ul { display: block; }

you can use this logic to hide and show all different levels of menus you have based on what page you are in. You may have to play around with parent classes overriding the display style, but thats the idea. If you view source you will see the classes available to you.


text:
Q: How to order resources from a specific module? I got some trouble ordering resources from a module.
class { 'postgres' :
    charset => 'UTF8',
    locale => 'fr_FR',
    require => Service['postgresqld'],
}->
class { 'postgresql::server':
}

postgresql::role { 'role1' :
    namevar => 'redmine',
    password_hash => 'random_md5',
    createdb => true,
    require => Class['postgres'],
}

postgresql::database_user {'charly':
    password => 'random',
    role => 'redmine',
    require => postgresql::role['role1'],
}

I want to order this, but it appears to have a syntax error on the last line at role.
I'm pretty sure it comes from the capitalized first letter. But Puppet doesn't want to run the manifest if I put a capital letter Postgresql::role['role1] or postgresql::Role['role1]. Without capital letter, I "just" get a warning :

warning: Deprecation notice:  Resource references should now be capitalized on line 61 in file /home/charly/testManifests/part1.pp

I'm doing something wrong, but I don't know what. I searched for an answer on the Internet but can't find what I want neither in tutorials nor on the forums.

A: Try using chaining arrows to your resource group references e.g.
Class['postgres'] -> Class['postgresql::server']

class { 'postgres' :
   charset => 'UTF8',
   locale  => 'fr_FR',
   require => Service['postgresqld']
}

class { 'postgresql::server': }

More detail can be found here in the puppet reference Chaining Arrows


text:
Q: Multi selection didn't get all records , all records didn't load before select [ExtensionOf(formControlStr(BankReconciliation ,ClearALL))]
 final class ClearAll_Extension
{

    void clicked()
    {

        next clicked();

        FormRun formrunn = this.FormRun();

        FormCheckBoxControl BankAccountTrans_Included = formrunn.design().controlName("BankAccountTrans_Included");

        FormDataSource BankAccountTran = formrunn.dataSource("BankAccountTrans");

        BankAccountTrans Bankacc  ;

        int  recordsCount ;

        recordsCount= BankAccountTran.recordsMarked().lastIndex();  // Total no of marked records.

        if (BankAccountTran.cursor().RecId != BankAccountTran.getFirst().RecId)
        {
            BankAccountTran.cursor(BankAccountTran.first());
        }

        for (Bankacc = BankAccountTran.getFirst(true) ? BankAccountTran.getFirst(true) : BankAccountTran.cursor(); Bankacc; Bankacc = BankAccountTran.getNext())
        {
            PurchTable_ds.findRecord(Bankacc);

        }

            if (Bankacc.Included == NoYes::No)
            {
                BankAccountTran.object(fieldNum(BankAccountTrans,Included)).setValue(NoYes::Yes) ;
                BankAccountTran.write();

            }
            recordsCount-- ;
            if (recordsCount == 0 || BankAccountTran.next() == 0)
            {
                BankAccountTran.research();
                BankAccountTran.reread();
                BankAccountTran.refresh();
                break;
            }
        }
    }

}

this code run successfully on small data but in a large data it is not running well because when we open the form and clicked select all not all data be loaded method run in some of records that loaded in first time but the other the method didn't run on it because it can't see all reocords , how to make multiselect get all records and run methods on all of them ? , or how to make all records load first and then select ?


text:
Q: Java Repaint a single image I'm drawing many bufferedImage's onto a JFrame using the paint() method,
public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(bufferedImg, x, y, layeredPane);
        ...More images
    }

The problem is it repaints all of the images and so the screen will go blank, then, display the images. I need to repaint a single image, not everything in the paint method.
So I tried making another method separate then the paint method and just call that..
public void drawImage(){
    Graphics2D g2d = (Graphics2D) getGraphics();

    if (condition == true) g2d.drawImage(bufferedImg, x, y, layeredPane);
}

And this works to draw the image, but once the boolean is set to false and called, it still keeps the images on the screen.
Sorry if this has been posted before, I seen quite a few posts about repainting images in Java, but I couldn't find one that specifically repaints a single image.

A: *

*If your program is a Swing program, then you should not override paint but rather paintComponent(...) of a JComponent derived class.

*You can limit the location of the repainted area by calling repaint(Rectangle r), with the Rectangle's bounds being that of the area that you want changed.

*You should not get a Graphics context by calling getGraphics() on a component as this will give you a short-lived Graphics object only, and anything drawn with it will be lost in a repaint.

*If many of your images don't change, if they act as a background, consider drawing them to one background BufferedImage, and then drawing that one in your paintComponent(...) method.

For more help, consider creating and posting a minimal, compilable, runnable example program.

Edit
Regarding your new post:

I'm drawing many bufferedImage's onto a JFrame using the paint() method

No, never draw directly into the JFrame as you lose many of the benefits of Swing graphics including double buffering, and risk messing up the drawing of borders and child components. You will want to read the Swing custom painting tutorial to learn more on how to draw correctly.


text:
Q: Apply formula for rows with first occurence of text I want to achieve something like the image below:

How can I do it?

A: use this formula:
=ARRAYFORMULA(IF(COUNTIFS(A:A, A:A, ROW(A:A), "<="&ROW(A:A))=1,
 "first occurance", ))

A: Looks like this normal Excel formula works just fine.
Assuming your data starts from cell A1, insert following formula
=IF(COUNTIF($A$1:A1,A1)=1,"First Occurrence","")
Then copy down as much as you need.


text:
Q: Inherit prop-types when a component was rendered through props Is there a way to inherit prop-types, when a component was rendered through parents prop? Assuming, we don't have access directly to 'ChildProps' and 'Props' interface?
Parent component
interface ChildProps {
  counter: number;
  setCounter: React.Dispatch<React.SetStateAction<number>>;
}

interface Props {
  child: React.ElementType<ChildProps>;
}

function Parent({ child: Child }: Props) {
  const [counter, setCounter] = React.useState(0);

  return (

      <Child counter={ counter } setCounter={ setCounter } />

  );
}

Child component
function Child(props) {
  return (

      // 'counter' is missing in props validation eslint(react/prop-types)

{ props.counter }

      // 'setCounter' is missing in props validation eslint(react/prop-types)
      <button onClick={ () => props.setCounter(props.counter + 1) }>
        inc
      </button>

  );
}

A: Jack,
In React, you shouldn't really extend / inherit from classes other than React.Component, it's the only convention we follow in React to write components.
Functional composition is how we do abstractions with, like: writing a HOC to give certain kind of methods or properties to anyother component.
const withAdditionalProps = (someProps) => WrappedComponent => (
  class NewWrappedComponent extends React.Component {
    givenMethod = () => { /* some algorithm */ }

    render(){
      const newProps = { ...this.props, givenMethod: this.givenMethod  }
      return (
        <WrappedComponent {...newProps}>
          {this.props.children}
        </WrappedComponent>
      );
    };
  }
);

I hope that, or some of it make sense.


text:
Q: Pass Function with Parameter-Defined Behavior in Java In Java, I want to define a normalizing function that takes one number as input but whose behavior is defined by multiple parameters.
Essentially, the Java equivalent of this in Lisp:
(define (normalizeVal min max floor ceiling)
  (lambda (x) (/ (* (- ceiling floor) (- x min)) (+ (- max min) floor))))

In pseudo-code, I'd like to:
function parsing(data, normalizeValFunc) {
   for (datum in data):
      normalizeValFunc(datum);
}

var input = userData;
var min, max, floor, ceiling = /* Calculate min, max, floor, and ceiling */
var output = parsing(input, normalizeValFunc(min, max, floor, ceiling));

Passing functions as parameters in Java can be tricky because functions are not first class objects in Java. (Maybe Java 8 Lambda expressions changes this?) Other questions address the issue of passing functions as parameters in Java, such as How to pass a function as a parameter in Java?, What's the nearest substitute for a function pointer in Java?, and Function Pointers in Java
However, none of these questions concern passing a function whose behavior is defined by parameters other than the function's input value. I don't know in advance what the min, max, floor, and ceiling parameters of the normalization function will be, but I only want the effective normalizing function to take one argument, the value to be normalized.

A: The old-fashioned way of doing this is with an interface:
public interface Normalizer {
    int normalize(int value);
}

You would then create an instance of a Normalizer, e.g. with an anonymous class:
public static Normalizer normalizeValFunc(final int min, final int max, final int floor, final int ceiling) {
    return new Normalizer() {
        @Override public int normalize(int value) {
            /* Use min, max, floor, ceiling & value here to return something. */
        }
    };
}

Then you can write a function that takes a Normalizer:
void parsing(int[] data, Normalizer normalizer) {
  // Call normalizer.normalize(...)
}

And call it like this:
parsing(/* something here */, normalizeValFunc(min, max, floor, ceiling))

In Java 8, you can avoid the anonymous class and just use a lambda instead:
public static normalizeValFunc(final int min, final int max, final int floor, final int ceiling) {
    return value -> /* Use min, max, floor, ceiling & value here to return something. */
}

You may as well do this inline:
parsing(/* something here */, value -> /* an expression using min, max, floor, ceiling, value */)

Also, rather than define a Normalizer, you can just use the standard IntUnaryOperator functional interface (and call applyAsInt instead of normalize).


text:
Q: Разные версии ноды под рутом и юзером? Под root показывает node -v версию 6... под юзером node -v показываерт версию 0.4... Из-за чего это и как это устанить?

A: У вас небось две версии ноды, одна /usr/bin/node, другая /usr/local/bin/node.
Обычный юзер использует /usr/local/bin/node, под рутом /usr/bin/node.
По-хорошему, надо удалить /usr/local/bin/node.


text:
Q: MySQL Trigger after insert Are MySQL AFTER INSERT triggers always being executed directly after the INSERT statement, or is it possible that 2 inserts occur and after that 2 triggers occur?
I'm writing this trigger namely:
CREATE DEFINER=`p28004_bf4`@`localhost` TRIGGER `setId`
AFTER INSERT ON `playerkills`
FOR EACH ROW
    BEGIN
        INSERT INTO globals () VALUES();
        UPDATE playerkills SET globalId = LAST_INSERT_ID() WHERE id = ROW.id;
    END

And I'm worried about what will happen if the insert statements somehow get interleaved, the globalId must always be consistent, like a global unique identifier accross multiple tables.
Globals table:

*

*id (Primary Key, Int, Auto Increment)

Playerkills table:

*

*id (Primary Key, int, Auto increment)

*globalId (Key, Int)

*etc.

A: Ultimately it doesn't matter what order concurrent commands run in this case. The LAST_INSERT_ID function is smart enough not to give you the ID inserted by a someone else's concurrent query.
As a relatively simple example, I opened two mysql sessions and created a table called globals with an autoincrement primary key, then alternated back and forth typing these commands.
    ## Session 1 ##                              ## Session 2 ##

mysql> INSERT INTO globals () VALUES ();
Query OK, 1 row affected (0.00 sec)

                                       mysql> INSERT INTO globals () VALUES ();
                                       Query OK, 1 row affected (0.00 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

                                       mysql> SELECT LAST_INSERT_ID();
                                       +------------------+
                                       | LAST_INSERT_ID() |
                                       +------------------+
                                       |                2 |
                                       +------------------+
                                       1 row in set (0.00 sec)


text:
Q: I want to see the full git history of the recovered file after it was removed from Intellij see this:

*

*Add file A.java.

*Remove file A.java.

*Add File A.java.

*Click file A.java's show history in Intellij

*I only see a third commit from A.java

Can I see all history of A.java file in Intellij?
In Git-bash and Eclipse(STS), I can see all the history I want.
Please help me.

A: I asked the same question to JetBrains, an Intellij developer, who told me it was a duplicate issue.
The issue is currently registered as a major issue in jetBrains and seems to be resolved in the Intellij 2017.1 version.
jetBrains issue link


text:
Q: Make karate to throw error when there is null result from jsonPath expression Json:
    def a = {
    "list1":[
        {
            "key":[]
        },
        {
            "key":[]
        }
    ],
    "list2":[
        {
            "key":[]
        },
        {
            "key":[]
        }
    ]

 }

Now for this jsonPath expression will be $..key it throws null result
If i try from karate And match each a..key == ${someexpectedvalue} since the array doesn't meets the expected result it should throw error but now it is getting passed


text:
Q: Validating object coming from the form params in the state machine before transition to certain state I'm using pluginaweek / state_machine gem
I need to validate object coming from form submitted by a user, but only before transition to a  certain state. Other states doesnt need validation.
I've got:
class Invoice < ActiveRecord::Base

  state_machine :state, :initial => :draft do
    before_transition :draft => :emited, :do => :check_date

    state :emited
    state :draft
  end

  def check_date
   if params[:date] < Time.now
     false
   end
  end

end

But params hash isn't available in the model. Is there a way to do what I need?

A: class Invoice < ActiveRecord::Base
  state_machine :state, :initial => :draft do
    state :draft

    state :emited do
      validate :validate_date
    end
  end

  def validate_date
    errors.add(:date, "in invalid") if params[:date] < Time.now
  end
end

Hope this helps


text:
Q: ¿Cómo encontrar un Objeto dentro de un arreglo, dada una Key y un valor? JavaScript Tengo un arreglo lleno de objetos cuyos atributos son desconocidos, me dan una key (el nombre de esta misma) y un valor para esta key. ¿Como puedo encontrar el objeto haciendo uso de dicha key?.

A: puedes usar tanto filter() como find() dependiendo de lo que quieras obtener, una lista de coincidencias o el primer objeto,
[].filter(element => element["tu_key"] ==  tu_value);
// retorna []
[].find(element => element["tu_key"] ==  tu_value);
// retorna {}


text:
Q: Linux - How to change default application for text files with custom extensions? I do some creative writing and use PyRoom for most of my drafts. I want to save my drafts with a custom extension story(i.e. Persuasion.story) and associate story extension to PyRoom. I want to, however, open the other text streams with GEdit as usual.
Changing extension and setting PyRoom as default application for that extension doesn't work because it detects the mime type as plain text. So if I set PyRoom as the default application for opening Persuasion.story, it will open the other text files in PyRoom as well. Which I don't want.
I tried adding text/story=pyroom.desktop to my ~/.local/applications/mimeapps.list as well. It didn't work. The file still opens in GEdit.
How do I change the default application for a file with a certain extension?


text:
Q: how to have two independent views? is it posible to have navigationcontroller view and a subview on it (or independent view) which not moves when navigationcontroller is pushed or poped? Both views responds to user interaction.

A: Yes, using container view controllers this is absolutely possible.

*

*Create a custom container view controller and add a subview (the view that should not move)

*Instantiate UINavigationController and add it as a child view controller (using addChildViewController:)  of the container view controller from step 1

*Attach UINavigationControllers's view below the subview you added in step 1

After that, you're done.


text:
Q: How to define a pointer to a class member function Related to C++ Basics.
I am creating a singly linked list.
class Linked_List
{
public: Linked_List();
    ~Linked_List();
        //Member Functions
    struct node* getHead(void);
private:
    struct node{
        int d;
        struct node* next;
    }*head;
};
struct node (Linked_List::*getHead)(void)
{
    return head;
}

I am getting this error:

"error C2470: 'getHead' : looks like a function definition, but there is no parameter list; skipping apparent body".

I tried to search in google but of no use. Any suggestions plz.

A: You don't need a pointer to member function, you just want to provide a definition for that function:
Linked_List::node* Linked_List::getHead()
{
    return head;
}

Also notice, that the struct keyword is unnecessary in the function definition, while you have to qualify the name of the struct node with the name of the class in the scope of which it is defined.
Also, the void keyword to specify an empty argument list is unnecessary. I therefore suggest you to rewrite the class definition as follows:
class Linked_List
{
private:
    struct node
    {
        int d;
        struct node* next;
    };
    node *head;
public:
    Linked_List();
    ~Linked_List();
    node* getHead();
};


text:
Q: Grabing text using Selenium/XPath/Python I want to grep the total number of deaths from the Johns Hopkins Covid dashboard. I want to do this using Selenium, Python and Selenium's chrome driver. The number of deaths can be found under the path //*[@id="ember1915"]/svg/g[2]/svg/text.

This is my script:
from selenium.webdriver import Chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

with Chrome() as driver:
    driver.get('https://coronavirus.jhu.edu/map.html')
    driver.implicitly_wait(20) # Waits for 20 s for the entire page to loads.

    diplayElement = driver.find_element_by_xpath('//*[@id="ember1915"]/svg/g[2]/svg/text')

It fails with the error "no such element:
Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1915"]/svg/g[2]/svg/text"}".

This also happens for other sites I'm trying to scrape.
How can I fix this? What's the reason for this error?

A: The element with the total number of deaths i.e. 905,181 from the Johns Hopkins Covid dashboard is within an <iframe> so you have to:

*

*Induce WebDriverWait for the desired frame to be available and switch to it.

*Induce WebDriverWait for visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using XPATH and get_attribute():
driver.get('https://coronavirus.jhu.edu/map.html')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE']")))
print(WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, "//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg' and @class='responsive-text-group']//*[name()='g' and @class='responsive-text-label']/*[name()='svg']/*[name()='text']"))).get_attribute("innerHTML"))

*Using XPATH and text attribute:
driver.get('https://coronavirus.jhu.edu/map.html')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE']")))
print(WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, "//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg']//*[name()='g']/*[name()='svg']/*[name()='text']"))).text)

*Console Output:
905,181

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python

Reference
You can find a couple of relevant discussions in:

*

*Ways to deal with #document under iframe

*Switch to an iframe through Selenium and python

*Ways to deal with #document under iframe

*Switch to an iframe through Selenium and python


text:
Q: Activity has leaked window while using PiP My app shows video streaming using exoplayer. All works ok until i use/activate Pip. After i put any video in Pip and go back to prev activity from backstack ( automatically ) when i press any button i get :
WindowManager: android.view.WindowLeaked: Activity com.rcsrds.player.ui.main.MainActivity has leaked window DecorView@ff7d496[] that was originally added here
i get this error message on some of my test phone, not all. If i press more than 1 time any button after 5 sec i get ANR (sometimes) ; My app does not use any dialog
I do have a ProgressBar. Comment it and error still appears.
LE : my player is a customview. This should be a problem for PiP ?
to enter in Pip i use
   public void enterPictureInPicture(PictureInPictureParams nPipParams) {
       ActivityUtils.hideSystemUI(this.getWindow());
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           enterPictureInPictureMode(nPipParams);
       } else {
           //Toast.makeText(this,"Picture in Picture not availabe",Toast.LENGTH_LONG).show();
       }
   }

<activity
           android:name=".ui.main.MainActivity"
           android:configChanges="screenSize|smallestScreenSize|screenLayout"
           android:supportsPictureInPicture="true"
           android:excludeFromRecents="true"
           android:autoRemoveFromRecents="true"
          />

A: You're missing android:configChanges orientation as recommended by:
https://developer.android.com/guide/topics/ui/picture-in-picture#declaring
The full list should be.
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
PIP doesn't support having the Activity destroy.
Your Activity is getting destroyed because it's running in portrait and entering PIP switches it to landscape.
Perhaps the other times you tested the device was already in landscape.


text:
Q: Database: SQL Pagination - How many pages? I'm using MySQL LIMIT to display 50 rows (pages) at a time, like so:
SELECT cols
FROM table
LIMIT 49, 50

What's the most efficient way for me to determine how many "pages" I have in my result set (how many total records my query is producing)?
Before I run the code above, should I just run a quick and dirty:
SELECT COUNT(cols)
FROM table

to determine the # of rows in my result set?
(This seems kind of inefficient to run 2 queries to do this)

A: You can use FOUND_ROWS() function:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

A: i think you are over optimizing. The only thing you can do to optimize the pagination process that i can think of is to keep the count in session, so you only do it once during page navigation, bad part it will be bad if new items are added during pagination.

A: One possibility (which might only work with some databases) is to peek inside the query plan to see what the optimizer is forecasting as a total row count. For example, in Oracle you can access the EXPLAIN plan and see that the optimizer estimates that, say, x rows are going to be returned in total. The accuracy of this of course depends on a number of factors: how appropriately the tables are indexed, how non-stale the statistics are etc.etc.


text:
Q: Abelian subgroup in the symmetric group
Let $p$ be a prime number. Show that there is an abelian subgroup $P$ of order $p^p$ in $S_{p^2}$ such that every element in $S_{p^2}$ that isn't in $P$ does not commute with every element in $P$.

I've tries using sylow theorems first theorem to show that there is a p-sylow subgroup $Q$ in $S_{p^2}$ with order $p^{(p+1)}$ and it has a subgroup of order $p^p$ because it is a p-group. I would like a hint on how to show that $P$ is abelian.

A: Start with the set $\{1,\dots,p^2\}$ on which $S_{p^2}$ acts, and partition it into $p$ blocks of cardinality $p$ each. Think of the elements of each block as being arranged in a cycle of length $p$.  Let $P$ consist of those permutations in $S_{p^2}$ that map each block to itself and preserve the cyclic ordering within each block.  That group is abelian because it's isomorphic to the direct product of $p$ copies of the cyclic group of order $p$.
Also, if an element $g\in S_{p^2}$ commutes with all the permutations in $P$, then it is fairly easy to see that $g\in P$.  Indeed, if $g$ moved an element of one block into a different block, then it would fail to commute with a permutation in $P$ that fixes the elements of the former block and mover the elements of the latter.  And if $g\in S_{p^2}$ moved the elements in some block in a way that doesn't respect the cyclic order there, then it would fail to commute with any element of $P$ that moves the elements of that block.


text:
Q: Combining Rows in MS Access SQL Query Below I have a screenshot of a query in MS Access. I am trying to combine the two "Kim Wong" rows into one row that has one time range in the Monday column and the other time range in the Tuesday column. There will when done have time ranges in each of the cells.

Here is what the query looks like.

And here is the actual code
SELECT qryEmployed.EmployeeName, First(IIf([EventDate]=DateAdd("d",0,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Monday, First(IIf([EventDate]=DateAdd("d",1,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Tuesday, First(IIf([EventDate]=DateAdd("d",2,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Wednesday, First(IIf([EventDate]=DateAdd("d",3,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Thursday, First(IIf([EventDate]=DateAdd("d",4,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Friday, First(IIf([EventDate]=DateAdd("d",5,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Saturday, First(IIf([EventDate]=DateAdd("d",6,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Sunday
FROM tblEvents INNER JOIN qryEmployed ON tblEvents.Employee = qryEmployed.EmployeeName
GROUP BY qryEmployed.EmployeeName, qryEmployed.Position, tblEvents.Event, tblEvents.EventDate, tblEvents.StartTime, tblEvents.EndTime, tblEvents.Lunch, IIf([Event]="Scheduled",((IIf([EndTime]<[StartTime],1,0)+[EndTime])-[StartTime]-IIf([Lunch],1/48,0))*24,0)
HAVING (((tblEvents.EventDate)=DateAdd("d",0,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",1,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",2,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",3,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",4,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",5,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",6,[Forms]![tblEvents]![tbxDate])));

Here is a sample of tblEmployees.

Here is the qryEmployed.

And here is the tblEvents.

A: It's a little hard to tell based on all the gunk that access is throwing in your actual sql, but I believe that you are getting this issue because you are starting your query with the Event table and then joining into the qryEmployed table.  Joining in that fashion is creating two rows because Kim Wong is assigned to two different events, hence her name gets entered onto two different rows.  You need to drop the Event column from your table as a start, that will likely fix it.
If you could show the whole table returned or at least the query tables it would go a long way in helping further diagnose what to change.

A: I agree with hdizzle, your query is incredibly hard to read because it seems it was generated from the MS Access GUI. I highly suggest you avoid the GUI and learn SQL syntax directly.
Your query is essentially aggregating among multiple values that return if the individual has a value for each day. You need to 'group by' all returned columns that are not being aggregated.
I re-formatted the query a bit and I removed all of the extraneous GROUP BY clauses that I don't believe do anything. Then I added an aggregate clause to each 'DayOfTheWeek' return column. The query below should return the time an event occurred for the individual if an event occurred or it should return a blank. If multiple events occurred, it would return the last one alphabetically (you never explained how you wanted that scenario to be handled).
Further, you are linking on the name field, I highly suggest you link on an ID field. Names change relatively often and I am fairly sure linking on an integer has better performance.
Try something like
SELECT qryEmployed.EmployeeName,
MAX(First(
    IIf(EventDate)]=DateAdd("d",0,[Forms]![tblEvents]![tbxDate]), IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Monday,
MAX(First(
    IIf([EventDate]=DateAdd("d",1,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Tuesday,
MAX(First(
    IIf([EventDate]=DateAdd("d",2,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Wednesday,
MAX(First(
    IIf([EventDate]=DateAdd("d",3,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Thursday,
MAX(First(
    IIf([EventDate]=DateAdd("d",4,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Friday,
MAX(First(
    IIf([EventDate]=DateAdd("d",5,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Saturday,
MAX(First(
    IIf([EventDate]=DateAdd("d",6,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")
)) AS Sunday
FROM tblEvents INNER JOIN qryEmployed ON tblEvents.Employee = qryEmployed.EmployeeName
GROUP BY
qryEmployed.EmployeeName


text:
Q: Iterating through multidimensional array to output the contents in an inner array in PHP Despite trying days long I can't get to output the "titles" stored in an array($innerresult) within the array ($SortedResult). I need to be able to access all the elements in $innerresult so that I can display them in the sidemenu on the view(Side menu are nothing but all the titles falling under a category ex: PHP). Any idea/modifications to my code below are most welcome.
$this->db->select('*');
$this->db->from('crd_article_desc');
$this->db->where('article_id', $CurrentTitleId);
$query = $this->db->get();
$result=$query->result_array(); //return fetched data

foreach($result as $value){

    $this->db->select('article_title');
    $this->db->from('crd_article_desc');
    $this->db->where('article_category', $value['article_category']);
    $innerquery = $this->db->get();
    $innerresult=$innerquery->result_array();
    $SortedResult[$value['article_category']][] =    array($innerresult,$value['article_desc']);
}
return ($query->num_rows() > 0)?$SortedResult:FALSE;
}

Below is how I am trying to access the array in my view
if(isset($res)){
    foreach($res as $ArticleCategory=>$title)
{
?>

<?php echo $ArticleCategory; ?>

<?php
    foreach($title as $articletitle) {
        $new_friendly_url = friendly_seo_string($articletitle['0']);
?>
        <a target="_top" href="<?php echo base_url();?>
<?php
        echo   $new_friendly_url;
?>
    ">
<?php
    echo $articletitle['0'];
?>

<?php
    }
}
}

The array
Array (
    [PHP] => Array (
        [0] => Array (
            [0] => Array (
                [0] => Array (
                    [article_title] => Variables
                    )
                [1] => Array (
                    [article_title] => arrays
                    )
                [2] => Array (
                    [article_title] => operators
                    )
                [3] => Array (
                    [article_title] => loops
                    )
                [4] => Array (
                    [article_title] => recursive
                    )
            ) [1] => This is article 1003
        )
    )
)

A: You seem to have created some unnecessary levels in that array, but this should list the Titles
foreach ( $SortedResult['PHP'][0][0] as $article )
    echo $article['article_title'];
}

And this should list the Category name as well as the title
foreach ( $SortedResult as $catName => $inner ){

    foreach( $inner[0][0] as $article){
        echo $catName . ' - ' . $article['article_title'] . '
';
    }
}

Result:
PHP - Variables
PHP - arrays
PHP - operators
PHP - loops


text:
Q: unresolved external symbol - calling static function from other project I have solution with two projects- proj_1, proj_2.
proj_1 is lib project and proj_2 is regular project
in proj_2 I have function named static void proj_2_func().
Im trying to call that function from proj_1 (without creating an object) but I get linkage error- unresolved external symbol.
proj_2:

class proj_2_class
{
  public:
   static void proj_2_func();  //the implementation is not relevant
}

proj_1:

in cpp file:

#include proj_2_class.h  // I added the path to "additional include files" in proj_1

void proj_1_class::proj_1_func()
{
  proj_2_class::proj_2_func();
}

Ill be happy for guidance on that error.
thanks.

A: Because your function proj_1_class::proj_1_func calls the function proj_2_class::proj_2_func, the latter needs to have an implementation provided somewhere - failing to do so is what causes the linker error


text:
Q: Problem with linespace and parskip and font size I am writing a thesis template with properties like word template.

in MS Wors: Font size=14pt, linespace=1.2, space before chapter/section/subsection title = 30pt/27pt/20pt.

What I have done so far is:

*

*After loading extbook.cls with fontsize=14pt I set \setlength{\p@}{1bp}. (like 14pt in word)

*Then, in the end of template I set \renewcommand\baselinestretch{1.23429} (=1.2 in word)

*Then I changed \parskip to a bit more than \baselinestretch (I don't know the exact value of \parskip in word but it seems it is a bit more than \baselinestretch).

I am sure (mostly) that the second change of \baselinestretch is exactly equal to its analogous in word. (by comparing its outputs). But

Q1: why after setting \setlength{\p@}{1bp}, \baselinestretch{1.2} isn't equal to its analogous in word?
Q2: How to prevent other changes (except paragraph skip) that has been defined by old parskip like space after sections?

\documentclass[14pt,a4paper]{extbook}

\usepackage{lipsum}
\makeatletter
\setlength{\p@}{1bp}
\makeatother

\setlength{\parskip}{1.2\baselineskip}
\renewcommand\baselinestretch{1.23429}
\begin{document}
\tableofcontents
\chapter{First Chapter} \pagebreak
\section{First Section}
\lipsum[1-2]
\subsection{First Subsection}
\chapter{Second Chapter} \pagebreak
\section{Second Section}
\lipsum[1-2]
\subsection{Second Subsection}
\lipsum[1-2]
\end{document}


text:
Q: Branding above navbar Bootstrap 3 It's been a long time since I've worked on any web projects and even longer since I've built something from scratch so I'm very new to CSS grid systems such as the one included in Bootstrap 3. I'm building a website and perhaps the largest part of the challenge is learning to think in terms of the mobile first grid system.
I'm working on a header that works in much the same way as the header on the New Yorker webzine or to put it descriptively it is fixed width, has a site branding (image) centred above a navbar on medium and large devices. Below medium the navbar collapses and moves to the same row as the branding (on the far-left) and the search icon moves to the far-right on the same row. So to visualise:
Medium/Large Devices:
    BRANDING
NAVBAR - SEARCH

Small/Extra Small Devices:
NAVBAR(COLLAPSED) - BRANDING - SEARCH

I'm not so much interested in having my hand held where the code is concerned, but a description of how that can be achieved using the B3 grid system.
Thank you in advance for your help.

A: Flexbox will be your bestfriend for this.
However for Bootsrap you can reorder columns using classes like .col-md-push-* and .col-md-pull-* to shift a column to the right or left, respectively. This would become relevant in your media queries (pulling the brand column into the middle) to achieve what you're looking for :)
For an intro to Flexbox I recommend:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
http://flexbox.io/view/qWL-7ih9Kw0
For a great overview of the bootstrap grid system check this out:
http://www.sitepoint.com/understanding-bootstrap-grid-system/


text:
Q: The connection between the length of Fibonacci $p$-step numbers and it's limit values One of the most important generalization of the classical Fibonacci numbers is the Fibonacci $p$-step numbers that is defined as follows
\begin{equation}\label{cp26}
 F_n^{(p)}=F_{n-1}^{(p)}+F_{n-2}^{(p)}+\cdots+F_{n-p}^{(p)}\, .
 \end{equation}
With boundary conditions
$$F_{0}^{(p)}=0\quad ,  \quad F_{1}^{(p)}=0\quad ,\, \cdots\, ,\quad F_{p-2}^{(p)}=0\quad , \quad F_{p-1}^{(p)}=1\, .$$
We can get the limit value of Fibonacci $p$-step numbers by inverse of solution of equation $x^{p+1}-2\, x+1=0$ in
the interval $(0,1)$.
  We denote the limit value of Fibonacci $p$-step numbers with $\alpha_p$. In fact, $\alpha_p$ is defined in the following form
  $$
\alpha_p=\displaystyle{\lim_{n\rightarrow\infty}}\quad \frac{F^{(p)}_{n+1}}{F^{(p)}_{n}}~.
  $$
We denote the length of $ F_n^{(p)}$ number with $L_n^{(p)}$. For example,  $ F_{10}^{(2)}=55$ therefore $L_{10}^{(2)}=2$.
  With simulation, I found the following connection between the length of Fibonacci $p$-step numbers and it's limit values
$$
\mid \frac{F^{(p)}_{n+1}}{F^{(p)}_{n}}-\alpha_p\mid \, \approx \,  10^{-{\displaystyle{L_n^{(p)}(\frac{p}{p-1})}}}~.
$$
I make some examples to clarify what i mean. For $p=2$, the Fibonacci $2$-step number is the classical Fibonacci number.
The limit value of the Fibonacci $2$-step number is inverse of solution of equation $x^3-2\, x+1=0$ in
the interval $(0,1)$.
so, for $p=2$, the limit value is
\begin{eqnarray}
\alpha_2= \frac{1}{0.61803398874989484820458683436563811772030917980580}& &  \\
& & \\
= 1.6180339887498948482045868343656381177203091798058~.& &
\end{eqnarray}
The length of $F_{72}^{(2)}$ and $ F_{73}^{(2)}$ are $15$. With calculation, we have the following relation
$$
\mid \frac{F^{(2)}_{73}}{F^{(2)}_{72}}-\alpha_2\mid=
\mid \frac{ 806515533049393}{ 498454011879264}-\alpha_2\mid
 \, \approx \,  10^{-30}~.
$$
For $p=3$, the Fibonacci $3$-step number is called Tribonacci number.
The limit value of the Fibonacci $3$-step number is  inverse of solution of equation $x^4-2\, x+1=0$ in
the interval $(0,1)$.
\begin{eqnarray}
\alpha_3= &1.8392867552141611325518525646532866004241787460975 & \\
& 92246778758639404203222081966425738435419428307014& ~.
\end{eqnarray}
The length of $F_{113}^{(3)}$ and $ F_{114}^{(3)}$ are $30$. With calculation, we have the following relation
$$
\mid \frac{F^{(3)}_{114}}{F^{(3)}_{113}}-\alpha_3\mid=
\mid \frac{270409000010299937423541789777}{ 147018402238651639664609196920}-\alpha_3\mid
 \, \approx \,  10^{-45}~.
$$
Is there a analytical method that we can proof the mentioned formula.  I would greatly appreciate for any suggestions.