text:
Q: App crashes in 2.2 after adding support library in (ActionBar) For making my app compatible down to api 2.2, I added appcompat_v7 as you can see my project properties
Then I added android-support-v4.jar in libs folder -> then right click-> add to build path.
After that I checked these items in Java Build Path
I am following this tutorial upto their 5th point.
So, In  manifest:
    <application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="COI: Ministry of Law & Justice"
    android:theme="@style/AppTheme" >
    <activity
        android:screenOrientation="portrait"
        android:configChanges="keyboardHidden|orientation"
        android:name="com.example.indianconstitution.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        android:theme="@style/Theme.AppCompat" /////I added this line for comaptibility
    </activity>
</application>

So, in main.xml:
<menu xmlns:yourapp="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
>

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    yourapp:actionProviderClass="android.support.v7.widget.ShareActionProvider"

    android:title="@string/action_settings"/>

</menu>

And my onCreateOptionsMenu :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);

MenuItem shareItem = menu.findItem(R.id.action_settings);

    // Need to use MenuItemCompat to retrieve the Action Provider
    mActionProvider = (ActionProvider)
        MenuItemCompat.getActionProvider(shareItem);

    return super.onCreateOptionsMenu(menu);
}

Now,I am getting many errors in my code due to getActionBar,setDisplayHomeAsUpEnabled,setHomeButtonEnabled,setTitle,invalidateOptionsMenu, etc . All saying me to use API 11 in manifest.
I am completely lost what should I do now?
UPDATE Adding @SuppressLint("NewApi") avoided all these errors , in API 2.2 I am getting this errors
Logcat is below:
Logcat:
07-16 10:28:26.282: W/dalvikvm(329): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-16 10:28:26.293: E/AndroidRuntime(329): FATAL EXCEPTION: main
07-16 10:28:26.293: E/AndroidRuntime(329): java.lang.NoSuchMethodError: com.example.indianconstitution.MainActivity.getActionBar
07-16 10:28:26.293: E/AndroidRuntime(329):  at com.example.indianconstitution.MainActivity.onCreate(MainActivity.java:54)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.os.Looper.loop(Looper.java:123)
07-16 10:28:26.293: E/AndroidRuntime(329):  at android.app.ActivityThread.main(ActivityThread.java:4627)
07-16 10:28:26.293: E/AndroidRuntime(329):  at java.lang.reflect.Method.invokeNative(Native Method)
07-16 10:28:26.293: E/AndroidRuntime(329):  at java.lang.reflect.Method.invoke(Method.java:521)
07-16 10:28:26.293: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-16 10:28:26.293: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-16 10:28:26.293: E/AndroidRuntime(329):  at dalvik.system.NativeStart.main(Native Method)

Please help....


text:
Q: Google Authenticator PAM for specific users My current sshd PAM config:
#%PAM-1.0
auth       include      system-auth
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth
session    optional     pam_keyinit.so force revoke
session    include      system-auth
session    required     pam_loginuid.so

I'm adding Google Authenticator but we're not ready to roll it out to all users.
I believe the following should require the Google Authenticator PAM for users in the 'gauth' group, but was hoping someone could check my work before I go locking myself out of SSH...
#%PAM-1.0
auth       include      system-auth
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth
auth [success=1 default=ignore] pam_succeed_if.so quiet user notingroup gauth
auth required pam_google_authenticator.so
session    optional     pam_keyinit.so force revoke
session    include      system-auth
session    required     pam_loginuid.so

Am I understanding correctly that "success=1" means "skip the next line if this is successful"?

A: I believe your understanding is correct, based on the pam documentation.
You should be able to make the changes, test, and revert back if needed if you open another connection to test with, leaving your original ssh session connected (make sure it doesn't time out though!)

A: When playing around with the PAM stack I usually do not use the service, that I in fact want to modify, since this is a "productive" service.
So in this case I would test with /etc/pam.d/login instead of ssh. login can be tested by simply calling:
login

If the PAM config looks good, I can transfer it to gdm, ssh or whatever. (Who needs a local login ;-)
And yes, success=n means, in case of success, skip the next n lines.

redpajama_set_name: RedPajamaStackExchange


text:
Q: First order non-linear differential equation Please help me solve this first-order non-linear differential equation.
$$ \frac{\mathrm{d}y}{\mathrm{d}x} = \frac{y+xy^2}{x-5y+y^2 \mathrm{cos}(y)}$$

A: Hint
Written as $$\frac{dy}{dx} = \frac{y+xy^2}{x-5y+y^2 \cos(y)}$$ the differential equation seems extremely complex because of the simultaneous presence of $y$ and $\cos(y)$.
So, let us reverse it and write it as $$\frac{dx}{dy} = \frac{x-5y+y^2 \cos(y)}{y+xy^2}$$ Now, because of the denominator, let us make a change of variable $x=z-\frac 1 y$ (which makes $y+xy^2=y^2z$), $\frac{dx}{dy}= \frac{dz}{dy}+\frac{1}{y^2}$. So, in terms of $z$, the differential equation write (after minor simplifications) $$\frac{\frac{1}{y^3}+\frac{5}{y}-\cos (y)}{z}+\frac{dz}{dy}=0$$ which seems to be quite simple.
I am sure that you can take from here.


text:
Q: read -t is not pausing my while loop in bash I'm trying to create a simple loop in bash that lists all the files in a directory, one by one.
I want to have to hit Enter before proceeding to the next one. I thought that adding read would make the loop pause. But it is not pausing. It is listing all the files at once. Here is the command I'm using
find . -type f | while read -r line; do echo "$line"; read -t 1; done`

A: You can do it like this:
# redirect fd=3 from 0
exec 3<&0

while IFS= read -rd '' line; do
   echo "$line"
   # read from fd=3 and wait for 1 sec
   read -u 3 -t 1
done < <(find . -type f -print0)

# close fd=3
exec 3<&-

A: Expanding on @anubhava's answer, it doesn't matter where you use the other file descriptor. You can use it for reading input from the find process and take user input to prompt the next file on stdin (fd0). The key is you must have two different discriptors in use, one for the input of filenames from find and the other to take input from the user's keystrokes. For example, you could also do:
while read -u 4 -r line; do
    echo "$line"
    read -n1 -t2 c
done 4< <(find . -type f)

It is functionally equivalent, aside from here, the result of the process substitution with find is redirected on fd4 while the user can provide input on stdin or after a 2 second timeout, the next file will automatically be displayed.

A:
I want to have to hit Enter before proceeding to the next one. I thought that adding read would make the loop pause

Try a ProcSub and use a different FD for the first read. Note that the inner read is just after the do.
while read -ru9 line; do read -p "$line"; done 9< <(find . -type f)

The -u flag from read means it will use the given file descriptor in this case the 9
If your bash is new enough you can probably just use a varname for the FD
Something like
while read -ru "$fd" line; do read -p "$line"; done {fd}< <(find . -type f)

Instead of hard coding a fix value for the FD. Where "$fd" is just an arbitrary name/variable.
See also help read in your local terminal.


text:
Q: Deleting a file that resides on an internal Linux server via my application I've recently been working on an enhancement for an application at work that will allow users to delete presentations stored not on their local machine but on a Linux server present on the internal network.  My problem is that I am not sure how to go about performing this delete.  The location of the files are as follows:
http://ipaddress/dataconf/productusers/**ACCOUNT**/presentations/

I have access to the ACCOUNT name which is a parameter that will need to be passed in to navigate to the right directory.  I will also have access to the presentation name which will be needed to specify the correct presentation to delete.
What I am having trouble with is where to begin.
I am using the Spring framework so my code is a mixture of Java, JSP, and JavaScript.
Essentially I have a .jsp page where I layout the presentations that are associated with each account.  I.E when you click on an account it makes a call to a database and lists the presentations that are associated with that account.  You can then select individual accounts and delete, or press one delete all button and delete them all.
I currently have it working so that when you delete a presentation in my application, it deletes the appropriate record from the database, but I also need to delete the physical presentation which is the basis for this question.  Just as an FYI, these requests (get presentations from database, remove presentations from database) are all being handled through AJAX and JSON.
I am hoping to learn how to create a connection to the correct server, navigate to the proper directory as specified above, and issue the Linux command "sudo rm file-name" all in the same delete process that I described in the prior paragraph.
If you could point me in the right direction, any help would be much appreciated. Also, if you need any further clarification please feel free to let me know.
Thanks again,
Dave

A: This will not be easy. Or maybe it will. Please understand first that simply knowing where some files are published on an HTTP server is basically useless in terms of manipulating those files.
So I understand the following: You have your own web application on server A, a database somewhere, and some files located on another web server B. Internally on server B, the files will be in some weird directory e.g. /var/www/docs/whoknowswhat/somefolder/dataconf/productusers.
What you need to do is to somehow expose this folder from within server B over the network to your server A. Talk to your admin people. Maybe NFS is an option, or maybe Samba, or SSHFS. Make sure you have write permissions, and also make sure that noone else does.
Once you have mounted the location from B in your server A and it is available to you as some directory /mnt/serverB/productusers, then all you have to do is something like this, i.e. File f = ...; f.delete();

A: I did a little research and stumbled upon a neat solution to accomplish what I am trying to do. If you take a look at the following link:
http://www.journaldev.com/246/java-program-to-run-shell-commands-on-ssh-enabled-system
The above site describes a method in which you can open an ssh connection in Java and execute commands as if you were running them from the terminal.  It has come in handy for my problem and I hope that if anyone else is experiencing the same problem that this will help them as well.  Feel free to let me know what you think.


text:
Q: where is the cut plane for Forge levels extension? for Forge Autodesk.AEC.LevelsExtension, where is the cut plane? looks like it doesn't follow the view range in Revit?

A: In this extension, floors cut planes are defined based on the bounding box of the floor node in the scene instance tree. Floors are defined in an additional AEC data json file which contains additional information.

A: Appended to what Cyrille mentioned.
Revit's AEC model data will be generated automatically during the Forge translation. The level info is dumping from Revit Level elements, e.g., the name, guid, elevations, extensions of the Revit Level which you can see with Revit API. The Levels extension just uses it to rebuild level ranges.
For example, the cutting range of level 1 will be from level1's elevation to (level2's elevation - a height adjustment) with my research. The height adjustment is to avoid cutting on top of floors to brining a better view. So, it's not following Revit's view range of the floor plan view.
If the levels extension doesn't match your need, you may check out my level section tool. This sample demonstrates the concept of how to create cut planes by levels.


text:
Q: Use mean value theorem on $f(x) = x^{1/5}$, to show that $2< \sqrt[5]{33}<2.0125$ The problem specifically aks us to use mean value theorem on the interval $[32, 33]$
It has always puzzled me that mean value theorem can be used to prove Inequalities.
Can anyone show how mean value theorem can be used to prove Inequalities like these.

A: The mean value theorem, in your situation, says that
$$\frac{{\root5\of{33}}-2}{33-32}=\frac{1}{5c^{4/5}}$$
for some $c$ between $32$ and $33$.  This can be rewritten
$${\root5\of{33}}=2+\frac{1}{5c^{4/5}}\ .$$
Since $c>32$ we have
$$\frac{1}{c^{4/5}}<\frac{1}{32^{4/5}}=\frac{1}{2^4}\ .$$
See if you can finish the problem for yourself.


text: Q: LinkedIn : Marketing Developer Platform Stuck in Review process I have created a product request in LinkedIn for the Marketing Developer Platform on 24th May, but still its on "Review in Progress". Can anyone suggest me, When will I get review/feedback?


text:
Q: Adding a method to a function that returns an element I'm playing around with a micro library for use within projects and I'm having difficulty adding a method to a function.
In this case I have shorthanded document.querySelector() which is all good and works as needed. However I have no real idea how to add a method to that which inherits the element from the selector function.
This is similar to how jquery works but a lot of code examples online are a fair few years old. I'm wanting a modern solution and to understand how this works going forward. I really hope someone can educate me and help to get this to work.
Cheers!
let S = (selector, container = document) => {
    return container.querySelector(selector);
};

S.prototype = {
  classAdd: (_class) => this.classList.add(_class)
};

S('div').classAdd('red');

https://codepen.io/matt3224/pen/NMqBLp?editors=0010

A: Arrow functions don't have a prototype property. To get it working use a normal function, that's not not modern. Arrow functions are not a replacement, but an addition. You could also use a class though - maybe that's what you mean with modern.

class S {
  constructor(selector, container = document) {
    this.selected = container.querySelector(selector);
  }

  classAdd(clazz) {
    this.selected.classList.add(clazz);
  }
}

new S('#foo').classAdd('bar');
console.log('#foo has bar as class: ', document.getElementById('foo').classList.contains('bar'));

  foo

A: Let's take a closer look at your code, shall we?
First block:
let S = (selector, container = document) => {
  return container.querySelector(selector);
};

This code declares a simple function and assigns function reference to variable S
The function itself returns HTML element as per querySelector documentation, which can not be use in a chain notation:
S('div').something();  // won't work
let ele = S('div');    // works

Second block:
S.prototype = {
  classAdd: (_class) => this.classList.add(_class)
};

Because S is a simple function (NOT a Function-Object) it has no prototype element as a regular Object does. However, the code still works as it creates a new property named propotype on the S function.
To prove what has been stated above, I have created following code example:

let S = (selector, container = document) => {
  return container.querySelector(selector);
};

let ele = S('div');
console.log(ele);

S.prototype = {
  classAdd: (_ele, _class) => _ele.classList.add(_class)
};

S.prototype.classAdd(ele, 'red');
.red {
  padding: 10rem;
  background-color: coral;
}

Text inside div

If you want to use chain notation such as S('div').classAdd(..) your first block function must return a valid object to act upon

let S = (selector, container = document) => {
  return {
    ele : container.querySelector(selector),
    classAdd: function(_class) { // regular function notation as it needs this
      this.ele.classList.add(_class)
    }
  };
};

S('div').classAdd('red')
.red {
  padding: 10rem;
  background-color: coral;
}

Inside Div

A: you can define classAdd in the S and return an object containing the methods :

let S = (selector, container = document) => {
  let element = container.querySelector(selector);

  return {
    classAdd: (_class) => {
      element.classList.add(_class)
    }
  }
};

S('div').classAdd('hello')

  hello


text:
Q: What is the difference between extend method for list and update method for set? Why is it that a set does not have extend() but has update() instead?
What is the reason?

A: extend augments a list regardless of its existing content whereas update uses the existing content in the process, only adding items that are not already there.  Updating a set does not necessarily make it larger (e.g. if you only provide values already in the set) so extend would not be an appropriate name. Conversely, update would not be appropriate for a list because no processing is performed on the basis of existing content.
This is semantically consistent with the english definitions of these verbs:
Extend:  cause to cover a larger area; make longer or wider
Update:  make (something) more modern or up to date


text:
Q: How to concatenate 2 strings when the first is defined in a preprocessor directive and the second is constant in C++? Here's what I have:
#define STRING "string 1"

string string2 = STRING + "string3";

This is wrong. What is the solution? Is the problem that string2 must be constant or what else, and why?

A: #define STRING "string 1"

std::string string2 = STRING "string3";

Concatenation of adjacent string litterals isn't a feature of the preprocessor, it is a feature of the C/C++

A: You cannot use operator + on two string literals, as this would effectively mean you are trying to add two char pointers.
There are two ways how to achieve what you want:
You can use runtime "string" concatenation (not preprocessor), but for this you need to construct a std::string from one of the string literals, so that the compiler knows what operator + overload to look for:
#define STRING "string 1"
string string2= string(STRING) + "string3"

Or, to use compile-time concatenation, keep both strings as string literals and just write then one after the other, the compiler will concatenate them:
#define STRING "string 1"
string string2= STRING "string3"

Or (to answer in C):
#define STRING "string 1"
const char string2[]= STRING "string3"

A: In general you can imagine your STRING as a const char *. As such it has no notion of "how to add another const char* to myself".
For your case to work, you can either let the compiler concatenate them:
#define STRING "string 1"
std::string string2 = STRING "string3"

which works only for string literals (constant strings that are defined within your source code), or in general you'd have to make a std::string out of it first, which has an operator+ overload, that allows you to add a C-String to it:
#define STRING "string 1"
std::string string2 = std::string(STRING) + "string3";


text:
Q: Extractvalue from XML using XML compliant format in Oracle SQL I have a  requirement . I need to query a table and display the column value by transforming escape character into XML format
example " & " to "&"
Details
I have table name "AppName"
select NAME from AppName

NAME
---------
Oracle & Database

What  i need to do is get the output in XML compliant format. something like below
eg:
NAME
------
Oracle & Database

I have used the DBMS_XMLGEN to make it XML Complaint and trying to using extractvalue to get the value. but it return as "Oracle & Database"
Below is query to transform to XML format
select SYS.DBMS_XMLGEN.getXML( 'select NAME from APPName ') XML_out from dual

"<?xml version="1.0"?>
 <ROWSET>
 <ROW>
  <NAME>Oracle & Database<NAME>
  </ROW>
 </ROWSET>
 "

And then i try to extract the Name
select extractvalue( XMLType.createXML(SYS.DBMS_XMLGEN.getXML( 'select NAME from APPNAme' )),'/ROWSET/ROW/NAME') XML_out from dual

which return back the output same as "Oracle & Database"
But i need output as "Oracle & Database"

How can i get this output using DBMS_XMLGEN or is there is any easy way.
Any help is greatly appreciated

A: You're doing more work than you need to; dbms_xmlgen has a convert() function, which escapes special characters (entities) by default:
select dbms_xmlgen.convert(name) from appname;

DBMS_XMLGEN.CONVERT(NAME)
--------------------------------------------------------------------------------
Oracle & Database

The second argument defaults to ENTITY_ENCODE, and you can either set that explicitly (using the underlying value 0 in plain SQL) to encode:
select dbms_xmlgen.convert('Oracle & Database', 0) from dual;

DBMS_XMLGEN.CONVERT('ORACLE&DATABASE',0)
--------------------------------------------------------------------------------
Oracle & Database

Or to 1 (ENTITY_DECODE) to do the reverse operation and decode:
select dbms_xmlgen.convert('Oracle & Database', 1) from dual;

DBMS_XMLGEN.CONVERT('ORACLE&DATABASE',1)
--------------------------------------------------------------------------------
Oracle & Database

If you already had the XMLType, or wanted it in that format for some other reason, you could use an XMLQuery instead of extractValue:
select xmlquery('/ROWSET/ROW/NAME/text()'
  passing XMLType.createXML(SYS.DBMS_XMLGEN.getXML('select name from appname'))
  returning content) XML_out from dual;

XML_OUT
--------------------------------------------------------------------------------
Oracle & Database

But in this case the conversion to XML is a bit pointless.


text:
Q: Java Android CountDownTimer malfunction I want my app to wait for a moment before changing the button text. I tried different things (wait(), Thread.sleep) but since I want the waiting time to be variable, I decided to make use of CountDownTimer. See the code below:

  public void onClick(View buttonClicked) {
    if (i == 0) {
        button.setText("Wait");
        waitingTime = (long) (Math.random() * 1000 + 10000);
        new countdown(waitingTime, 1000);
        time1 = System.currentTimeMillis();
        button.setText("Press");
        i++;

For some reason this doesn´t work, and the program does not wait at all. Can anyone please help me? I did not fill the CountDownTimer with anything since I figured that it should only wait for a couple of seconds.

A: Thread is also variable:
try {
 Thread.sleep(1000);
 } catch (Exception e) {
 }

A: try this code
@Override
public void onClick(View view) {
if(i==0) {
        YourActivity.this.runOnUiThread(new Runnable() {

@Override

public void run() {
txtView.setText("please wait...");
}
});

while(counter < 1000) {
try {
    Thread.sleep(100);
}catch(InterruptedException e) {
    e.printStackTrace();
}
counter +=100;
}

txtView.setText("press");

i++;

}

}

Increase the thread timing according to ur needs. And if needed write this code in the function where you are passing the sleep value
EDIT
mHandler = new Handler();
         btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            btn.setText("wait");
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    btn.setText("press");
                }
            }, 1500);
        }
    });


text:
Q: Published .Net Core Web Application to Apache2 Web Server only Showing up as Directory Search I am currently working on setting up a QA server at my home in order to test applications, and I have run into a bit of an issue. I have attempted to publish my .Net Core 6 website to the server by the following steps:

*

*Publishing the website via Visual Studio, to a local folder. Visual Studio Publishing

*Copy the published website over to the server via Filzilla. Filezilla Copy
Unfortunately, when I go to the url I only wind up with a directory search of the published files: Directory Search
The webserver is Apache2, running on Ubuntu Server 22.04. How can I get my website up and running on this QA server, rather than just a directory search?
Thanks in advance for your help!

A: 4L4M1N's comment is correct. The publish files you generated just for windows IIS. not Apache2.
So you need check the official to create .htaccess file, and the webserver will be working.
Reference Video:
How to Deploy .Net Core Web Application to Ubuntu Linux


text:
Q: Can I get value from content dictionary with xpath? This is an example of a meta tag from which I want to get the pub_date:
<meta name="parsely-page" content='{"title":"Article title","link":"https:\/\/site.com\/category\/article","type":"post","section":"category","image_url":"","author":null,"pub_date":"2009-03-01T14:17:14+00:00","post_id":"article_6463676334","tags":[]}' />
The xpath to get the entire content would be:
//meta[@name="parsely-author"]/@content
Is it possible to get the values of dict keys using xpath?

A: With XPath 3.1 you can do
//meta[@name="parsely-author"]/parse-json(@content)?pub-date

Sadly, it's very likely that you are using an XPath processor that only supports XPath 1.0 in which case you won't be able to use this unless you find a different processor.

A: With XSLT 1.0:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:variable name="vQ">"</xsl:variable>
  <xsl:template match="/">
    <xsl:value-of select=
    'substring-before(substring-after(//meta[@name="parsely-page"]/@content,
                                      concat($vQ, "pub_date", $vQ, ":", $vQ)), $vQ)'/>
  </xsl:template>
</xsl:stylesheet>

When this transformation is performed on this XML document (your meta tag):
<meta name="parsely-page"
content='{"title":"Article title","link":"https:\/\/site.com\/category\/article","type":"post","section":"category","image_url":"","author":null,"pub_date":"2009-03-01T14:17:14+00:00","post_id":"article_6463676334","tags":[]}' />

the wanted result is produced:
2009-03-01T14:17:14+00:00
We can write a single XPath 1.0 expression that evaluates to the wanted string, however we will have to escape quotes and apostrophes in order to avoid errors for their being nested, if unescaped:
substring-before(substring-after(//meta[@name="parsely-page"]/@content,
                                 '"pub_date":"'),
                 '"')

Verification using XSLT 1.0:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:variable name="vQ">"</xsl:variable>
  <xsl:template match="/">
    <xsl:value-of select=
    'substring-before(substring-after(//meta[@name="parsely-page"]/@content,
                                      '"pub_date":"'),
                      '"')'/>
  </xsl:template>
</xsl:stylesheet>

When this transformation is applied to the same XML document (above), it evaluates the single XPath 1.0 expression and outputs the wanted, correct result:
2009-03-01T14:17:14+00:00


text:
Q: JSON record manually creaed I am trying to create the following record in JS as a string to pass to DataTables. The example below is failing. What do I need to change. Thank you.
RECORD:
{
 "SMG": "<input type="hidden" class="smg-wty-up-val" value="none">SMG Standard Warranty Only",
 "wty": "' + StdWty + '",        <== VARIABLE HERE
 "pri": "0.00"
};

TRYING THIS (AMONGST OTHER COMBINATIONS):
WtyRow +='{ \
            \"SMG\": "<input type=\"hidden\" class=\"smg-wty-up-val\" value=\"none\">SMG Standard Warranty Only\", \
            \"wty\": \"' + StdWty + '\", \
            \"pri\": \"0.00\" \
          }';

A: If you start with double quotes, then use single quotes inside the string, and vice versa. Try
var obj = {
           "SMG": "<input type='hidden' class='smg-wty-up-val' value='none'>SMG Standard Warranty Only",
           "wty": StdWty,
           "pri": "0.00"
          };

You can stringify the above like JSON.stringify(obj)


text:
Q: How to return the number of empty fields in an object? I am trying to create a progress bar feature where it tells you your progress by what data you have inserted into your profile. The idea is that it takes all the fields that are empty and subtracts it from the total number of fields.
How do I get all empty fields and return it as a number?

A: You can use bool() to check for "empty" fields.
fields = instance._meta.fields
empty = sum(bool(getattr(instance, field.attname)) for field in fields)

You might want to restrict this to only checking certain field types, for example CharFields and TextFields.
fields = [f for f in instance._meta.fields if isinstance(f, (TextField, CharField))]

You can add this as a method or property on your model class. In this case, progress will return a number between 0 and 1.
class MyModel(models.Model):
    ...
    @property
    def progress(self):
        text_fields = [f for f in self._meta.fields if isinstance(f, (TextField, CharField))]
        values = (getattr(self, field.attname) for field in text_fields)
        return sum(bool(value) for value in values) / len(text_fields)


text:
Q: QMessageBox exec doesnt seem to return QDialog::DialogCode My application's closeEvent() looks nearly like this (Qt 5.8.0 on Windows):
void MainWindow::closeEvent(QCloseEvent *event)
{
    if(some_changes_were_made)  // bool
    {
        QMessageBox mbox;
        mbox.setText("Page(s) have been changed.");
        mbox.setInformativeText("What do you want to do?");
        mbox.addButton("Exit now", QMessageBox::AcceptRole);
        mbox.addButton("Save page(s) first", QMessageBox::RejectRole);

        int exit_code = mbox.exec();

        if(exit_code == QDialog::Rejected)
        {
           // bail out of the close event so the user can save pages
           event->ignore();
           return;
        }
    }

    event->accept();
}

I'm curious if the documentation is wrong, which states that exec() returns a QDialog::DialogCode.  It actually seems to return the QMessageBox::ButtonRole (which interestingly is the inverse value).  Or am I just doing something totally wrong here?
Please forgive any typos, as I'm unable to copy the actual code here.

A: Check QMessageBox reference here.
It is supposed to return one of the standardButton replies. You are using QDialogBox replies, QMessageBox has already overriden QDialogBox's exec method.
You want to check something like this:
switch (exit_code) {
  case QMessageBox::Save:
      // Save was clicked
      break;
  case QMessageBox::Discard:
      // Don't Save was clicked
      break;
  case QMessageBox::Cancel:
      // Cancel was clicked
      break;
  default:
      // should never be reached
      break;
}

Source from the same link.


text:
Q: Shifting characters in C++ I tried to write a function to do simple shifting of characters (either to the left or right, depending on the shift parameter in the following function). Capital letters remain to be capital letters. Here is my approach:
char encodeCaesarCipherChar(char ch, int shift)
{
    char result;
    if (!isalpha(ch)) return ch;

    result = ch + shift;

    if (islower(ch) && result < 'a') {
        result += int('z') - 1;
        result -= int('a');
    } else if (islower(ch) && result > 'z') {
        result -= int('z');
        result += int('a') - 1;
    }  else if (isupper(ch) && result < 'A') {
        result += int('Z') - 1;
        result -= int('A');
    }  else if (isupper(ch) && result > 'Z') {
        result -= int('Z');
        result += int('A') - 1;
    }

    return result;
}

This function stops working properly when the input character is 's' and beyond. Could anyone please point out what's the problem to my approach?
Thanks in advance.

A: 's' + 13 will overflow a signed char. Keep the result in an int and cast to char after adjusting the number and before returning.


text:
Q: Timestamp data stored in UTC, yet the actual timestamp is BST I'm trying to convert a timestamp column to UTC.
The issue is the column reads it as UTC already, when the timestamps are actually stored in 'Europe/London'.

current data
expected data

2022-03-26 23:46:18 UTC
2022-03-26 23:46:18 UTC

2022-03-27 00:15:16 UTC
2022-03-27 00:15:16 UTC

2022-03-27 02:52:48 UTC
2022-03-27 01:52:48 UTC

The 3rd row here looks to be stored in UTC, yet it's actually in BST, so i'm trying to figure out how to convert it to UTC.
The data has been ingested from
Mixpanel, yet a time zone wasn't applied to the ingestion, hence it has been auto assigned UTC. I was wondering if there's a way to set this as "Europe/London" within a sql query - without changing any of the numbers for hour in the actual time stamp, so it can be then converted to UTC.
If not current solution is to update past events by selecting the date time ranges of BST over the past 5 years and updating the column, and then try and fix the ingestion for the future.
Any help would be greatly appreciated

A: You can consider the below query to convert BST timestamp data to UTC. Also, BigQuery stores timestamps in UTC.
with sample as (
    select timestamp('2022-03-27 02:52:48', 'Europe/London') as ts
)
select timestamp(datetime(ts), 'UTC') as utc_time from sample;

Output:

A: See if this helps to clarify the concept:
select current_timestamp() as current_utc_ts, current_datetime("Europe/London") as current_bst_ts, current_datetime("America/New_York") as current_est_ts


text:
Q: Placeholder in Select component I use https://github.com/callemall/material-ui/tree/v1-beta
Can I make a placeholder in the Select component?
<Select
  value={value}
  onChange={handleChange}
  input={<Input />}
>
  <MenuItem value={''}>Any</MenuItem>
  <MenuItem value={'Male'}>Male</MenuItem>
  <MenuItem value={'Female'}>Female</MenuItem>
</Select>

Thanks

A: You should use FormControl and InputLabel components.
Example from the select component material page:
<FormControl className={classes.formControl}>
      <InputLabel htmlFor="age-simple">Age</InputLabel>
      <Select
        value={this.state.age}
        onChange={this.handleChange('age')}
        input={<Input id="age-simple" />}
      >
        <MenuItem value="">
          None
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>

Hope it helps :)


text:
Q: Get Preferred/Default app on Android I am trying to get the default/preferred application for a given Intent. For example, when the user installs a second web browser, then attempts to open a URL, he or she will get a dialog like this:

If the user then selects the Use by default for this action option, then the dialog box no longer opens when a URL is pressed.
I am working on an application that should be aware of what this default or preferred app/action is. How do I do this? I am currently using the code below, but getPreferredPackage doesn't return anything:
Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
IntentFilter ifilter = new IntentFilter(i.getAction());
if (i.getCategories() != null) {
    for(String category : i.getCategories()) {
        ifilter.addCategory(category);
    }
}
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(ifilter);
List<ComponentName> preferredActivities = new ArrayList<ComponentName>();
pm.getPreferredActivities(filters, preferredActivities, null);
for (ComponentName activity : preferredActivities) {
    for (ResolveInfo rinfo : list) {
        if (rinfo.activityInfo.applicationInfo.packageName.equals(activity.getPackageName())) {
            try {
                final PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
                Toast.makeText(context, pm.getApplicationLabel(pi.applicationInfo), Toast.LENGTH_SHORT).show();
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}

What am I doing wrong? Is this even the right approach?

A: The method launchUrlInDefaultBrowser below launches a URL without displaying any selection query for the user. First, it tries to find the user's default browser app and launch the URL with it. Second, if there was no default app, it lists all the capable activities for launching the URL and picks up the first one. In case an activity was launched, the method returns true; otherwise, false.
boolean launchUrlInDefaultBrowser(Context context, String url) {
    final Intent browserIntent = new Intent(Intent.ACTION_VIEW);
    browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    browserIntent.setData(Uri.parse(url));

    // 1: Try to find the default browser and launch the URL with it
    final ResolveInfo defaultResolution = context.getPackageManager().resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
    if (defaultResolution != null) {
        final ActivityInfo activity = defaultResolution.activityInfo;
        if (!activity.name.equals("com.android.internal.app.ResolverActivity")) {
            browserIntent.setClassName(activity.applicationInfo.packageName, activity.name);
            context.startActivity(launchIntent);
            return true;
        }
    }
    // 2: Try to find anything that we can launch the URL with. Pick up the first one that can.
    final List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
    if (!resolveInfoList.isEmpty()) {
        browserIntent.setClassName(resolveInfoList.get(0).activityInfo.packageName, resolveInfoList.get(0).activityInfo.name);
        context.startActivity(browserIntent);
        return true;
    }
    return false;
}

Beware, the OEMs may have their own ResolverActivity implementation. E.g. Huawei has com.huawei.android.internal.app.HwResolverActivity.

A: Well, the solution turned out to be much simpler than I made it (although this is very poorly documented). The following code is my solution:
Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final ResolveInfo mInfo = pm.resolveActivity(i, 0);
Toast.makeText(context, pm.getApplicationLabel(mInfo.activityInfo.applicationInfo), Toast.LENGTH_LONG).show();

A: In Kitkat AOSP, getPreferredPackages() always returns empty list. Source code as below
public List<PackageInfo> getPreferredPackages(int flags) {
    return new ArrayList<PackageInfo>();
}


text:
Q: How can I chain functions asynchronously using JavaScript? I was asked to create such an object called foo that can chain the function log and wait.
For example:
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner');

In this scenario it prints breakfast first, waits 3 seconds, prints lunch, and then after 3 seconds it prints dinner.
I tried something like this, but it doesn't work. What did I miss?

var foo = {
  log: function(text){
    console.log(text);
    return foo;
  },

  wait: function(time) {
    setTimeout(function() {
      return foo;
    }, time);
  }
}

foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner');

A: It's always better to use promises. An implementation of this functionality could be;

class Foo {
  constructor(){
    this.promise = Promise.resolve();
  }
  log(txt){
    this.promise = this.promise.then(_ => console.log(txt))
    return this;
  }
  wait(ms){
    this.promise = this.promise.then(_ => new Promise(v => setTimeout(v,ms)));
    return this;
  }
}

  var foo = new Foo();
  foo.log("happy").wait(1000).log("new").wait(1000).log("year");

A: For the record, Redu's excellent answer without the class sugar.
See also

const foo = {
  promise: Promise.resolve(),
  log(txt) {
    this.promise.then(_ => console.log(txt));
    return this;
  },
  wait(ms) {
    this.promise = this.promise.then(_ => new Promise(v => setTimeout(v, ms)));
    return this;
  }
};

// OR
const Foo = (defaultMs = 1000) => {
  let promised = Promise.resolve();
  return {
    log(txt) {
      promised.then(_ => console.log(txt));
      return this;
    },
    wait: function(ms) {
      promised = promised.then( _=>
        new Promise( rs => setTimeout(rs, ms || defaultMs) ) );
      return this;
    }
  };
};

foo.log("Happy").wait(1000).log("new").wait(1000).log("year");
Foo().wait(3000)
  .log(`** From Foo ;)`).log(`Happy`).wait().log("new").wait().log("year");

A: Place the call to wait inside the previous one, and as the last item, like a recursive function.

meals=['breakfast','elevenses','lunch','afternoon tea','dinner','supper'];
c=0;
wait=t=>{setTimeout(function() {
      if (c<meals.length) document.write(meals[c++],'<br>');wait(500);
    }, t);}

wait(500);

A: I was inspired by @James 's solution, which is partially wrong because the log messages are in the reverse order, but he does not use Promises. I still think that @Redu 's solution should be the accepted one (after all if you can use Promises, that is perfect), but this one is interesting too in my opinion:

const foo1 = {
    incrementalTimeout: 0,
    nextActions: [],
    log(text) {
        const textLog = () => { console.log(text); };
        if (this.incrementalTimeout == 0)
            textLog();
        else
            this.nextActions.push(textLog);
        return this;
    },
    wait(time) {
        let newObj = {...this, incrementalTimeout: this.incrementalTimeout + time, nextActions: []};
        setTimeout(() => { newObj.nextActions.forEach((action) => action()); } , newObj.incrementalTimeout);
        return newObj;
    }
}
foo1.log('breakfast').wait(1000).log('lunch').wait(3000).log('dinner');

The idea is that I do not immediately log text but I push a lambda with the console.log in an array that is going to be called after the correct timeout expires.
I run all the log and wait operations one after the other, but I keep track of the seconds to wait before executing the actions. Every time a new wait is called, the incrementalTimeout is increased by time. To keep the nextActions belonging to different time frames separated, I return a newObj every time, more or less like @James does.

A: Shorter, within Promise (not recommended).
Promise.prototype.log = function(txt) {
    return this.then(() => console.log(txt))
}

Promise.prototype.wait = function(ms) {
    return this.then(() => new Promise(res => setTimeout(res, ms)))
}

var foo = Promise.resolve()
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner')

A: You can do it without promises:

const foo = {
    log(text) {
        return {...foo, start: () => {
            this.start();
            console.log(text);
        }};
    },
    wait(time) {
        return {...foo, start: () => {
            setTimeout(this.start, time);
        }};
    },
    start() {}
};
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner').start();

The functions foo.log() and foo.wait() return immediately, returning a modified clone of foo. A clone is made using {...foo}, but with the start() function modified so that it calls the caller's this.start() followed by the new operation. When the chain is complete you call start() to start the actions.


text: Q: What would happen to the physical photon if the electroweak symmetry were to be restored? Suppose the Higgs field goes back to its initial unstable state, as it was before electroweak symmetry breaking. Or, in other words, suppose the electroweak symmetry is restored. Since, the physical photon that we observe today was, before symmetry breaking, a linear combination of $W^{0}$ and $B^{0}$, would it "decompose" back to being that linear combination if the symmetry is to be restored?


text:
Q: i want to write a code in golang. program reads 100 url from file and print its status code how can i pass url via for loop in get request i have read a file and want to pass it on get request
but i have a problem in for loop can anybody help me
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {

    data, err := ioutil.ReadFile("url.txt")

    resp, err := http.Get(data)
    if err != nil {
        log.Fatal(err)
    }

    // Print the HTTP Status Code and Status Name
    fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))

    if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
        fmt.Println("HTTP Status is in the 2xx range")
    } else {
        fmt.Println("Argh! Broken")
    }
}

A: You should use os package instead of io/ioutil package as described in the ioutil package:

As of Go 1.16, the same functionality is now provided by package io or
package os, and those implementations should be preferred in new code.
See the specific function documentation for details.

This will also avoid unnecessary conversion from byte returned by ioutil.ReadFile() to  string object required by http.Get().
Further, you can use the NewScanner() method from the bufio package to read line by line.
package main

import (
    "fmt"
    "log"
    "net/http"
    "bufio"
    "os"
)

func main() {

    file, err := os.Open("url.txt") // open the file
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        resp, err := http.Get(scanner.Text()) // call http.Get per URL object
        if err != nil {
            log.Fatal(err)
        }
        // Print the HTTP Status Code and Status Name
        fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))

        if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
            fmt.Println("HTTP Status is in the 2xx range")
        } else {
            fmt.Println("Argh! Broken")
        }
    }
}

Note: The input will by default be splitted on newline character.


text:
Q: How to store ids with selections in AutoComplete AjaxControlToolkit ASP.NET? I am implementing the Autocomplete textbox from AjaxControlToolkit in ASP.NET. The ServiceMethod allows me to call a function which will populate a string list with which to populate the autocomplete list that will display.
My question is, when I call the database, I would like to store an ID that corresponds with each selection, so that once it is selected by the user, I can easily look it back up in the database. I don't want to display it in parentheses next to the selection (ie. "John Smith (ID1234)", etc.)
Is there a way to do this so that the ID is 'hidden' so to speak within the Autocomplete box, and can be retrieved on selection? Should i use a different autocomplete box to accomplish this? Any help is greatly appreciated. Thanks!

A: This might answer your question
http://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-in-ASP.Net-AJAX-AutoCompleteExtender.aspx


text:
Q: How to put more views in a page title strip? I'm trying to use a page title strip and I need to put three seekbars in one of my fragments. This is my code:
public class MainActivity extends FragmentActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        Fragment fragment = null;
        Bundle args = new Bundle();
        switch (position) {
        case 0:
            fragment = new Page1();
            args.putInt(Page1.ARG_SECTION_NUMBER, position + 1);
            break;
        case 1:
            fragment = new Page2();
            args.putInt(Page2.ARG_SECTION_NUMBER, position + 1);
            break;
        case 2:
            fragment = new Page3();
            args.putInt(Page3.ARG_SECTION_NUMBER, position + 1);
            break;
        }
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase();
        case 1:
            return getString(R.string.title_section2).toUpperCase();
        case 2:
            return getString(R.string.title_section3).toUpperCase();
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class Page1 extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public Page1() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Create a new TextView and set its text to the fragment's section
        // number argument value.
        // TextView textView = new TextView(getActivity());
        // textView.setGravity(Gravity.CENTER);
        // textView.setText(Integer.toString(getArguments().getInt(
        // ARG_SECTION_NUMBER)));
        SeekBar sb1 = new SeekBar(getActivity());
        SeekBar sb2 = new SeekBar(getActivity());
        SeekBar sb3 = new SeekBar(getActivity());
        return sb1;
    }
}

public static class Page2 extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public Page2() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Create a new TextView and set its text to the fragment's section
        // number argument value.
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.LEFT);
        textView.setText("Second tab");
        return textView;
    }
}

public static class Page3 extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public Page3() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Create a new TextView and set its text to the fragment's section
        // number argument value.
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.RIGHT);
        textView.setText("third tab");
        return textView;
    }
}
}

This actually works but I only have one seekbar in the first page. Ho can I put the three of them??? Thanks!!!!

A: on this code:
    SeekBar sb1 = new SeekBar(getActivity());
    SeekBar sb2 = new SeekBar(getActivity());
    SeekBar sb3 = new SeekBar(getActivity());
    return sb1;

you're creating 3 SeekBars but only returning the first one. The other two are being garbage collected quickly after that return statement.
Inside the onCreateView method you must create a GroupView, and this group will have the 3 SeekBars or whatever layout you need. The best/easiest way to do it is creating a XML layout and use the LayoutInflater that is passed on the function. Something similar to:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.frag_page1, null);
}


text:
Q: Displaying HTML Source rather than rendering the code in GAE I am trying to display the source code of the site using Google App Engine. Here is the snippets of the code that I have tried out.
 def post(self):
    s = 'http://www.bing.com'
    fp = urllib.urlopen(s)
    src = fp.read()
    self.response.out.write(template.render('main.html',{'temp1':src}))

And the template I have used have some thing similar to

{{temp1}}

The problem here is that it renders the source and gives me the html page of the site rather than the code which I am trying to embed. Let me know how to get this solved?

A: If you want to see the html and not the page you gonna need to escape the html entities.
Try: src = cgi.escape(src)
And maybe put it inside

 tags for distinctive displaying.

A: (assuming that you're using the Django templates that come with Appengine,) you can use the built-in escape filter, like:

{{temp1|escape}}

A: You could put the HTML code inside the div inside a
 tag. It's for pre-formatted content. That is, you want the browser to display it exactly the way you write it, so it ignores tags and does not truncate multiple spaces/tabs.

{{temp1}}


text:
Q: ASP.NET MVC: Register action filter without modifying controller I'm working with nopCommerce and I need to add in my only Action Filter, however, I don't want to modify the core controllers to avoid my code being overwritten when a new update is released.
I've setup my Action Filter:
public class ProductActionFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            ...
        }
        base.OnActionExecuted(filterContext);
    }

}

If I were to modify the controller, I could just add [ProductActionFilter] to the action I want it assigned to.
Is there a way I can register my custom Action Filter to a specific action without modifying the controller?

A: I think global filters is what you need.
Once you created the filter register it in the global.asax:
protected void Application_Start() {

    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new MyActionFilterAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Add custom validation logic to filter if you want to apply it not to all actions.

A: If you want your filter to be registered for every action (or it is otherwise OK to do so), then MVC 3 allows you to apply Global action filters.  Of course this requires that nopCommerce is built on MVC 3, which I believe the newest version is?

A: In NopCommerce 3.5 (the latest as of this answer, and newer than the question date), the best way I've found to add a global action filter is by creating a plugin with an IStartupTask implementation in it. This method completely avoids altering any NopCommerce core files.
The NopCommerce Application_Start event initializes the EngineContext, which creates the NopEngine instance. The NopEngine initialization finds all IStartupTask implementations, and executes them in their specified order. So an IStartupTask is the place to do anything that needs to happen on application start.
Sample code below:
public class Plugin : BasePlugin
{
    public Plugin()
    {
    }

    /// <summary>
    /// Check to see if this plugin is installed
    /// </summary>
    public static bool IsInstalled(ITypeFinder typeFinder)
    {
        IEnumerable<Type> types = typeFinder.FindClassesOfType<IPluginFinder>(true);

        if (types.Count() == 1)
        {
            IPluginFinder plugins = Activator.CreateInstance(types.First()) as IPluginFinder;
            PluginDescriptor descriptor = plugins.GetPluginDescriptorBySystemName("MyPluginName");

            if (descriptor != null && descriptor.Installed)
            {
                return true;
            }
        }

        return false;
    }
}

/// <summary>
/// Redirects to the 404 page if criteria not met
/// </summary>
public class FluffyTextureRequiredAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (Kitten.Texture != Textures.Fluffy)
        {
            var routeValues = new RouteValueDictionary();
            routeValues.Add("controller", "Common");
            routeValues.Add("action", "PageNotFound");

            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
    }
}

/// <summary>
/// Does application start event stuff for the plugin, e.g. registering
/// global action filters
/// </summary>
public class StartupTask : IStartupTask
{
    private ITypeFinder _typeFinder;

    public StartupTask()
    {
        //IStartupTask objects are created via Activator.CreateInstance with a parameterless constructor call, so dependencies must be manually resolved.
        _typeFinder = EngineContext.Current.Resolve<ITypeFinder>();
    }

    public void Execute()
    {
        // only execute if plugin is installed
        if (Plugin.IsInstalled(_typeFinder))
        {
            // GlobalFilters is in System.Web.Mvc
            GlobalFilters.Filters.Add(new FluffyTextureRequiredAttribute());
        }
    }

    public int Order
    {
        get { return int.MaxValue; }
    }
}

A: This approach works for NopCommerce 4.10
This code will redirect "/Register" requests with "GET" Method to "YourCustomAction" action inside "YourCustomController".
Step 1:
implement INopStartup
 public class NopStartup : INopStartup
 {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<MvcOptions>(config =>
            {
                config.Filters.Add<YourCustomActionFilter>();
            });
        }

        public void Configure(IApplicationBuilder application)
        {

        }

        public int Order => 0;
    }

Step 2 :
public class YourCustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!(context.ActionDescriptor is ControllerActionDescriptor actionDescriptor)) return;

        if (actionDescriptor.ControllerTypeInfo == typeof(CustomerController) &&
            actionDescriptor.ActionName == "Register" &&
            context.HttpContext.Request.Method == "GET")
        {
                    string controllerName = nameof(YourCustomController).Replace("Controller", "");
                    string actionName = nameof(YourCustomController.YourCustomAction);
                    var values = new RouteValueDictionary(new
                    {
                        action = actionName,
                        controller = controllerName
                    });
                    context.Result = new RedirectToRouteResult(values);
        }
    }
}

With this approach, you can cut down the registration process and add some extra check/process then you can go on the registration process.

A: What about creating a partial class. As of version 2.60 all controllers are partials:
public partial class CatalogController : BaseNopController

You can put the filter to the class and then query the action name.


text:
Q: Border color on Border-radius for safari I am trying to apply a border and a border color for a div with a border-radius. It works for all browsers except for safari. In safari the border radius work but the border and border color get messed up. Here is my code
#profilePic{
    border-radius: 100%;
    border: 3px solid #fff;
    box-shadow: 0 1px 2px rgba(0,0,0,0.4);
    background-color:white;
}

A: have try to draw the border with a box-shadow:inset 0 0 0 3px white; to avoid that gap  sometimes appearing in safari ?
http://codepen.io/gcyrillus/details/jbxDo


text:
Q: Eclipse ADT virtual machine won't start Please note this is not a duplicate. I have found no thread that solves my issue.
I opened up fresh install of eclipse adt with hello world example and opened Android Virtual Device Manager. Here, I added several devices with different configuration and hit start on each of them but all I got is starting virtual device then .. nothing happens. No log, no alert, nothing.
Things, I have tried:

*

*Wait 10 mins after run, nothing happend.

*Changed priority on adb.exe to real time

*Killed adb.exe (here, console started showing up Connection attempts: 1..2..3 ... nothing more)

*Changed perspective to DDMS. Here, no devices are found. Hitted "reset adb" (here, console shows An existing connection was forcibly closed by the remote host)

*In Window->Preferences->Android checked SDK location (no spaces)

*Run emulator.exe -avd test2 from command line  (emulator-arm.exe stop working)

*Installed different API. I had API 17 and I installed API 16 (all sub-things)

*Run configuration Lauch as ... (not Launch Def. Activity)

*Deleting avd's content in userdata fold and creating new

*Run as admin

*Check stackoverflow for all possible solutions

*Minor restarting, creating new AVD, different  settings, ram size and stuff..

notes:
- I have new PC, there are no performance issues possible
- I am using Adt bundle windows x86_64 - 2013 02 19 build 21.1.0-569685
- UAC and all those stuff disabled
- Windows 7 64-bit
- Again, Never made it to lock screen, no log available


text:
Q: Creating a BST from an array I need to create a binary search tree in the following (strange) way:
I am given an array (A[n]). A[1] becomes the root of the tree.

*

*Then, I insert A[1]+A[2] to the left subtree (subtree1, used below) of the root and also insert A[1]-A[2] to the right subtree (subtree2) of the root.

*I insert A[1]+A[2]+A[3] to the left subtree of subtree1 (subtree3) and A[1]+A[2]-A[3] to the right subtree of subtree1 (subtree4).

*Then, I insert A[1]-A[2]+A[3] to the left subtree of subtree2 (subtree5) and A[1]-A[2]-A[3] to the right subtree of subtree2 (subtree6).

*I repeat for subtree3, subtree4, subtree5, subtree6 until I reach the end of the array.
So, basically, the first element of the array becomes the root of the tree and then I move down: Every left subtree has for value the sum of its parent plus the next element of the array and every right subtree has for value the difference of its parent and of the next element in the array.
I understand I need to use the concept of recursion but in a modified way. Typing my problem here and trying to explain it to someone else apart from my brain actually made me form it in a way that gave me some ideas to try but I can see the problem I am dealing with being a usual problem so maybe you could give me some pointers on how to use recursion to build the tree.
Looking around at other questions and the discussions I understand there is a policy against asking whole solutions so I wanted to make it clear that I am not asking for the solution but for guidance to it. If someone would like to have a look I can show you what I've already done.

A: The way to do recursion is to always assume you already have a working function in hand. So let's see [using Java syntax]...
Tree buildTree(int currentSum, int[] array, int index, boolean sign);

Suppose that works. Then would do u need to do to build a tree at index i?
// current value to look at at this level
int curValue = array[index];
// depending on sign, it may be negative
if (!sign) {
  curValue *= -1;
}
// add it to the running total
int nodeValue = currentSum + curValue;
Node nd = new Node(nodeValue);

nd.left = buildTree(nodeValue, array, index + 1, true);
nd.right = buildTree(nodeValue, array, index + 1, false);

That's basically it. You need to take care of the edge cases: of index = array.length, creation of the very first node, and the like


text:
Q: PHP Warning: failed to open stream: No such file or directory, File Path Errors I am having trouble understanding how PHP chooses to compile or how including files within files works.
Here's my file structure:
I require secrets.php inside head.php.
I require head.php inside index.php.
head.php
require "../environment/secrets.php";

index.php
require "php/head.php";

I get an error:

Warning: require_once(../environment/secrets.php): failed to open
  stream: No such file or directory in /home/ubuntu/workspace/Cally
  Dai/php/head.php on line 2 Call Stack: 0.0002 234760 1. {main}()
  /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2.
  require_once('/home/ubuntu/workspace/Cally Dai/php/head.php')
  /home/ubuntu/workspace/Cally Dai/index.php:5 Fatal error:
  require_once(): Failed opening required '../environment/secrets.php'
  (include_path='.:/usr/share/php:/usr/share/pear') in
  /home/ubuntu/workspace/Cally Dai/php/head.php on line 2 Call Stack:
  0.0002 234760 1. {main}() /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2. require_once('/home/ubuntu/workspace/Cally Dai/php/head.php') /home/ubuntu/workspace/Cally Dai/index.php:5

where am I going wrong?

A: According to me, I feel that the path must be from root in ubuntu. Try your code with,
require_once("/home/ubuntu/workspace/Cally Dai/php/head.php")

A: When a PHP file includes another PHP file which itself includes yet another file — all being in separate directories — using relative paths to include them may raise a problem.

PHP will often report that it is unable to find the third file, but
  why? Well the answer lies in the fact that when including files in PHP
  the interpreter tries to find the file in the current working
  directory. In other words, if you run the script in a directory called
  A and you include a script that is found in directory B, then the
  relative path will be resolved relative to A when executing a script
  found in directory B. So, if the script inside directory B includes
  another file that is in a different directory, the path will still be
  calculated relative to A not relative to B as you might expect. This
  is a very important point to understand about the difference between
  PHP and other languages like C/C++.

One solution is to use dirname(__FILE__):

Use dirname(__FILE__) – The __FILE__ constant contains the full path
  and filename of the script that it is used in. The function dirname()
  removes the file name from the path, giving us the absolute path of
  the directory the file is in regardless of which script included it.
  Using this gives us the option of using relative paths just as we
  would with any other language, like C/C++. We would prefix all our
  relative path like this:

include(dirname(__FILE__) . "/dir/script_name.php");

Source: http://yagudaev.com/posts/resolving-php-relative-path-problem/


text:
Q: *Tensorflow Objection Detection API* mAP calculations for YOLO darkflow? so I would like to use to TF Object Detection API to calculate mAP scores for YOLO.
Currently I'm training my YOLO model and it is producing ckpt files/frozen graph files.
I would like to take my YOLO model and evaluate it using the TF Obj Dec API. I know Eval.py says

2) Three configuration files may be provided: a model_pb2.DetectionModel
configuration file to define what type of DetectionModel is being evaluated, an
input_reader_pb2.InputReader file to specify what data the model is evaluating
and an eval_pb2.EvalConfig file to configure evaluation parameters.
Example usage:
./eval \
    --logtostderr \
    --checkpoint_dir=path/to/checkpoint_dir \
    --eval_dir=path/to/eval_dir \
    --eval_config_path=eval_config.pbtxt \
    --model_config_path=model_config.pbtxt \
    --input_config_path=eval_input_config.pbtxt

However, with darkflow there is no model_pb2.DetectonModel Configuration file. Is this possible?


text:
Q: php redirect with custom user roles set and working but redirect not working for when users are logged in I have created code to add custom user rules. It works. However when I try to tie in the code for redirecting an already logged in user based on one test role, then it doesn't work. What am I missing in this in order to have it redirect, based on a user's role. Here is the code:
add_action('init', 'cloneRoleCompany');
function cloneRoleCompany(){
    global $wp_roles;
    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    $adm = $wp_roles->get_role('subscriber');
    //Adding a 'new_role' with all admin caps
    $wp_roles->add_role('company-admin', 'Company Admin', $adm->capabilities);
    $wp_roles->add_role('company', 'Company', $adm->capabilities);
    $wp_roles->add_role('user', 'User', $adm->capabilities);
}
function redirect_from_front_page() {
    $redirect_url  = '/user-dashboard';
    $expected_role = 'user';

    if( is_front_page() ) {
        return;
    }

    if( is_user_logged_in() ) {
        return;
    }

    $user  = wp_get_current_user();
    $roles = $user->roles;

    if ( in_array( $expected_role, $roles ) ) {
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

A: If the user is logged-in, the function returns before the redirect code lower in the function.
if( is_user_logged_in() ) {
    return;
}

Since you want the redirect code to run only if the user is logged in, try this:
if( ! is_user_logged_in() ) {
    return;
}


text:
Q: Issue with calling SOAP Web services using PHP Curl I want to fetch SOAP result using the following code but its returning "bool(false)". Can you point out what's missing in the below code:

<?php
$credentials = "username:password";
$url = "_https://xxxx.rightnowdemo.com/cgi-bin/xxxx.cfg/services/chat_soap";
$body = '<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns oapenv="_http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="urn:messages.chat.ws.rightnow.com/v1_1">
   <soapenv:Header>
      <v1:ClientRequestHeader>
         <v1:AppID>Chatws</v1:AppID>
      </v1:ClientRequestHeader>
   </soapenv:Header>
   <soapenv:Body>
      <v1:GetChatOperatingHours/>
   </soapenv:Body>
</soapenv:Envelope>'; /// Your SOAP XML needs to be in this variable

$headers = array(
                 "Content-type: text/xml;charset=\"utf-8\"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "SOAPAction: GetChatOperatingHours",
                "Content-length: ".strlen($body),
   );
//load_curl();
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $credentials);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Stuff I have added
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$data = curl_exec($ch);
curl_close($ch);
var_dump($data);

?>
Any inputs/suggestions are welcome
Thanks,
suresh


text:
Q: RAILS - HOW TO ADD VOTES IN A POLL I'm new to Rails and I'm using translate to post here.
I'm practicing rails and for that I set up a poll (voting) system.
Until then the voting is working normally, the votes are stored correctly, however, I would like to set up a screen on the frontend to display the result, and that's where I'm having difficulty.
How can I sum the votes from the PollOptions table of the "Votes" column. I would like to display it like this:
name: 10 votes or X% of votes
name: 10 votes or X% of votes
name: 10 votes or X% of votes
As I understand it, I need to create a method in the controller that will do this sum?
Any documentation links/tips, I'd appreciate it.
polls_controller
class PollsController < ApplicationController
  def index
    @poll = Poll.where(finished_at: nil).last
    @poll_options = @poll.poll_options.order :name
  end

  def vote
    @poll_option = PollOption.find params[:poll_option_id]
    @poll_option.increment! :votes

    respond_to do |format|
      format.turbo_stream { render :vote }
    end
  end
end

model:
poll
class Poll < ApplicationRecord
  has_many :poll_options
end

poll_option
class PollOption < ApplicationRecord
  belongs_to :poll
end

In this view, I would like to call the result of the vote.
view _poll.html.erb

      <%= @poll.name %>

        <%= @poll_options.pluck(:name).to_sentence(last_word_connector: ' ou ') %>

        <% @poll_options.each do |item| %>

            <%= button_to vote_url,
                method: :post,
                class: "btn btn-outline-secondary",
                params: { poll_option_id: item.id } do %>

              <%= item.name %>
              <%= image_tag item.photo, size: "40x40" %>

          <% end %>
        <% end %>

https://i.stack.imgur.com/JQfQP.png
Thanks in advance for any guidance.

A: You can use ActiveRecord::Calculations sum (.sum(:votes)) to sum all the rows for the votes column under poll_options.
To find all the votes of a poll you need the following
@poll.poll_options.sum(:votes)

Then to create the % for the PHP for example you could do
total_votes = @poll.poll_options.sum(:votes)
php_votes = @poll.poll_options.where(name: 'PHP').votes
(php_votes / total_votes).to_i * 100


text:
Q: Configure Camel Jetty endoint without specifying protocol, host and port In order to accept (in a Camel WAR application) uploaded files I need to expose a jetty endpoint and, in the jetty configuration, I'd like to not specify protocol, host, port and context root (I'd like to inherit these informations from the container WAR).
Is possible to do so? I've found no informations about this.

A: Solved as follows: instead of using jetty I used servlet
<camel:route id="servlet-route">
    <camel:from id="servletfrom" uri="servlet://provaservlet?disableStreamCache=true"/>
    <to id="servletto" uri="provaUploadProcessorId"/>
</camel:route>

In the processor provaUploadProcessorId I got the servlet request from the exchange body
HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);

and then I was able to read params and files as shown below
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                log.info("param name " + fieldName + ", param value " + fieldValue);
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                log.info("file param name " + fieldName + ", file param value " + fileName);
                InputStream fileContent = item.getInputStream();
                // do what you want with the file content and then close it
                fileContent.close();
            }
        }

Keep in mind to load these depencencies
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>


text:
Q: Axios Abort all Previous Requests Background: I have an infinite scroll component that continually makes requests to a third party API as the user gets to the bottom div. I'm running into a problem where if the user switches pages before the outstanding requests finish it creates a memory leak.
What I tried: I tried using a global cancel token as suggested in this answer to cancel all outstanding api requests, but this prevents all future requests.
Question: I'm looking for a way to cancel ALL current & previous requests across all my API calls, from outside the api file, while still allowing future requests.
My api file looks like this:
import React from 'react'
import axios from 'axios'

export const fetchAvatars = (query, amount) => {
  return axios.get('https://pixabay.com/api/', {
    params: {
      key: process.env.PIXABAY_API,
      q: query,
      orientation: 'vertical',
      per_page: amount,
      image_type: 'photo'
    }
  })
}

export const fetchVideos = (amount, category, editorsChoice, query) => {
  return axios.get('https://pixabay.com/api/videos/', {
    params: {
      key: process.env.PIXABAY_API,
      q: query,
      per_page: amount,
      category: category,
      editors_choice: editorsChoice,
      min_height: 1080,
      orientation: 'horizontal'
    }
  })
}

export const fetchVideoFromID = (id) => {
  return axios.get('https://pixabay.com/api/videos/', {
    params: {
      key: process.env.PIXABAY_API,
      id: id
    }
  }).catch(err => {
    if (!err.response) {
      console.log('network error, probably bad id')
    }
    else console.log(err)
  })
}

export const fetchPictureFromID = (id) => {
  return axios.get('https://pixabay.com/api/', {
    params: {
      key: process.env.PIXABAY_API,
      id: id
    }
  }).catch(err => {
    console.log(err)
  })
}

export const getRandomName = () => {
  return axios.get('https://randomuser.me/api/?nat=gb,au,ca')
}


text:
Q: Java 8 stream map to list of keys sorted by values I have map Map<Type, Long> countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:
countByType.entrySet().stream().sorted().collect(Collectors.toList());

however this just gives me a list of entries, how can I get a list of types, without losing the order?

A: You can sort a map by value as below, more example here
//Sort a Map by their Value.
Map<Integer, String> random = new HashMap<Integer, String>();

random.put(1,"z");
random.put(6,"k");
random.put(5,"a");
random.put(3,"f");
random.put(9,"c");

Map<Integer, String> sortedMap =
        random.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

A: Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values()
                       .stream()
                       .sorted()
                       .collect(Collectors.toList());

Output: [A, B, C, D]

A: You can use this as an example of your problem
    Map<Integer, String> map = new HashMap<>();
    map.put(10, "apple");
    map.put(20, "orange");
    map.put(30, "banana");
    map.put(40, "watermelon");
    map.put(50, "dragonfruit");

    // split a map into 2 List
    List<Integer> resultSortedKey = new ArrayList<>();
    List<String> resultValues = map.entrySet().stream()
            //sort a Map by key and stored in resultSortedKey
            .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
            .peek(e -> resultSortedKey.add(e.getKey()))
            .map(x -> x.getValue())
            // filter banana and return it to resultValues
            .filter(x -> !"banana".equalsIgnoreCase(x))
            .collect(Collectors.toList());

    resultSortedKey.forEach(System.out::println);
    resultValues.forEach(System.out::println);

A: Here is the simple solution with StreamEx
EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();

A: You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.
And you want to get the keys; use map to transform entries to keys.
List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

A: You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting
countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());


text:
Q: Ranking computed variables I am using the Cigarette dataset from the Ecdat package. I need to find the median annual rank of number of packs/capita sold between 1985 and 1995. As well as the lowest, whereby higher rank is defined as having a grater number of packs/capita.
I have tried to filter based on year and compute a median packs variable using median(packpc) and arrange by that mutated variable but continue to get error messages.
Any suggestions?

A: What you are looking for is summarize:
library(Ecdat)
library(dplyr)
Cigarette %>%
  filter(year>=1985, year<=1995) %>%
  summarise(min=min(packpc), median=median(packpc), max=max(packpc))
#>       min   median     max
#> 1 49.2722 105.9096 197.994

As you put the dplyr tag to this question, you might want to check out tutorials on this package.
PS: If this is your homework, you should state it clearly so we don't just give out the answer.

A: I guess the idea is to get the states' ranks for each year and then find the median and minimum of those ranks over the years.
Since the dataset only includes years 1985 to 1995, there is no need for filtering.
So I came up with this rather ugly solution:
ranks_perYear <- aggregate(packpc ~ year, Cigarette, rank)$packpc
colnames(ranks_perYear) <- levels(Cigarette$state)
medianRank <- apply(ranks_perYear, 2, median)
minRank <- apply(ranks_perYear, 2, min)

I am actually not entirely sure whether the states are assigned correctly here. Maybe the dataset has to be sorted by state (e.g., dplyr::arrange(Cigarette, state)) beforehand.


text:
Q: ipa extraction after you download an app from iTunes We are currently providing ios app via Itunes. The main function of the app is to verify `app integrity' and it is done by checking hash value (sha256) of the execution file in .ipa once we download it.
With the 32bit app we downloaded from iTunes, we can extract .ipa file to get execution file without problems. However, it does not seem to be possible with 64bit ios apps. (maybe there is a way and we couldn't find it. if this is the case please enlighten us.) Since we are planning provide our service both with 32 and 64bit, we do need to extract execution file from 64bit app.
So there are two questions we would like to ask regarding on this ipa extraction.
1. The hash value(sha256) of the app before we upload to iTunes and the value after we download it from iTunes is different. Why is that?
2. Is there any way we can extract .ipa (32/64 bit both) after we download the app from iTunes?


text:
Q: Recovering RAID5 - using Linux "mdadm" Using Linux mdadm to recover from failed disk / partition.
Here  are titles of the steps I took so far - I can post detailed copy if it helps.
( I am not sure how to post file link here...)
The last response to "run" is :
nov25-1@nov251-desktop:~$ sudo mdadm --run /dev/md0
mdadm: failed to start array /dev/md/0: Input/output error
nov25-1@nov251-desktop:~$

What would be my next step to "activate" the array ?
nov25-1@nov251-desktop:~$ cat /proc/mdstat  1
nov25-1@nov251-desktop:~$ cat /proc/mdstat  2
nov25-1@nov251-desktop:~$ sudo mdadm --assemble /dev/md0    3
nov25-1@nov251-desktop:~$ sudo mdadm --assemble --force /dev/md0    3
nov25-1@nov251-desktop:~$ sudo mdadm --detail /dev/md0  4
nov25-1@nov251-desktop:~$ sudo mdadm --run /dev/md0recovering

A: Wouldn't the next step be to mount it?
I think I've used this guide before, maybe it will help you out?
https://kb.synology.com/en-uk/DSM/tutorial/How_can_I_recover_data_from_my_DiskStation_using_a_PC
You should definitely consider whether any disk has failed because trying to recover with a faulty drive still in place may be worse than removing it. I'd at least try to check out the SMART status of each disk. The read-only nature of the setup in the article means if you get it wrong it won't damage your array, you can just start over with more or different disks.


text:
Q: Perl loop stuck reading file? Closing this question. Will drink red bull. Sleep. Code and come back with brand spanking new question with unit test cases.
UPDATE: The new file is here
Also the config file is here
I refactored the code again:
sub getColumns {
    open my $input, '<', $ETLSplitter::configFile
        or die "Error opening '$ETLSpliter::configFile': $!";

    my $cols;
    while( my $conline = <$input> ) {
        chomp $conline;
        my @values = split (/=>/, $conline);
        if ($ETLSplitter::name =~ $values[0] ) {
            $cols = $values[1];
            last;
        }
    }

    if($cols) {
        @ETLSplitter::columns = split (':', $cols);
    }
    else {
        die("$ETLSplitter::name is not specified in the config file");
    }
}

This code always dies here die("$ETLSplitter::name is not specified in the config file");.
Another clue is that if I change split (':', $cols); to split (/:/, $cols); I get this error.
 perl -wle "
 use modules::ETLSplitter;
 \$test = ETLSplitter->new('cpr_operator_metric_actual_d2', 'frame/');
 \$test->prepareCSV();"
 syntax error at modules/ETLSplitter.pm line 154, near "}continue"
 Compilation failed in require at -e line 2.
 BEGIN failed--compilation aborted at -e line 2.

A: FINAL POST FOR THIS QUESTION: Based on your latest updates, I believe the following code illustrates how there is no problem with using /:/ as the first argument to split. It also points out that it is easier to read code when one uses arguments to functions rather than relying on global variables:
#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

for my $varname ( qw( adntopr.cpr.smtref.actv cpr_operator_detail )) {
    print $varname, "\n";
    print Dumper get_columns(\*DATA, $varname);
}

sub get_columns {
    my ($input_fh, $varname) = @_;

    while ( my $line = <$input_fh> ) {
        chomp $line;
        my @values = split /=>/, $line;
        next unless $varname eq $values[0];
        return [ split /:/, $values[1] ];
    }
    return;
}

__DATA__
adntopr.cpr.smtref.actv=>3:8:18:29:34:38:46:51:53:149
adntopr.smtsale2=>3:8:16:22:27:37:39:47:52:57:62:82:102:120:138:234:239:244:249:250:259:262:277:282:287:289:304:319:327:331:335:339:340:341:342:353:364:375:386:397:408
cpr_operator_detail=>3:11:18:28:124:220:228:324
cpr_operator_org_unit_map=>7:12
cpr_operator_metric_actual=>8:15:25:33:38:40:51

C:\Temp> tjm
adntopr.cpr.smtref.actv
$VAR1 = [
          '3',
          '8',
          '18',
          '29',
          '34',
          '38',
          '46',
          '51',
          '53',
          '149'
        ];
cpr_operator_detail
$VAR1 = [
          '3',
          '11',
          '18',
          '28',
          '124',
          '220',
          '228',
          '324'
        ];

There is a lot of cruft in that code. Here is my interpretation of what you are trying to do:
UPDATE: Given your recent remark about regex special characters in patterns, if you are going to use them in the pattern to split, make sure to quote them. There is also a chance that $ETLSpliter::name might contain other special characters. I modified the code to deal with that possibility.
sub getColumns {
    open my $input, '<', $ETLSpliter::configFile
          or die "Error opening '$ETLSpliter::configFile': $!");
      my @columns;
      while( my $conline = <$input> ) {
          my @values = split /=>/, $conline;
          print "not at: ".$conline;
          push @columns, $values[1] if $values[0] =~ /\Q$ETLSpliter::name/;
      }
      return @columns;
  }

ANOTHER UPDATE:
So, the pattern indeed is /=>/ based on your comment below. Then:
my $conline = q{cpr_operator_detail=>3:11:18:28:124:220:228:324};
my @values = split /=>/, $conline;

use Data::Dumper;
print Dumper \@values;
__END__

C:\Temp> tml
$VAR1 = [
          'cpr_operator_detail',
          '3:11:18:28:124:220:228:324'
        ];

No errors ... No warnings Therefore, there is something else that is going on which you insist on not showing us.
Other Remarks:

*

*Use lexical filehandles and let perl tell you what errors it may encounter rather than presuming.

*Declare variables in the smallest applicable scope.

*No need to assign $_ to $conline in the body of the loop when you can do that in the while statement.

*In the original code, you were not putting anything in @columns or doing anything useful with $colData.

*Tone down the rhetoric. Computers work on the principle of GIGO.

*Looking at the code at the link you posted, it looks like you are not aware that you can do:
use File::Spec::Functions qw( catfile );
...
catfile($ETLSpliter::filepath_results, $ETLSpliter::actual_name);

Further, it looks like you are using a package where hash would have done the job:
$ETLSpliter{filepath}

Finally, you do realize Spliter is incorrect. ITYM: Splitter.

A: Are you sure that it's stuck? You never store any data in @columns, so your code will always return an empty list.
Other notes:

*

*Your die call should include $! (OS error). There are other reasons that the open could fail besides a non-existent file, and $! will tell you what the real problem was.

*You should probably do a chomp $conline to get rid of the newline.

*You can do while (my $conline = <CFILE>) instead of copying the value from $_.

*Two-argument open (particularly with an implicit < mode) is poor form. Using the three-argument form (ideally with a lexical filehandle) is preferred: open(my $fh, '<', $filename) or die...

A: What's in $ETLSpliter::name - any / chars there should be escaped.
Many other issues in the snippet have already been addressed so I won't go there.

A: FINALLY FIGURED IT OUT!!!!! Wow Sleep is awesome power.
Anyway. The problem was in $ETLSplitter::configFile in my die message.
die ('Error opening '.$ETLSpliter::configFile.': '.$!);

Which has winblows path separators '/'. So because I was outputting in double quotation, perl interperted the '/' in the path as patterns. From here
die "Error opening some/path/to/ ...

to
...  /=>/,

Which messed with the entire program flow in the subroutine. This was solved by doing this.
die ('Error opening '.$ETLSpliter::configFile.': '.$!);


text:
Q: How pass extra param from html to controller Spring Boot 2.5, Thymeleaf
I need when click submit to pass object Product and additional extra param (quantity)
html template:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${appName}">Category template title</title>
    <link th:href="@{/public/style.css}" rel="stylesheet"/>
    <meta charset="UTF-8"/>
</head>
<body>
<div class="container">
    <h3 th:text="*{title}"/>
    <form method="post" action="#" th:object="${product}" th:action="@{/product}">
        <input type="hidden" id="id" th:field="*{id}"/>
        <input type="text" placeholder="Name" id="name" th:field="*{name}" th:disabled="${isView}"/>
        <input type="hidden" id="created" th:field="*{created}"/>
        <textarea placeholder="Description" rows="5" id="description"
                  th:field="*{description}" th:disabled="${isView}"></textarea>
        <input type="number" placeholder="Price" id="price" th:field="*{price}" th:disabled="${isView}"/>
        <input type="text" placeholder="Currency" id="currency" th:field="*{currency}" th:disabled="${isView}"/>
        <input type="text" placeholder="Images URL(separate by comma)" id="images" th:field="*{images}" th:disabled="${isView}"/>
        <input th:type="${isView} ? hidden : submit" value="Submit"/>
    </form>
</div>
</body>
</html>

and here my controller:
 @RequestMapping("cart/add")
    public String addProduct(Model model) {
        logger.info("addProduct");
        model.addAttribute("isAdd", true);
        model.addAttribute("product", new Product());
        model.addAttribute("title", "Add Product");
        model.addAttribute("viewMode", ViewMode.ADD);
        return "product";
    }

    @PostMapping(value = "/product")
    public String submitProduct(Product product, Model model) {
        logger.info("submitProduct = " + product);
        if (product.getId() == 0) { // add category
            product.setCreated(new Date());
        } else { // update category
            product.setUpdated(new Date());
        }
        return "redirect:/cart";
    }

So when click button Submit call submitProduct with fill object Product. But I need to pass extra param (as second param in method submitProduct) - quantity.
How I can pass this extra int  param from html to controller?

A: One option is to access the value directly from the request parameters.
Assuming the quantity value is available in the form as an input field, with a name of quantity (looks like it is not there at the moment), then you can alter your controller to use this:
import org.springframework.web.bind.annotation.RequestParam;

And then change the relevant method signature to something like this:
public String submitProduct(Product product, Model model,
        @RequestParam(name = "quantity") String quantity) {...}

(Field validation of some kind would also be needed, I assume.)


text:
Q: linear transformation such that image equals kernel Construct a linear transformation T : R4 → R4 such that Kernel(T) = Image(T). How about the same for a linear transformation S : R5 →R5.

A: Take a base $v_i$ and a map $v_1 \mapsto 0$, $v_2\mapsto 0$, $v_3 \mapsto v_1$ and $v_4 \mapsto v_2$, the kernel and image seems isomorphic.
For odd dimensional spaces, the dimension will provide obstruction, because since isomorphic spaces have the same dimension:
$$
\dim \ker S + \dim \text{Im } S  = 2 \dim \ker S  = 5
$$

A: Take $T:(a,b,c,d)\mapsto (c,d,0,0)$  for $\mathbb R^4$,
but for $\mathbb R^5$ there is none,
because dim(Ker)+dim(Im)=dim(space),
so if dim(Ker)=dim(Im) then dim(space) is even.


text:
Q: img src variable not displaying pictures I have a list of image files inside mrtg/images directory. Files names are like:
router-day.png
router-week.png
switch-day.png

What I am trying to do is display image popup based on $hostname but it is not displaying any images;
 $hostname = router;
<img src="mrtg/images/<? echo $hostname;?>-day.png">

This is not working. If I put manually the filename then image is displayed.

Any suggestion why it is not displaying images?
thank you

A: As someone told you, this will never work:
$hostname = router;
<img src="mrtg/images/<? echo $hostname;?>-day.png">

Two problemes there:
1 - The variable you are using, $hostname, isn't correctly assigned.
2 - You are mixing HTML and PHP.
The correct code should look more like this:
<?php
$hostname = 'router';
?>
<img src="mrtg/images/<? echo $hostname; ?>-day.png">

But this could be because you didn't provide an EXACT example of your code. If not, please do it.
Also I would encourage you to do this:
<img src="mrtg/images/<?php echo $hostname; ?>-day.png">

Or this:
<img src="mrtg/images/<?=$hostname?>-day.png">