text:
Q: Want a better way to deploy java.util.ResourceBundle properties files with Java application I am teaching myself Java program localization using java.util.Locale and java.util.ResourceBundle.  To this end I wrote a very simple Java app to test English, French and default language message bundles.  The program works fine.  I am running Eclipse Kepler SR2 on Windows.
My question relates to the deployment of the properties files used by ResourceBundle.getBundle (I will get to my question below) but first a bit about what I have already tried in terms of laying out my demo app and deploying it.
When I first called ResourceBundle.getBundle (see LocaleWrapper.java, below) I discovered the path it searches defaults to the deployment bin folder.
The ResourceBundle Javadoc doesn't talk about deployment folders, nor does the Oracle tutorial on Java internationalization that I was following.
So, to avoid dumping my properties files all in bin, I settled on creating a separate package (demo.locale) for my locale wrapper class and added all of the properties files to that package, as follows:
My Eclipse project named LocaleDemo consists of 5 source files in 2 packages, as follows:
src/demo/DemoApp.java
src/demo.locale/LocaleWrapper.java (wraps java.util.Locale, java.util.ResourceBundle)
src/demo.locale/MessageBundle.properties (default messages, same as English/US)
src/demo.locale/MessageBundle_en_US.properties (English/US messages)
src/demo.locale/MessageBundle_fr_FR.properties (French/France messages)

When the application is deployed it ends up under the bin folder, as follows:
bin/demo/DemoApp.class
bin/demo/locale/LocaleWrapper.class
bin/demo/locale/MessageBundle.properties
bin/demo/locale/MessageBundle_en_US.properties
bin/demo/locale/MessageBundle_fr_FR.properties

(I excluded package info files from these lists for clarity.)
So to get to my actual question:
My concern with this type of deployment is that it mixes properties files with class files.
I tried to separate them by creating a data folder at the same level as my src folder in Ecipse, and I put all the properties files in there, and added the data folder to my build path; however, when I deployed the app all of the properties files simply end up in the bin folder at the top level above the package folders (e.g. bin/MessageBundle.properties).
This was not satisfactory, so I reverted to putting them with the demo.locale package.  The layout I settled on was accepted as an answer in this stackoverflow question:
However, I do agree with another poster in that thread who said to separate classes and data, which is what I would prefer, but there was no example given how to do that.
So that is my question: is there a clean way in Eclipse to create a distinct data folder for the application and have the properties files deployed in that folder, not just dumped at the root folder of the project, which is what happened when I tried it.
I am looking for some specific examples of what programmers have done, or even better a reference to some official documentation on this subject -- I could not find anything specifically mentioning how this might be done in practice, only generalities.
As an appendix I have included the source code for my two Java classes below.  The resource files I use are straight from the Oracle tutorial that I linked above.
DemoApp.java
package demo;

import demo.locale.LocaleWrapper;

public class DemoApp {

    public static void main(String[] args) {

        LocaleWrapper intl = null;

        // English/USA
        intl = new LocaleWrapper("en", "US");
        doTest(intl);

        // French/France
        intl.changeLocale("fr",  "FR");
        doTest(intl);

        // non-existent language/country will use default
        intl.changeLocale("sp", "MX");
        doTest(intl);

    }

    private static void doTest(LocaleWrapper intl) {
        System.out.println("Testing: " + intl.getLanguage() + "_" + intl.getCountry());
        System.out.println("  " + intl.getString("greetings"));
        System.out.println("  " + intl.getString("farewell"));
        System.out.println("  " + intl.getString("inquiry"));
        System.out.println();
    }
}

LocaleWrapper.java
package demo.locale;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Internationalization using java.util.Locale and java.util.ResourceBundle.
 */
public class LocaleWrapper {

    private static final String PATH = "demo/locale/MessageBundle";

    private String language = null;
    private String country = null;
    private Locale locale = null;
    private ResourceBundle messages = null;

    public LocaleWrapper(String language, String country) {
        super();
        this.language = language;
        this.country = country;
        this.locale = new Locale(language, country);
        messages = ResourceBundle.getBundle(PATH, this.locale);
    }

    public void changeLocale(String language, String country) {
        this.language = language;
        this.country = country;
        this.locale = new Locale(language, country);
        messages = ResourceBundle.getBundle(PATH, this.locale);
    }

    /**
     * Get an internationalized string based on it's key.
     *
     * @param key
     *            Message key.
     * @return Internationalized message string.
     */
    public String getString(String key) {
        return messages.getString(key);
    }

    // getters

    public String getLanguage() {
        return language;
    }

    public String getCountry() {
        return country;
    }

}

A: Don. You just give a long-long question.
you can specify a resouce folder to palce the resource bundle.
I study question 10911708 And do a example program and it work.
Here is what I did:
Step1: create a resource folder(here,I named it resource) in the same level as src (I use eclipse) folder,and put the properties file  in this folder.
Remember to use native2ascii to encode the text to different languange utf8 like:
native2ascii -encoding utf8 MessagesBundle_zh_CN.properties

then you get :
greetings = \u4f60\u597d.(你好)
farewell = \u518d\u89c1.(再见)
inquiry = \u4f60\u597d\u5417?(你好吗?)

save these utf8 text to properties file or you will get messy code.
step2:  for two cases:
A. visit resource bundle in jar file (package your project to a runnable jar)
In your code,visit the source bundle like:
 Locale currentLocale = new Locale(language, country);

  ResourceBundle messages =
    ResourceBundle.getBundle("resource.MessagesBundle",currentLocale);

  System.out.println(messages.getString("greetings"));
  System.out.println(messages.getString("inquiry"));
  System.out.println(messages.getString("farewell"));

B. visit your resource bundle in eclipse project.
you should click the project properties,and add resource folder in the java build path ,
and then eclipse will automatically copy these files to bin derectory ,
and you should write the path like:
ResourceBundle messages =
        ResourceBundle.getBundle("MessagesBundle",currentLocale);

without Prefix "resource".
My test result in jar file is:
D:\>java -jar Sample.jar zh CN
你好.
你好吗?
再见.

you can get this demo from: oracle website ,hope it help!


text:
Q: How do I make 2 PWA's under same root domain I have a folder under which I have 2 react apps.
app 1 - abc.com
app 2 - abc.com/Shop
currently, when I am installing any one of the PWA by adding to the homescreen, it doesn't show the add to the homescreen for the other app.
app 1 manifest -
{
  "short_name": "abc",
  "name": "abc",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

app 2 manifest
{
    "short_name": "abc shop",
    "name": "abc shop",
    "icons": [
        {
            "src": "favicon.ico",
            "sizes": "64x64 32x32 24x24 16x16",
            "type": "image/x-icon"
        },
        {
            "src": "logo192.png",
            "type": "image/png",
            "sizes": "192x192"
        },
        {
            "src": "logo512.png",
            "type": "image/png",
            "sizes": "512x512"
        }
    ],

    "start_url": "https://abc.in/Shop",
    "scope": "/shop-user/",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#ffffff",
    "orientation": "portrait"
}

How should I set up my manifest soo that if I install app 1 and then go to app 2 still it should show for add to the home screen popup

redpajama_set_name: RedPajamaStackExchange


text:
Q: NullPointerException when creating GoogleApiClient instance I've started creating Watch Face for Android Wear. I've implemented almost everything and now I want to show on the face the phone battery. From what I understood after my research this is only doable via Message or Data Layer API. So I've started working in his area but I'm facing a problem in the very beginning. I cannot connect to Google Api Client.
I have two classes under "wear" - one generic for the watch (service) and one created by me:
public class BatteryActivity extends Activity {

    GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks( new ConnectionCallbacks() {
            @Override
            public void onConnected(Bundle connectionHint) {
                Log.i( "", "onConnected: " + connectionHint);
                // Now you can use the Data Layer API
            }
            @Override
            public void onConnectionSuspended(int cause) {
                Log.i( "", "onConnectionSuspended: " + cause);
            }
        })
        .addOnConnectionFailedListener( new OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(ConnectionResult result) {
                Log.i( "", "onConnectionFailed: " + result);
            }
        })
                // Request access only to the Wearable API
        .addApi(Wearable.API)
        .build();
}

Whan I simply instance it like this: BatteryActivity batteryActivity = new BatteryActivity();
I get this error:

java.lang.NullPointerException: Attempt to invoke virtual method
  'android.os.Looper android.content.Context.getMainLooper()' on a null
  object reference

I don't understand how mGoogleApiClient is null if I've instance it.
As a note - this is purely based on google documentation here - https://developer.android.com/training/wearables/data-layer/messages.html

A: I suppose you should build the GoogleApiClient on onCreate method. Your code would be like this:
public class BatteryActivity extends Activity {

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

        GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks( new ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    Log.i( "", "onConnected: " + connectionHint);
                    // Now you can use the Data Layer API
                }
                @Override
                public void onConnectionSuspended(int cause) {
                    Log.i( "", "onConnectionSuspended: " + cause);
                }
            })
            .addOnConnectionFailedListener( new OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    Log.i( "", "onConnectionFailed: " + result);
                }
            })
        // Request access only to the Wearable API
        .addApi(Wearable.API)
        .build();
    }
}

A: It also happens when not providing proper context. Pass context like this :
mGoogleApiClient = new GoogleApiClient.Builder(context) // Pass context here
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();

A: Ideally this should be done via Async task: https://developer.android.com/google/auth/api-client.html#Communicating
private class WatchTask extends AsyncTask<String, Void, Void> {
    protected void doInBackground(String text) {

Or for a quick fix, you may just be using this in the wrong spot:
In your onCreate use getActivity() or this to use a Context for this line:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)

I would also suggest checking out: http://developer.android.com/training/wearables/data-layer/index.html
If you really want to use an activity, then it would look something like:
public class MainActivity extends Activity  implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, MessageApi.MessageListener {

    private GoogleApiClient googleClient; // A google client for Wear interaction

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Build a new GoogleApiClient that includes the Wearable API
        googleClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Wearable.MessageApi.addListener(googleClient, this);
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        //Same onMessageReceived as in WearableListenerService
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) { }
    @Override
    public void onConnectionSuspended(int i) { }
}


text:
Q: MacOS Sierra Launch Daemon won't start VPN service before login prompt I'm trying to get a new MacBook Pro running the latest version of Sierra to connect to my corporate VPN before the login screen. My machine is connected via Ethernet so I don't have to try and start Wi-Fi service prior to login. My command line script to connect to the VPN works fine in terminal. I know the file needs to be placed in /Library/LaunchDaemons/ but I'm not sure how to make sure it's processing before getting to the login screen. I'm new to writing plist files, so any help would be appreciated!
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
<dict>
<key>Label</key>
<string>com.vpn_at_boot</string>
<key>ProgramArguments</key>
<array>
    <string>sh</string>
    <string>-c</string>
    <string>sudo /usr/local/Cellar/sstp-client/1.0.11_1/sbin/sstpc vpn-hidden.hidden.com --user <hidden> --password <hidden> --log-stderr --cert-warn require-mschap-v2 noauth refuse-eap noccp</string>
</array>
<key>RunAtLoad</key>
<true/>

A: Your plist contains major errors and minor glitches. The proper plist - including stderr and stdout - looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.vpn_at_boot</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>-c</string>
        <string>/usr/local/sbin/sstpc vpn-redacted.redacted.com --user redacted --password redacted --log-stderr --cert-warn require-mschap-v2 noauth refuse-eap noccp</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/tmp/com.vpn_at_boot.err</string>
    <key>StandardOutPath</key>
    <string>/tmp/com.vpn_at_boot.out</string>
</dict>
</plist>

Replace redacted with the proper domain name, user and password in your plist.
Your plist misses important tags (e.g. </dict> and </plist>). It contains unnecessary stuff like sudo. The sstp-client may be updated later, so use its link in /usr/local/sbin. I also recommend to add /usr/local/sbin to /etc/paths.
The plist permissions have to look like this:
-rw-r--r--  1 root  wheel  - 682 Jun  9 13:38 /Library/LaunchDaemons/com.vpn_at_boot.plist

After running the daemon successfully (i.e. without errors) you may remove the keys StandardErrorPath and StandardOutPath and their corresponding strings in the plist.

A: Once your plist is in the correct spot, /Library/LaunchDaemons, it should be OK.
LaunchAgents and LaunchDaemons are not easy to control or test. Can I suggest you grab a copy of Lingon which has a good GUI interface for the job, including testing.


text:
Q: css transparent triangle with border Is it possible to style(skew) triangle like on the picture on the right side?
http://s15.postimg.org/h2vruavmz/triangle.jpg
I want to skew it, make background transparency 0.5 and hide bottom border of the triangle.

body {
    background-color: #ccc;
}
.arrow_box {
 position: absolute;
    top: 40px;
    left: 40px;
 background: #fff;
 /*border: 1px solid #ffffff;*/
}
.arrow_box:after, .arrow_box:before {
 bottom: 100%;
 left: 50%;
 border: solid transparent;
 content: " ";
 height: 0;
 width: 0;
 position: absolute;
 pointer-events: none;
}

.arrow_box:after {
 border-color: rgba(0, 0, 0, 0);
 border-bottom-color: #fff;
 border-width: 20px;
 margin-left: -20px;
}
.arrow_box:before {
 border-color: rgba(255, 255, 255, 0);
 border-bottom-color: #000;
 border-width: 21px;
 margin-left: -21px;
}

A: you can use transform: skew(60deg,0deg); on the :before and :after

body {
    background-color: #ccc;
}
.arrow_box {
 position: absolute;
    top: 40px;
    left: 40px;
 background: #fff;
 /*border: 1px solid #ffffff;*/
}
.arrow_box:after, .arrow_box:before {
 bottom: 100%;
 left: 50%;
 border: solid transparent;
 content: " ";
 height: 0;
 width: 0;
 position: absolute;
 pointer-events: none;
    transform: skew(60deg,0deg);
}

.arrow_box:after {
 border-color: rgba(0, 0, 0, 0);
 border-bottom-color: #fff;
 border-width: 20px;
 margin-left: -12px;
}
.arrow_box:before {
 border-color: rgba(255, 255, 255, 0);
 border-bottom-color: #000;
 border-width: 24px;
 margin-left: -21px;
}

Fiddle
I don't think you'd be able to make that background transparent easily with the technique you have used to draw triangles. You should use png image if you can.

A: The method you are currently using means that you will not be able to set a semi transparent "background" on the triangle. This is because the black borders of the triangle are actually a slightly larger separate triangle, it just happens that the smaller white triangle is overlaying its center. If you modify the white triangle's opacity then you will just peek through to the black triangle.
This can be avoided by using another method to create the triangle. The general principle is to create a box then turn it on its side using transform: rotate(45deg);. Using overflow: hidden; on the container you can cut off half of the box to leave you with a triangle without a bottom border.
You can then skew the container using transform: skewX(55deg); to push the triangle to one side.

body {
  background-color: #ccc;
}
.arrow_box {
  height: 17px;
  left: 40px;
  overflow: hidden;
  position: absolute;
  top: 40px;
  transform: skewX(55deg);
  width: 34px;
}
.arrow_box:after {
  background-color: rgba(255, 255, 255, 0.5);
  border: 2px solid rgba(0, 0, 0, 1);
  content: " ";
  height: 20px;
  left: 5px;
  position: absolute;
  top: 5px;
  transform: rotate(45deg);
  width: 20px;
}


text:
Q: Disable cron jobs for a specific user I have a list of jobs in the crontabs for user1, user2. I want to prevent the jobs of user2 from running.
I tried listing user2 in cron.deny, but that only prevents him from accessing his crontab. The  jobs listed in user2's crontab still get executed.
How do I disable cron jobs for a specific user?

A: Brute force!
crontab -u fred -e
%s/^/#/
:wq

There's probably a more elegant way to do it, but unless you are doing this all the time, use the hammer you have.

A: The easiest way to disable the crontab for a specific user is to locate her crontab and rename it. The Debian man page for cron says:
cron searches its spool  area  (/var/spool/cron/crontabs)  for  crontab
files  (which  are named after accounts in /etc/passwd); crontabs found
are loaded into memory.

So just rename the file to something that is not in the passwd, usually by giving it a suffix like disabled, offline, dead or similar.
mv -vi /var/spool/cron/crontabs/user2 /var/spool/cron/crontabs/user2.disabled

On Debian (and related systems like Ubuntu) this produces the following entry in /var/log/syslog:
(user2.disabled) ORPHAN (no passwd entry)

Make sure to also add user2 to the file /etc/cron.deny, otherwise the user will be able to create a new crontab for herself.
Re-enable the user's crontab by deleting the entry from /etc/cron.deny and renaming her crontab:
mv -vi /var/spool/cron/crontabs/user2.disabled /var/spool/cron/crontabs/user2

A: Delete /var/spool/cron/user1 or user2 ? and you also want to add these user names to /etc/cron.deny otherwise they can add those cron jobs back

A: crontab -r username works on Solaris to remove the crontab for a given username.
If -r doesn't work for you, then try:
su username 'sh -c "crontab /dev/null"'
Quicker to type and easier to script than crontab -e.

A: If you want to block the crontab job for a particular user make sure that your logged in with root user,root user only have access for crontab files.
1.Then go to the dir /etc/cron.d in this directory you can see that cron.deny file,make an enter of particular user name which user want to block by using vi editor or orther.


text:
Q: Python passing Oracle Cursor as parameter to Oracle Stored procedure I am trying to passing the Oracle Cursor from python to Oracle Stored Procedure(SP). The requirement is that SP fetch the data and insert the data into the table.
The SP take two parameters- p1 and p2, p1->VARCHAR2 and p2 is sys_refcursor.
Below is the Stored Procedure details:
p2 is sys_refcursor, the data will be in concatenated format (col1|col2|...)
CREATE OR REPLACE PROCEDURE pt1 (p1 IN VARCHAR2,
                             p2 IN sys_refcursor)
IS
    t VARCHAR2(32767);
    v_err_cd       NUMBER;
    v_err_msg      VARCHAR2(32767);
BEGIN
     LOOP
          fetch p2
          into t;

          INSERT INTO LIBRA.test_2(col1,col2)
          VALUES(p1,t);
          EXIT WHEN p2%NOTFOUND;
    END LOOP;
    COMMIT;
EXCEPTION
  WHEN OTHERS
  THEN
      rollback;
      v_err_cd  := SQLCODE;
      v_err_msg := v_err_msg || 'SQL Error:' ||     SUBSTR(dbms_utility.format_error_stack() || chr(10)  ||   dbms_utility.format_error_backtrace(),1,300);
      RAISE_APPLICATION_ERROR (-20101,'Error Code : ' || v_err_cd || 'Exception :  ' || v_err_msg );
END pt1;

Python Code:
srcqry = "select col1 || '|' || col2 from TEST rownum < 2"

oraconn = qz.core.sqldbs.connect(DBContext.getOracleConnectionName()) ##TODO Add a cursor in dbcontext
qzdb = qz.data.qztable_dbapi.QzTableSql(oraconn)
cur = qzdb.conn.cursor()
result = cur.execute(srcqry)
print "type of result",type(result) # type 'OracleCursor'
lineStr = 'Call1'
cur.callproc("LIBRA.pt1",[linestr,result])
cur.close()
qzdb.conn.close()

Getting "DatabaseError: ORA-01036: illegal variable name/number" in the line
cur.callproc("LIBRA.pt1",[linestr,result])
Please help!
Thanks,
Bala

A: All database object names are UPPERCASE by default in Oracle, even if they're lowercase in your source code. The solution is to change your invocation of cur.callproc to use "LIBRA.PT1" instead of "LIBRA.pt1".
Best of luck.


text:
Q: CSV load into Dataframe with filename as additional column in pyspark I'm trying to create a dataframe from a directory full of csv files but I want to keep the filename of each file on the dataframe as an additional column, is that possible on pyspark without using pandas?, also I want to remove the path from the filename.
from pyspark.sql.functions import input_file_name

df = spark.read.option("delimiter", "\t").csv(mount_point_input)
df_.withColumn("filename", input_file_name())

I tried using input_file_name() but all rows on the dataframe got the same filename.
Input:
False    2021-06-05T14:45:09     Server       True
True     2021-06-02T21:32:42     Server       True

Output:
+-----+-----------------------+-------+-------+--------------------------------+
False  2021-06-05T14:45:09     Server   True   /2021-06-02-general/c32d3f47.csv
+-----+-----------------------+-------+-------+--------------------------------+
False  2021-06-02T21:32:42     Server   True   /2021-06-02-general/c32d3f47.csv
+-----+-----------------------+-------+-------+--------------------------------+

Expected output:
+-----+-----------------------+-------+-------+--------------------------------+
False  2021-06-05T14:45:09     Server   True   c32d3f47.csv
+-----+-----------------------+-------+-------+--------------------------------+
False  2021-06-02T21:32:42     Server   True   c32d3f48.csv
+-----+-----------------------+-------+-------+--------------------------------+

A: You can use os.path.basename within a UDF -
>>> from pyspark.sql.functions import input_file_name,udf
>>> from pyspark.sql.types import StringType
>>> from os.path import basename
>>>
>>> data = [("/home/user/test/File1.txt",10),
...         ("/home/user/test/File2.txt",20),
...         ("/home/user/test/File3.txt",30),
...         ("/home/user/test/File4.txt",40),
...         ("/2021-06-02-general/c32d3f47.csv",50),
...         ("/2021-06-02-general/c32d3f47.csv",50)
...         ]
>>>
>>>
>>> cols = ["file_path","dummy_value"]
>>> testDF = spark.createDataFrame(data=data, schema = cols)
>>>
>>> testDF.show(truncate=False)
+--------------------------------+-----------+
|file_path                       |dummy_value|
+--------------------------------+-----------+
|/home/user/test/File1.txt       |10         |
|/home/user/test/File2.txt       |20         |
|/home/user/test/File3.txt       |30         |
|/home/user/test/File4.txt       |40         |
|/2021-06-02-general/c32d3f47.csv|50         |
|/2021-06-02-general/c32d3f47.csv|50         |
+--------------------------------+-----------+

>>>
>>>
>>> @udf(StringType())
... def return_filename(inp):
...     if inp:
...       return basename(inp)
...     else:
...       return None
...
>>> testDF = testDF.withColumn("file_name", return_filename('file_path'))
>>> testDF.show(truncate=False)
+--------------------------------+-----------+------------+
|file_path                       |dummy_value|file_name   |
+--------------------------------+-----------+------------+
|/home/user/test/File1.txt       |10         |File1.txt   |
|/home/user/test/File2.txt       |20         |File2.txt   |
|/home/user/test/File3.txt       |30         |File3.txt   |
|/home/user/test/File4.txt       |40         |File4.txt   |
|/2021-06-02-general/c32d3f47.csv|50         |c32d3f47.csv|
|/2021-06-02-general/c32d3f47.csv|50         |c32d3f47.csv|
+--------------------------------+-----------+------------+


text:
Q: insheet and multiple-character delimiters in Stata I am trying to use insheet to load in a data set from a .csv file. The delimiter in the data set is, however, "," (including the quotes) rather than simply a comma , . The top three lines in the .csv file would thus look something like this:
Name","Sex","Income
John","M","45000
Jane","F","20000

It appears that insheet does not allow for multiple-character delimiters - I get an error message that states that the "delimiter() option was incorrectly specified." Is there anyway to easy insheet data from a file like this?

A: Solution 1.
Stata 13 has support for multi-character delimiters. The command is import delimited. See the manual here.
Solution 2.
Use filefilter before using insheet. For example:
filefilter "source-file" "destination-file", from("\Q,\Q") to(",") replace

This replaces your multi-character delimiter with a comma delimiter. Run help filefilter.
Solution 3.
Are you not able to do a find/replace with your favorite text editor before importing to Stata? Find "," and replace with ,, for example. Then use Stata's insheet command. A good text editor may be more flexible than pure Stata in this respect.
Solution 4 (maybe).
Have you checked infix and infile? I have no experience with these but they may be worth checking out.

A: This is not especially good technique, but it underlines @Roberto Ferrer's point that several different solutions exist. First put your toy dataset into a file, and then read it in as one string variable. Here we respect the limit in Stata <13 of 244 characters; in Stata 13 you can have much longer string variables.
. infix str data 1-244 using test.dat
(3 observations read)

Now split the data into parts, parsing wth your separator. We need compound double quotes here protecting the literal double quotes.
. split data, p(`"",""')
variables created as string:
data1  data2  data3

. l

     +----------------------------------------------+
     |                data   data1   data2    data3 |
     |----------------------------------------------|
  1. | Name","Sex","Income    Name     Sex   Income |
  2. |    John","M","45000    John       M    45000 |
  3. |    Jane","F","20000    Jane       F    20000 |
     +----------------------------------------------+

Take the variable names out of the first observation, drop that and then use destring to convert to numeric what can be converted.
. forval i = 1/3 {
2. rename data`i'  `=data`i'[1]'
3. }

. drop in 1
(1 observation deleted)

. destring, replace
data contains nonnumeric characters; no replace
Name contains nonnumeric characters; no replace
Sex contains nonnumeric characters; no replace
Income has all characters numeric; replaced as long


text:
Q: How to assign players to teams in a game I'm creating a game with different participants that belong to different teams.
I having trouble assigned the players to the teams.
The players exist in an ArrayList, and i have created lists for each of the teams as well, but is it even possible to assign an element of one list to another list? So that the player exists in both lists?
Thanks

A: The list object contains an array of methods for adding and removing elements from lists: https://docs.oracle.com/javase/7/docs/api/java/util/List.html
I'd suggest something like :
teamList.add(playerList.get(playerIndex))
where playIndex is an integer of the player you want to add to the team. Assuming your players and teams are the same object type, the above code will retrieve a player from the player list and add that player to your team list.


text:
Q: How do I access NSApplicationDelegate from XCUIApplication in my UI tests I need to access some values in the app delegate to modify (and test) updates process with Sparkle. So the question is, how do I access NSApplicationDelegate from XCUIApplication in my UI tests?

A: Short answer:
You can´t access you AppDelegate file from your UITest project.
Long answer:
As stated by Oletha in their answer here:

Xcode UI testing is designed such that the test code can only see what a user can see, so no objects from the application under test can be used or inspected in the test code. This is also why the views on the screen are represented as XCUIElement objects instead of UIView descendants.
The UI tests run in a separate executable from the application under test.


text:
Q: Local notifications with unknown content at time of request in Swift I am looking to create a local notification system where the text it displays is different than the text it contains at request. I'm not looking to modify the notification from the standard Title, Body format. To test this, I tried to create a notification showing the current date, but when it was displayed, the time shown was two minutes ago. Is it possible to have this notification show the current date and time (or other variable content) without push notifications?
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy MM dd HH mm ss"
let dateString = dateFormatter.string(from: date)
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "the date is \(date)"
content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: false)

let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)


text:
Q: Technology behind [crawlera](http://crawlera.com)(What tools the use to download page content) I usually use urllib module in python to scrap data.
Certain websites are blocking to download the page content they are throwing 404 error but the website is live.
In such cases I use crawler proxies.
I wonder what tools and technologies they use for blacklist the website to make this work from 404 to 200
Could any one have idea behind it?


text:
Q: CookieSyncManager is now deprecated, what can I use instead? I'm using a cookie in my app which works fine in all browsers, but in android device the cookie is not setting as fast as I wanted, it takes some time until cookie is saved, same is happening when I delete the cookie. Is there anything I can do to make it work better? Thank in advance for your answers.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true); // enable javascript

    CookieManager.setAcceptFileSchemeCookies(true);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.acceptCookie();
    String cookie = CookieManager.getInstance().getCookie("mylink");

    final Activity activity = this;

    webview.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
        }
    });
    webview.loadUrl("mylink");

    setContentView(webview);
}

A: Simply Just enable javascript And Dom Storage. this helps me to remember my login details in my webview android app. I Didn't use Any CookieManager But Enabling This Do the trick for me.
 webView.getSettings().setJavaScriptEnabled(true);
 webView.getSettings().setDomStorageEnabled(true);

A: Nothing : "The WebView now automatically syncs cookies as necessary. You no longer need to create or use the CookieSyncManager."
As DarkKnight said, you can test if your app target below API 21 Lollipop (5.0), if not, you don't need anymore CookieSyncManager.

A: On Lollipop and beyond, the CookieManager singleton works fine by itself. (Refer Link - http://developer.android.com/reference/android/webkit/CookieManager.html)
however, prior to Lollipop it also required the use of an additional static method from CookieSyncManager. The code below works for me on all Android versions when setting the cookies on a WebView -
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    CookieSyncManager.createInstance(this);
}
cookieManager.setAcceptCookie(true);


text:
Q: Show that a given matrix always has an eigenvector in $\mathbb{R}$ Can somebody give a hint? The given exercise is, for all $\theta$ in $\mathbb{R}$, show that the matrix always has an eigenvector in $\mathbb{R^2}$ $$
A = \begin{pmatrix}
\cos(\theta) & \sin(\theta) \\
\sin(\theta) & -\cos(\theta)
\end{pmatrix}
$$
The use of determinants isn't allowed, it is just allowed that I should use de definition of eigenvector and eigenvalue, and the fact that the eigenvectors are linearly independent if they are distinct (if needed).
I don't fully understand the problem because I can't see how is possible that this matrix can give me a multiple scalar of some vector.

A: the matrix $\pmatrix{\cos \theta & \sin \theta\\ \sin \theta & -\cos \theta}$ represents  the reflection on a mirror along the line $y = \tan (\frac{\theta}{2})\  x.$ therefore $\pmatrix{\cos (\theta/2) \\\sin(\theta/2)}$ is an eigenvector corresponding to the eigenvalue $1$  and $\pmatrix{\sin (\theta/2) \\-\cos(\theta/2)}$ is an eigenvector corresponding to the eigenvalue $-1$.

A: AFTERTHOUGHT: it occurs to me that there is something that does not need determinant, although the concept is implicit. As you can easily confirm, we have a matrix $A$ such that $\color{red}{A^2 = I}.$ Now, if you are willing to accept the proposition that every square matrix has an eigenvalue (possibly complex) then we can write
$$ Av = \lambda v  $$ for $v$ a nonzero column matrix, possibly complex as well. Then
$$ v = Iv =  A^2 v = \lambda Av = \lambda^2 v.  $$
So, in fact, $\lambda = \pm 1.$ This argument holds for things that are not reflections or symmetric; consider
$$ A =
\left(
\begin{array}{cc}
0 & 7 \\
\frac{1}{7} & 0
\end{array}
\right)
$$
Also, note that  possession of an eigenvalue is not automatic in infinite dimension.  From what I can see, in the space of one-sided infinite sequences with, say, complex entries,  the right-shift operator does not have any non-zero eigenvector. See http://en.wikipedia.org/wiki/Shift_operator#Sequences
ORIGINAL: People seem confused. This matrix gives a REFLECTION. Determinant is $-1,$ trace is $0,$ so, no matter what $\theta$ might be, the characteristic polynomial is
$$ \lambda^2 - 1  $$
and the eigenvalues are $1$ and $-1.$ there is no counterexample.
It saves a little writing if you write the matrix as
$$
\left(
\begin{array}{cc}
a & b \\
b & -a
\end{array}
\right)
$$
with the understanding that
$$ a^2 + b^2 = 1.  $$
So, the $+1$ eigenvector is a column vector sent to the zero vector by
$$
\left(
\begin{array}{cc}
a -1 & b \\
b & -a -1
\end{array}
\right).
$$
Think about it. With $a^2 + b^2 = 1,$ why is the matrix immediately above singular? What is the actual eigenvector in terms of $a,b?$
Similar, the $-1$ eigenvector is a column vector sent to the zero vector by
$$
\left(
\begin{array}{cc}
a +1 & b \\
b & -a +1
\end{array}
\right).
$$
Again, why is this singular? Oh, symmetric matrix, the eigenvectors have different eigenvalues and are perpendicular to each other.
You can tell that a matrix is a reflection if it can be written as $\color{red}{I - 2 v v^T},$ where the letter $v$ refers to a column vector of length $1.$ Oh, in the other order, $v^T v$ is the (squared) length of $v,$ it is a 1 by 1 matrix with entry $v \cdot v.$ In the order used above, $v v^T$ is a symmetric, rank one, positive semidefinite matrix, furthermore its trace is exactly $1.$ So, the determinant of $\color{red}{I - 2 v v^T}$ is $-1$ and its trace is $n-2,$ where $n$ is the dimension. In dimension 2, you need only check the trace and determinant to know for sure.

A: Suppose $Av=\lambda v$.
We can scale $v$ to have unit norm, so that $v=(\cos\alpha,\sin\alpha)$.
Writing out $Av=\lambda v$ gives
$$
(\cos\theta\cos\alpha+\sin\theta\sin\alpha,\sin\theta\cos\alpha-\cos\theta\sin\alpha)
=
\lambda(\cos\alpha,\sin\alpha).
$$
We can simplify the LHS:
$$
(\cos(\theta-\alpha),\sin(\theta-\alpha))
=
\lambda(\cos\alpha,\sin\alpha).
$$
If we calculate the norm of both sides, we get
$$
1=\lambda^2\cdot1,
$$
so $\lambda=\pm1$.
If $\lambda=1$, we have $\cos(\theta-\alpha)=\cos\alpha$ which implies $\theta-\alpha=\pm\alpha+2\pi n$ for some $n\in\mathbb Z$.
The negative sign is only possible if $\theta$ is a multiple of $2\pi$ (this case is simple to solve separately).
For the positive sign we get $\alpha=\theta/2-\pi n$ for some $n\in\mathbb Z$.
Shifting $\alpha$ by $\pi$ changes the sign of $v$.
Therefore, up to sign, the normalized eigenvector corresponding to $\lambda=1$ is $(\cos(\theta/2),\sin(\theta/2))$.
A similar calculation for $\lambda=-1$ gives $(\sin(\theta/2),-\cos(\theta/2))$.

A: That transformation $A$ is a reflection $P_x$ along the $x$-axis followed by a rotation $R_\theta$ by an angle $\theta$ :
$$
A =
\left(
\begin{matrix}
\cos\theta & \sin\theta \\
\sin\theta & -\cos\theta
\end{matrix}
\right)
=
\left(
\begin{matrix}
\cos\theta & -\sin\theta \\
\sin\theta & \cos\theta
\end{matrix}
\right)
\left(
\begin{matrix}
1 & 0 \\
0 & -1
\end{matrix}
\right)
=
R_\theta \, P_x
$$
The length of the vector will be preserved by the transformation, because reflections and rotations do.
We want $A x = \lambda x$ for some non-zero vector $x$ and real number $\lambda$. Thus
$$
\lVert x \rVert = \lVert A x \rVert = \lvert \lambda \rvert \, \lVert x \rVert
$$
The preserved length enforces $\lambda = \pm 1$.
So a vector $u_\phi$ with angle $\phi$ and non-zero length $r$
$$
u_\phi
=
\left(
\begin{matrix}
r \cos \phi \\
r \sin \phi
\end{matrix}
\right)
\quad (*)
$$
and
$$
A u_\phi
=
R_\theta \, P_x u_\phi
=
R_\theta u_{-\phi}
=
u_{-\phi + \theta}
=
u_\phi
\iff \\
-\phi + \theta = \phi \iff
\phi = \frac{\theta}{2}
$$
will have an eigenvalue $1$. For the eigenvalue $-1$,
$$
A u_\phi = - u_\phi = u_{\phi + \pi}
$$
one needs a vector with
$$
-\phi + \theta = \phi + \pi \iff \phi = \frac{\theta-\pi}{2}
$$
Both vectors exist for any $\theta$, just use the above determined  $\phi$ for any non-zero $r$ in equation $(*)$.


text:
Q: How do I check a string for one or more symbols I'm struggling to find a method of checking to see if a string contains one or more symbols like the following: #}{&*"(£) While it's fairly trivial to make a check for one or more of these symbols I'm not looking to build and maintain a list or dictionary of possible entries. Is there a way I can check to see if a string contains one or more of any non standard symbol in go preferably using the standard library?
Specifically I'm looking to detect anything that isn't a-zA-Z0-9 which for the basis of my question would be counted as a non standard symbol.

A: In Go, write a simple function. For example,
package main

import (
    "fmt"
)

func isStandard(s string) bool {
    for i := 0; i < len(s); i++ {
        switch b := s[i]; {
        case b >= 'a' && b <= 'z':
            continue
        case b >= 'A' && b <= 'Z':
            continue
        case b >= '0' && b <= '9':
            continue
        default:
            return false
        }
    }
    return true
}

func main() {
    fmt.Println(isStandard(`ABCabc123`))
    fmt.Println(isStandard(`#}{&*"(£)`))
}

Playground: https://play.golang.org/p/Y2KjDcHSupH
Output:
true
false

The Go Programming Language Specification
Switch statements
"Switch" statements provide multi-way execution. An expression or type
  specifier is compared to the "cases" inside the "switch" to determine
  which branch to execute.
Expression switches
In an expression switch, the switch expression is evaluated and the
  case expressions, which need not be constants, are evaluated
  left-to-right and top-to-bottom; the first one that equals the switch
  expression triggers execution of the statements of the associated
  case; the other cases are skipped. If no case matches and there is a
  "default" case, its statements are executed. There can be at most one
  default case and it may appear anywhere in the "switch" statement.
The switch expression may be preceded by a simple statement, which
  executes before the expression is evaluated.
Fallthrough statements
A "fallthrough" statement transfers control to the first statement of
  the next case clause in an expression "switch" statement. It may be
  used only as the final non-empty statement in such a clause.

switch b := s[i]; {
    // ...
}

is equivalent to
switch b := s[i]; true {
    // ...
}

is equivalent to
{
    b := s[i]
    switch true {
        // ...
    }
}

The simple statement b := s[i] declares b to be a switch { } statement block local variable.
The case expresions are evaluated and compared to true. If none are true, the default is taken.
Go, unlike C, requires explicit fallthrough.
ASCII is a subset of Unicode UTF-8. Since the standard characters are all ASCII, we can simply compare bytes.

Here is a simple benchmark.
Output:
$ go test standard_test.go -bench=. -benchmem
BenchmarkPeterSO-8    200000000       8.10 ns/op    0 B/op    0 allocs/op
BenchmarkJubobs-8      10000000     222 ns/op       0 B/op    0 allocs/op
$

standard_test.go:
package main

import (
    "regexp"
    "testing"
)

func isStandard(s string) bool {
    for i := 0; i < len(s); i++ {
        switch b := s[i]; {
        case b >= 'a' && b <= 'z':
            continue
        case b >= 'A' && b <= 'Z':
            continue
        case b >= '0' && b <= '9':
            continue
        default:
            return false
        }
    }
    return true
}

func BenchmarkPeterSO(b *testing.B) {
    std := `ABCabc123`
    for N := 0; N < b.N; N++ {
        isStandard(std)
    }
}

var (
    whitelist  = "A-Za-z0-9"
    disallowed = regexp.MustCompile("[^" + whitelist + " ]+")
)

func IsValid(s string) bool {
    return !disallowed.MatchString(s)
}

func BenchmarkJubobs(b *testing.B) {
    std := `ABCabc123`
    for N := 0; N < b.N; N++ {
        IsValid(std)
    }
}

A: Since the whitelist can easily be defined as a regexp, use regexp.MatchString:
package main

import (
    "fmt"
    "regexp"
)

var (
    whitelist  = "A-Za-z0-9"
    disallowed = regexp.MustCompile(fmt.Sprintf("[^%s]+", whitelist))
)

func main() {
    fmt.Println(IsValid("foobar007"))
    fmt.Println(IsValid("foo%bar&007"))
}

func IsValid(s string) bool {
    return !disallowed.MatchString(s)
}

(playground)


text:
Q: What is the correct JQL query if I want to search all projects of a particular jira user? I tried the JQL query below but it does not work.
project is EMPTY AND assignee = johndew
The output I want is a list of projects of the user.

A: Jira users are not directly connected to Projects. They are working / assigned to Jira issues, which belong to a Project.
It can not expressed in just a JQL. But when creating an issue filter with JQL like assignee = johndew and then save it, like 'issues-johndew'. Then open one of the Jira Dashboards and add the Gadget Issue Statstics. Fill in the field Project or Saved Filter the value of the filter issues-johndew. Fill in the field Static Type Project.
This should give an overview of where John Dew is working on.
In Jira this is the shown as below


text:
Q: how to get a HTML textbox Value into another HtMl table  see.first index.html has a add button..whenever the add button get active it should be add the textbox value into the table.html.The table.html table should be editable and updatable..
pls friends give solution to me.........

A: sorry, but I think that it is not possible to do just by JavaScript !


text:
Q: Kendoui bar chart set series on click of a button I am working with KendoUI bar chart. Please check this fiddle. In this fiddle I am setting series config at the design time. I want to add series to the chart at run time on click of a button. How can I add series to kendo chart on click of a button.
Currently series is assigned at the design time, i want to do the same at the run time on click of a button.
Code:
<!DOCTYPE html>

    <base href="http://demos.telerik.com/kendo-ui/bar-charts/grouped-stacked-bar">

    <title></title>
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.common-material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.material.min.css" />

A: Ageonix gave a good answer!  If you do not want to use a global variable for the chart options, you can get the chart instance from the DOM data-attribute, add the series to the chart instance and then tell the chart to redraw:
var newseries = {
      name: "100+",
      stack: "Female",
      data: [654622, 625844, 784930, 844982, 900941, 39797, 72929, 118435, 118454]
};
//Get the chart
var chart = $("#chart").data("kendoChart");
//add the series
chart.options.series.push(newseries);
//refresh the chart
chart.redraw();

Updated DOJO

A: If you set the chart options as a global variable, you can then modify options.series and set it to your updated series data source in the button click event and call createChart() again, which will update (recreate) the chart with the updated series.
Create a global chartOptions variable:
var chartOptions =
{
  title: {
  text: "World population by age group and sex"
},
legend: {
etc. etc.

Then create the chart with the options stored in the variable:
$("#chart").kendoChart(chartOptions);

Finally, update the options.series with the updated data and recreate the chart:
click: function()
{
  chartOptions.series = updatedSeries;
  $("#chart").kendoChart(chartOptions);
}

I updated your Dojo and added a button that populates a new series on click.
http://dojo.telerik.com/oTeTi/3


text:
Q: how to call the posts of a different custom taxonomy of a category name in wordpress? I have written a code for displaying all the posts of a particular category from a particular custom taxonomy. Here $term is the name of the category of which the posts are to be displayed. The following code is being given below :
<?php

    $args = array(
        'posts_per_page' => '-1',
        'post_type'      => 'brand',
        'taxonomy'       => 'brand-category',
        'terms'          => $term,
        'category_name'  => $term,
        'order'          => 'DESC'
    );

    $results = new wp_Query($args);

    if(have_posts()){
        while($results->have_posts()){
            $results->the_post();
            $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
    ?>

        <img src="<?php echo $image; ?>" alt="pvc hose">

    <?php }
    }

?>

The above code is not displaying the images which I have given in the particular category in the particular taxonomy brand-category. Can anyone suggest corrections to this code?

A: For custom taxonomies you should use the tax_queryparameter. Your args should be like:
$args = array(
    'posts_per_page' => -1,
    'post_type'      => 'brand',
    'order'          => 'DESC',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'brand-category',
            'field'    => 'slug',
            'terms'    => $term,
        ),
        array(
            'taxonomy' => 'brand-category',
            'field'    => 'name',
            'terms'    => $term,
        ),
    ),
);

Hope it helps!


text:
Q: Prove that $\langle Ax_n\;,\;x_n\rangle\to\langle Ax\;,\;x\rangle$ In this question $F$ stands for a complex Hilbert space with inner product $\langle\cdot\;,\;\cdot\rangle$ and the norm $\|\cdot\|$. Let $\mathcal{B}(F)$ be the algebra of all bounded linear operators on $F$.

Assume that there exists $(x_n)_n\subset F$ such that $\lim_{n\to \infty}\|x_n-x\|=0$. If $A\in\mathcal{B}(F)$, then why is the following true:
  $$\lim_{n\to \infty}\langle Ax_n\;,\;x_n\rangle=\langle Ax\;,\;x\rangle ?$$

A: Write
$$
\begin{align}
|\langle Ax_n, x_n  \rangle-\langle Ax, x  \rangle|&\leq |\langle A(x_n-x), x_n  \rangle|+ |\langle Ax, x_n-x  \rangle|\\
&\leq \lVert A\rVert\lVert x_n-x\rVert\lVert x_n\rVert +  \lVert A\rVert\lVert x\rVert \lVert x_n-x\rVert
\end{align}
$$
by the C.S inequality. Argue that this can be made less than $\epsilon >0$ by choosing $n$ sufficiently large using the hypotheses. Special care needs to be taken to deal with the cases where $\lVert A\rVert=0$ or $\lVert x\rVert=0$.

A: Consider the map $v\mapsto\langle Av,v\rangle$. It is continuous, since you can get it by composing two continuous maps: the map $v\mapsto(Av,v)$ and the map $(v,w)\mapsto\langle v,w\rangle$.
Therefore, since $\lim_{n\to\infty}x_n=x$, $\lim_{n\to\infty}\langle Ax_n,x_n\rangle=\langle Ax,x\rangle$.

A: $$| \langle Ax_n,x_n \rangle-\langle Ax,x \rangle| \leq |\langle Ax_n-Ax,x \rangle|+|\langle Ax_n,x_n-x \rangle |$$ $$ \leq \| A\| \| x_n-x\|\|x\|+\|A\|\|x_n\|\|x_n-x\|$$
By the boundedness of $A$ and $\lim_{n\to \infty}\|x_n-x\|=0$ we have the result
Here you are


text:
Q: Barman server unable to connect to Primary I have created and followed instructions from the barman documentation. I have a primary Postgres and backup barman servers. I am able to ssh to primary server from back server without password. But when running any of the barman commands like barman check Postgresdb-server I am unable to get any response. At same time the wal archiving is working fine as I see the wal logs in backup server. Even barman backup Postgresdb-server is not responding. Is there anything that I am missing? The log file says it is impossible to take backup but other than that there is no other message. I am using the latest barman 2.1 and PostgreSQL 9.6.2
[Postgresdb-server]
description =  "Example of PostgreSQL Database (via Ssh)"
ssh_command = ssh postgres@pg
conninfo = host=pg user=barman dbname=postgres
backup_method = rsync
reuse_backup = link
archiver = on

Update: The issue was resolved after opening a firewall port 5432 for external connections. In this case opening port 5432 from backup/barman server to primary postgres server. This helped resolved the issue.
psycopg2.connect("host=pg user=barman dbname=postgres")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
    conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection timed out
        Is the server running on host "pg" and accepting
        TCP/IP connections on port 5432?


text:
Q: Find the shortest cycle in a directed graph passing through certain nodes I have a weighted directed graph G, including the vertices V and edges E. I have certain nodes, namely S, which are the subset of the set V. Among the nodes in S, one of them is considered as the starting point, namely, t.
How can I find the shortest cycle that starts from t, passes through the nodes in S, and ends at t?  I am wondering if the starting point plays an important role in our problem.
I saw a similar question asked before in the below link, but the question in the link says that the cycle passes through at list one of the nodes in the set U, which in our case is the set S. In fact, in my case the cycle must pass through all the nodes in the set U or in my case set S.
Finding the lightest path to one vertex from all others in a graph
A similar question in the below link asks for the path, not the cycle I am looking for.
Find the shortest path in a graph which visits certain nodes
A similar question in the below link concerns an undirected graph, while in my case, the graph is directed.
Finding shortest circuit in a graph that visits X nodes at least once


text:
Q: Import remote DLL every time VS starts? I am somewhat responsible for a common code base at work. It becomes very frustrating pushing out updates to the libraries simply because people don't keep track of that stuff or when old projects need updates, a lot of the times it contains the old DLL and the person in charge of changes doesn't include the latest version. The result ends up being that our code base is fragmented with new/old versions. I want to MAKE SURE that when a project is worked on, it is using the lastest DLLs.
Is there a way in visual studio to set the DLL to import every time? I noticed that once the DLL is in place, even if you update the DLL file, you have to reimport to get the lastest goodies. Is there a way for maybe Visual Studio to reimport it on every start? The DLL will sit on a shared drive, so when I push out new updates I can simply update the DLL on the shared drive and it gives everyone the lastest version automatically.

A: Even if this is possible, people would have to restart their visual studio to get the updated driver. I tend to leave my workspaces and projects open for days. So it would not help if I were in your office.
Sounds better to me to implement a version control system (ie SVN) and either commit the DLL or the code itself and let people update/recompile as they want. Usually people learn to update and commit often to avoid complicated merge conflicts.
Or do you already have your code under version control?


text:
Q: Interface{} type understanding Can't understand the problem:
    var foo interface{}
    foo = make(map[string]int)
    fmt.Println(foo)  // map[]

but
    foo["one"] = 1

prog.go:10: invalid operation: foo["one"] (index of type interface {})
[process exited with non-zero status]
Why is that?

A: foo is of type interface{}. It might contain a map, but it is still an interface.
In order to do a map lookup, you first need to make a type assertion:
foo.(map[string]int)["one"] = 1

More about type assertion can be found in the Go specifications:

For an expression x of interface type and a type T, the primary expression
  x.(T)
  asserts that x is not nil and that the value stored in x is of type T.
  The notation x.(T) is called a type assertion.


text:
Q: Woocommerce Orders Rest API: Add a coupon code I have Visited The official WooCommerce Rest API documentation "Create an Order" section. I am trying to create an order via the API, but when I want to create the order with the apply coupon, I don't know how to make it.
How I will pass the coupon code as a discount when I create the order through the REST API?
In the related official documentation I don't find any request parameter to pass a coupon code or a discount.
Please suggest how to pass the coupon code when creating order via rest API in WooCommerce.

A: You should need to add in your data array 'coupon_lines', something like:
    'coupon_lines' => [
        [
            'code' => 'mycouponcode',
            'discount' => '5',
            'discount_tax' => '0.75',
            'meta_data' => [
                [
                    'key' => 'coupon_data',
                    'value' => [
                        'id' => '1234',
                        'code' => 'mycouponcode',
                        'amount' => '10',
                        /* ... and so on ... */
                    ]
                ]
            ]
        ]
    ]

The meta_data array is all the woocommerce coupon meta data. This should work…

A: I have tried the following answer
The first step is to create a coupon from woocommerce admin backend and add your rules for this coupon (percentage of discount or discount amount or others..)
Then according to the order controller class that is part of the woocommerce rest api, when updating an order to attach a coupon you will need to include ONLY the coupon code as part of the coupon_lines array.
Below link of the controller:
https://github.com/woocommerce/woocommerce/blob/master/includes/api/class-wc-rest-orders-controller.php
This is the part of the code that do validation on coupon_lines array and apply our coupon code to the woocommerce order
As you can see, It do validates that you are not passing a coupon id and you only pass coupon code before applying this code to the orders.
Below sample JSON that worked with me on updating the order
 {
    "coupon_lines": [
        {
            "code": "1122"
        }
     ]
 }

Once your coupon code is applied, the order will be returned with all other fields populated by woocommerce after doing the order total calculation & applying coupon discount
Below validation code from rest api order controller
        foreach ( $request['coupon_lines'] as $item ) {
            if ( is_array( $item ) ) {
                if ( empty( $item['id'] ) ) {
                    if ( empty( $item['code'] ) ) {
                        throw new WC_REST_Exception( 'woocommerce_rest_invalid_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
                    }
                    $results = $order->apply_coupon( wc_clean( $item['code'] ) );
                    if ( is_wp_error( $results ) ) {
                        throw new WC_REST_Exception( 'woocommerce_rest_' . $results->get_error_code(), $results->get_error_message(), 400 );
                    }
                }
            }
        }

A: This is because the API for creating coupon codes is separate from the ordering API.  You need to define coupons using the Coupon API:
 code: '10off',
 discount_type: 'percent',
 amount: '10',
 individual_use: true,
 exclude_sale_items: true,
 minimum_amount: '100.00'

Then any coupons applied by the customer are automatically computed.

A: you should add "coupon_lines" to your order object as stated here
Order properties detailed further on here enter link description here
so every order should have and "coupon_lines" array containing "id","code","amount" for you desired coupon which you get when you verify the coupon through the coupon API.
'coupon_lines' => [
    [
        'id' => 32,
        'code' => testcoupon,
        'amount' => '0.75',
    ]
]

A: if you didn't found a way i wrote and answer just in case someone else comes here with the same question as i did :). After you create an order using the rest api you should update that order with the coupon_lines as suggested by others here. So in summary create an order using the rest api use the order_id returned by it to update (documentation here) the order with the coupon_lines to apply the coupon the user applies.

A: Applying coupons to orders via API doesn't exist in v2. use v3.


text:
Q: Is There is a way in .net to get centroid for polyline? I want to get the centroid of polyline2d.  I have a polyline from TraceBoundary like so:
DBObjectCollection objs = Application.DocumentManager.MdiActiveDocument.Editor.TraceBoundary(Point, false);
Polyline polyline = (Polyline)objs[0];
Point2d centroid = ***The missing part i need any way to get center of gravity of the above polyline as point2d***

I was doing that before with autolisp:
(setq arob (entlast))
(setq enpol (vlax-ename->vla-object arob))
(setq cgpoint (vlax-get-property enpol 'Centroid))

I have a mathematical solution, but it's not valid when the polyline comes with some curves.
I won't use this function:
public static Point2d GetPolyLineCentroid(Polyline polyline)
    {
        double area = polyline.Area;
        double cx = 0.0;
        double cy = 0.0;
        double X0 = 0.0;
        double Y0 = 0.0;
        double X1 = 0.0;
        double Y1 = 0.0;

        for (int i = 0; i < polyline.NumberOfVertices - 1; i++)
        {
            X0 = polyline.GetPoint2dAt(i).X;
            Y0 = polyline.GetPoint2dAt(i).Y;
            X1 = polyline.GetPoint2dAt(i + 1).X;
            Y1 = polyline.GetPoint2dAt(i + 1).Y;

            cx += (X0 + X1) * (X0 * Y1 - X1 * Y0);
            cy += (Y0 + Y1) * (X0 * Y1 - X1 * Y0);
        }

        // last Point
        int Lv = polyline.NumberOfVertices - 1;
        X0 = polyline.GetPoint2dAt(Lv).X;
        Y0 = polyline.GetPoint2dAt(Lv).Y;
        X1 = polyline.GetPoint2dAt(0).X;
        Y1 = polyline.GetPoint2dAt(0).Y;

        cx += (X0 + X1) * (X0 * Y1 - X1 * Y0);
        cy += (Y0 + Y1) * (X0 * Y1 - X1 * Y0);

        cx /= 6 * area;
        cy /= 6 * area;

        return new Point2d(cx, cy);
    }

I don't want to use AutoLisp.  Is there a way to do this in .NET?

A: I found this solution and it's valid for me:
public static Point2d GetPolyLineCentroid(DBObjectCollection objs)
{
    Solid3d Solid = new Solid3d();
    Solid.Extrude(((Region)Region.CreateFromCurves(objs)[0]), 1, 0);
    Point2d centroid = new Point2d(Solid.MassProperties.Centroid.X, Solid.MassProperties.Centroid.Y);
    Solid.Dispose();
    return centroid;
}

A: For AutoCAD <= 2013, create a region with .NET (Region.CreateFromCurves), and get a reference to it with COM and the HandleToObject method. On the region ActiveX object, there is a Centroid property.
For AutoCAD > 2013, there is a AreaProperties method on the Region class that returns a RegionAreaProperties structure with a Centroid property.


text:
Q: How do I use .queue() to properly chain custom callback functions? I'm trying to figure out how to chain custom functions:
I have something like this:
show_loader(0, function() {
    open_box($target_open, event.value, '.wide-col', function() {
        hide_loader(function() {
            scroll_to_content($target_open, function() {
            });
            $(this).dequeue();
        });
        $(this).dequeue();
    });
    $(this).dequeue();
});

Those functions have a callback implemented that looks something like this:
function show_loader(position, callback) {
    $ajaxSpinner.fadeIn();
    status = "loading"; //some non-jQuery stuff
    if (callback) $ajaxSpinner.queue( function() {callback()} );
}

You can see the basic idea of what i'm trying to do: execute my functions after the animations inside the functions are complete.
I don't think my code is quite right. The order should be: show loader, open box, hide loader, then finally scroll to content. Instead, it seems like this is what's actually happening when i test it: show loader, hide loader, scroll to content, then open box.
How do I get that order of function calls properly queued? And am I using the keyowrd "this" in the proper context?

A:
You can see the basic idea of what i'm trying to do: execute my functions after the animations inside the functions are complete.

If you use standard animation functions from jQuery, you should be able to directly pass a callback to them. E.g.:
function show_loader(position, callback) {
    $ajaxSpinner.fadeIn(callback);
    status = "loading"; //some non-jQuery stuff
}

Have a look at http://api.jquery.com and see how they work.
Update:
Here is an example that produces the desired result using queue. I'm using a newer form, where the next function to execute is passed as argument to the callback. Maybe you are doing something wrong with dequeue. Edit: I tried your code and it works fine. I guess your are not using queue properly in the other functions.


text:
Q: facebook->getUser() returns 0 I assume that this is because users have to grant some sort of access to my facebook application, for getUser to be available to me? Here is my code:
 <? require 'facebook.php'; ?>
 <?php

 $facebook = new Facebook(array(
 'appId' => '[//fb app id]',
 'secret' => '[//fb app secret]',
 'cookie' => true
 ));

 $uid = $facebook->getUser();
 echo $uid;

 ?>

So I guess my question is, short of prompting the user to give permission to my app, is there any other sort of unique identifier that I can grab from a fb user to prevent them from submitting more than 1 entry to my app. I have user's add submissions, but I only want to allow 1 submission per user. Thanks for the help!

A: To get user id, user have to grant permission
if($uid){
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');

  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}else{
    $loginUrl = $facebook->getLoginUrl();
    echo("<br>login url=".$loginUrl);
};

After the user grant permission (see the loginUrl), you may access user id


text:
Q: How to remove dead files from Open Recent list in Sublime Text 3? In Sublime Text 3 if I go to:
MENU: File>Open Recent
There are files in that list which are no longer available.
How can I clean that list of dead files?
I don't want to clear the full list, just the dead ones.

Note: I've followed How to increase number of recent files in Sublime Text 3? to get 30 recent files showing in this menu.

A: Following this post over on the Sublime Forum it can be done by editing the Session.sublime_session file.
For example: I'd edited etc/hosts so I could block myself from watching youtube, but with it being in the recent files list in Sublime it's easy to unblock myself thus I wanted to remove /etc/hosts from my recent file list in Sublime (ST3).
My copy of Sessions.sublime_session is in ~/.config/sublime-text-3/Local/ from which I deleted all lines containing etc/hosts.
The only caveat is that you can't edit that file using Sublime, Sublime should not be running, I used a different text editor.
Final caveat this is the solution for linux, and ST3, for windows and mac I'm guessing there's something similar.

A: I found out how to do this using this python script here:
https://github.com/STealthy-and-haSTy/SublimeScraps/tree/master/session_cleaner
I don't want to post the python code as I don't have permission to do so but that has been up on GitHub for a couple of years so there should be no worries of it disappearing anytime soon.
I've written a batch file that will start the python file, see the code below. Just name it RunSessionCleaner.cmd and place this in the same folder as the sublime_session_clean.py file.
@echo off & title %~nx0 & color 5F & chcp 65001 >NUL
rem Based on this thread here: https://stackoverflow.com/a/13351373
goto :MY_ROUTINE
:CMD_SIZE
chcp 850 >NUL & set "uiWidth=%1" & set "uiHeight=%2"
mode %uiWidth%,%uiHeight%
if %4==TRUE (set /a "uiHeightBuffer=uiHeight+%3")
if %4==TRUE (powershell.exe -ExecutionPolicy Bypass -Command ^
  "&{$H=get-host;$W=$H.ui.rawui;$B=$W.buffersize;$B.width=%uiWidth%;$B.height=%uiHeightBuffer%;$W.buffersize=$B}")
if %4==FALSE (powershell.exe -ExecutionPolicy Bypass -Command ^
  "&{$H=get-host;$W=$H.ui.rawui;$B=$W.buffersize;$B.width=%uiWidth%;$B.height=%uiHeight%;$W.buffersize=$B}")
chcp 65001 >NUL & goto :EOF
:MY_ROUTINE
call :CMD_SIZE 60 7 222 TRUE
title Cleaning folders, files and projects...
echo Cleaning folders, files and projects...
:: Full path to data folder        W:\Apps (Portable)\Sublime Text\Data
:: Full path to python.exe         W:\Apps (Portable)\Sublime Text\Data\Packages\User\SessionCleaner\python\python.exe
:: Full path to sublime_session_clean.py  W:\Apps (Portable)\Sublime Text\Data\Packages\User\SessionCleaner\sublime_session_clean.py
:: Or like I have done use a relative directory to the Data folder
:: The SsssionClearner.py file is located in: W:\Apps (Portable)\Sublime Text\Data\Packages\User\SessionCleaner
::
:: Change this line below to suit your needs.
".\python\python.exe" "sublime_session_clean.py" --data-dir "..\..\..\..\Data" --workspaces --files --folders
echo/
goto :EXIT_ROUTINE
:EXIT_ROUTINE
rem call :CMD_SIZE 100 10 222 FALSE
title Exiting routine...
echo Exiting routine...
set /p "=" <NUL &
ping localhost -n 3 >NUL & exit
exit

Change line 24 of the code above to suit your paths. You can just use relative paths here like I have done so you can do that too.
This batch file can be clicked on or set up in Task Scheduler to start up when the PC does to clean out all the non-existent files or workspaces.
Please note, Sublime Text needs to be closed in order for this to work.


text:
Q: AJAX: Form Submit to post comments I'm having an issue getting a form to submit and display the comment without the page refreshing (in-place) but when I click on the button, it takes me to the top of the page but does not perform any actions, does not insert into the database and thus does not display the comments in the page.
It is supposed to place the comment in the appropriate place with a fade effect.
Credits and Demo for the script: Original Script Here
The script provided int he link above, works if I try it as it comes but I had to modify it to fit my needs and this is what I have.
The Form:

    <form id="form" action="" method="post">

                <input class="field" type="hidden" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" />
                <input class="field" type="text" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" disabled="disabled">

                <input class="field" type="hidden" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" />
                <input class="field" type="text" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" disabled="disabled">

                <input class="field" type="hidden" name="PageID" value="<?php echo $_GET['PageID']; ?>" />
                <input class="field" type="text" name="PageID" value="<?php echo $_GET['PageID']; ?>" disabled="disabled">

        Choose an Option
        <select id="commentbox" name="comment" class="bs-select form-control">
            <option disabled selected value> -- Options -- </option>
            <option value="First Option">First Option</option>
            <option value="Second Option">Second Option</option>
            <option value="Third Option">Third Option</option>
        </select>
        <button class="btn btn-icon submit" name="btn-sumbit" type="submit" id="submit" value="Post Message">Post Message</button>

    </form>

Messages

    <?php echo $postedcomments; ?>

The script
located in the same page as the form.

The Query
comment-insert.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include_once 'include/dbconfig.php';
include_once 'include/dbconnection.php';
$conn = dbconnect();

if (!empty($_POST['comment'])) {
        $Name = mysqli_real_escape_string($conn, $_POST['Name']);
        $PageID = mysqli_real_escape_string($conn, $_POST['PageID']);
        $ID = mysqli_real_escape_string($conn, $_POST['ID']);
        $Comment = mysqli_real_escape_string($conn, $_POST['comment']);

        $sql = "INSERT INTO comments
        (PageID, PosterID, PosterName, PostDate, Comment)
        VALUES
        ('$PageID', '$ID', '$Name', now(), '$Comment')";

        mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
}
?>

<img src='users/images/<?php echo $_SESSION['Image'] ?>'>

<?php echo $Name ?>, Said:
<?php echo $Comment ?>

<?php
    mysqli_close($conn);
endif?>

A: This works:
$(document).ready(function() {
    //var form = $('#form');
    //var submit = $('#submit');

    $('#submit').on('click', function(e) {
        e.preventDefault();
        // the rest of your code goes here
    })
});

A: Your jQuery event handler refers to an non-existent jQuery object. Try replacing the first line of the event handler with this:
form.on('submit', function(e) {


text:
Q: How to improve the quality of the `concorde` TSP solver? Am I misusing it? I'm trying to use the concorde TSP solver in a file using the following format:
NAME : p5
COMMENT : Nada
TYPE : TSP
DIMENSION : 20
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
0 0.329733 0.67714
1 0.823944 0.035369
2 0.002488 0.866692
3 0.241964 0.671822
4 0.98876 0.134457
5 0.879147 0.457779
6 0.021017 0.271951
7 0.221737 0.367143
8 0.549802 0.523319
9 0.363839 0.22359
10 0.696631 0.495935
11 0.279072 0.100501
12 0.660156 0.860675
13 0.251769 0.029172
14 0.32112 0.207704
15 0.821433 0.507387
16 0.095411 0.953448
17 0.115897 0.269363
18 0.704484 0.411328
19 0.705198 0.795917

Since I couldn't find a guide about the format, I just modified a sample file I downloaded. I am running the following command:
concorde myFile.tsp

It quickly (~45ms) outputs the solution as a .sol file, which results in something like that:
20
0 10 19 8 12 15 5 4 18 1
9 17 6 11 7 13 14 3 2 16

Graphing, I get:

Which, by visual inspection, is too far from an ideal solution. Thus,

*

*Am I doing something wrong with the file format or command?

*If not, considering how fast it computed the solution, can I prompt it to spend more time looking for better solutions?

A: EUC_2D is the rounded L2 norm.  That is, the distance between two points is taken to be their Euclidean distance rounded to the nearest integer.  Your points are all going to be at distances 0 or 1 to one another and Concorde is going to generate a daft tour like the one you drew.
Scale your problem up until the rounding stops making a difference.


text:
Q: Expression.Body removes class on static method call I have an Expression with a certain Lambda in it that looks like this:
Expression<Func<string[],int>> expression = p => int.Parse(p[0]) * int.Parse(p[1])

when I call expression.Body, I get:
(Parse(p[0]) * Parse(p[1]))

if the expression would be like this:
Expression<Func<string[],int>> expression = p => p[0].ToInt() * p[1]ToInt()

naturally, the expression cuts off the class from a static method and do with it something.
My question is, how can i get a string representation with the excluded class?
where does it store the static method? can i string.Format() the properties to get the full body?
p.s. I don't need to run the expression, i know that it will work when I'll call expression.Invoke. since I'm using CodeDom, I need the exact expression body

A: Expression.ToString() will instantiate an ExpressionStringBuilder, which unfortunately is internal sealed so you can't  do much about it.
See the relevant source code.
You can try the following workaround:

*

*Create a subclass of ExpressionVisitor

*Instantiate a StringBuilder in the constructor

*Override VisitMethodCall to implement your logic and append the string to the StringBuilder. Use MethodInfo.DeclaringType to access the method's type.

*For the other node types, just append node.ToString() to the StringBuilder (reuse the existing functionality).


text:
Q: Unwind with more than 1 segue using iOS 7 UIViewController transition animations I am using the UIViewController animated transitions introduced in iOS7. I am able to produce some really great transitions going back and forth between VC's using segues etc.
Take a look at my picture below:

I can very easily go back and forth if it is just one segue/vc at a time. For example if, I go from Screen 1 to Screen 2, the animation works perfect. And then say I go back to 1 or forward to 3, it works perfectly.
But, if you notice on screen 4 at the bottom there is a button that says "Back To Screen 1"—this is an unwinding segue to screen 1. The issue is, I can't get the transition animation to work. In fact, the delegate methods never get called.
Here is how I have it set up (for example animating from screen 2 to 3):
//This is found in screen 2's view controller .m

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if ([segue.identifier isEqualToString:@"screen2to3"]) {

        UIViewController *destination = segue.destinationViewController;
        destination.transitioningDelegate = self;
        destination.modalTransitionStyle = UIModalPresentationCustom;

    }
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {

    STSlideAnimation *animator = [STSlideAnimation new];
    animator.presenting = YES;
    return animator;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {

    STSlideAnimation *animator = [STSlideAnimation new];
    return animator;
}

//This is the unwinding segue action

-(IBAction)returnToScreen2:(UIStoryboardSegue *)segue{

}

This works perfect going both to screen3 and back to screen2. The animation gets called both ways. However, I can't get any animation to work when going back more than one vc at a time. Any ideas? Let me know if I need to post more sample code.

A: You need to make custom segue classes for each type of transition you wish to apply
#import <UIKit/UIKit.h>

@interface CustomSegue : UIStoryboardSegue

@end

@implementation CustomSegue

 -(void)perform {

 // write your transition code here
 // this code will be called every time transition is made

}

Select a segue in storybord - in inspector change its type to custom - select custom class you have made in above case "CustomSegue"

If you have subclassed it properly then you will find inspector as below

Unwind as usual but will get the same effect even if you have poped from 4th controller to 1st controller


text:
Q: What type of a modem/router/switch for LAN party where no internet access is needed? What type of a "box" would be suitable for only LAN connections?
Im about to have a nice little LAN party with 6 people coming in and we dont need the internet, just some local "switch". I started reading about Netgear switches such as "Netgear GS108GE" but then I noticed that you need a "router" or internet connection for these to work. Nowhere is it ever said that a box could be used strictly for LAN.
What type of a box do I need to simply have a local area network between 7 machines?
No matter what I google I cant get a clear answer to this.
Thanks in advance!

A: Technically, a basic Ethernet switch is enough for LAN communications. All you really need is the ability to exchange packets, and switches & hubs do exactly that; and they most certainly work without an Internet connection.
(Don't get a hub, though. While it also relays L2 frames just like a switch would, hubs will give you awful performance at best – Gigabit Ethernet requires a switched network.)
The primary job of a router is to connect networks together (e.g. Internet and a LAN, or just two LANs), but you only have one isolated network so there's nothing to route. Likewise, a modem bridges between different signal types, e.g. Ethernet to ADSL – if your network is 100% Ethernet, you don't need a modem.

But one concern is IP address assignment – if you want the convenience of DHCP (instead of telling everyone to manually configure IPv4 addresses), then you will need a DHCP server somewhere in your LAN. Likewise with IPv6 and SLAAC.
On the one hand, it doesn't have to be an actual router – you could hook up a RasPi or any old Linux system, then set up dnsmasq (or dhcpd + radvd) on it. On the other hand, home routers already come with the same preconfigured.
Most home "routers", after all, are N-in-one devices: you get a 4-port switch internally connected to a CPU performing routing tasks. So even if you don't have any Internet connection, you can still use a home "router" or "modem" as an average switch + WiFi AP + DHCP server.

Finally, should you need to extend the LAN (e.g. if you ran out of Ethernet ports), then a switch will be 100% enough for that. Best not to try to chain multiple routers.


text:
Q: Regular expression matching "dictionary words" I'm a Java user but I'm new to regular expressions.
I just want to have a tiny expression that, given a word (we assume that the string is only one word), answers with a boolean, telling if the word is valid or not.
An example... I want to catch all words that is plausible to be in a dictionary... So, i just want words with chars from a-z A-Z, an hyphen (for example: man-in-the-middle) and an apostrophe (like I'll  or Tiffany's).
Valid words:

*

*"food"

*"RocKet"

*"man-in-the-middle"

*"kahsdkjhsakdhakjsd"

*"JESUS", etc.

Non-valid words:

*

*"gipsy76"

*"www.google.com"

*"me@gmail.com"

*"745474"

*"+-x/", etc.

I use this code, but it won't gave the correct answer:
Pattern p = Pattern.compile("[A-Za-z&-&']");
Matcher m = p.matcher(s);
System.out.println(m.matches());

What's wrong with my regex?

A: *

*Add a + after the expression to say "one or more of those characters":

*Escape the hyphen with \ (or put it last).

*Remove those & characters:

Here's the code:
Pattern p = Pattern.compile("[A-Za-z'-]+");
Matcher m = p.matcher(s);
System.out.println(m.matches());

Complete test:
String[] ok = {"food","RocKet","man-in-the-middle","kahsdkjhsakdhakjsd","JESUS"};
String[] notOk = {"gipsy76", "www.google.com", "me@gmail.com", "745474","+-x/" };

Pattern p = Pattern.compile("[A-Za-z'-]+");

for (String shouldMatch : ok)
    if (!p.matcher(shouldMatch).matches())
        System.out.println("Error on: " + shouldMatch);

for (String shouldNotMatch : notOk)
    if (p.matcher(shouldNotMatch).matches())
        System.out.println("Error on: " + shouldNotMatch);

(Produces no output.)

A: This should work:
"[A-Za-z'-]+"

A: But "-word" and "word-" are not valid. So you can uses this pattern:
WORD_EXP = "^[A-Za-z]+(-[A-Za-z]+)*$"

A:
Regex - /^([a-zA-Z]*('|-)?[a-zA-Z]+)*/

You can use above regex if you don't want successive "'" or "-".
It will give you accurate matching your text.
It accepts
   man-in-the-middle
   asd'asdasd'asd
It rejects following string
man--in--midle
asdasd''asd

A: Hi Aloob please check with this, Bit lengthy, might be having shorter version of this, Still...
[A-z]*||[[A-z]*[-]*]*||[[A-z]*[-]*[']*]*


text:
Q: make child divs display inline with 100% width and parent overflow scroll I've tried all day and can't seem to get this to work.
Here is a fiddle so you can understand what I'm talking about: http://jsfiddle.net/P2BqP/I am sure it can be done with no Java script, but i guess there is something i am missing here.
So I want to make the child divs take the value of the parent's min-width, so I can be able to horizontally scroll left or right, without having the parent expand. The reason I am doing this is because I want a scalable carousel without having to have a set width for the parent and child elements. I would like it to be scalable no matter the screen size or if user maximizes window size.Does this make sence?

A: Simplified version, but should get you the general idea:
CSS:
#container {
    background-color:#CCC;
    min-width:50%;
    max-width:300%;
    overflow-x:scroll;
    white-space:nowrap;
    display: block;
}

#container div {
    border: 1px solid #006;
    white-space:nowrap;
    display: inline-block;
    width:100%;
}

http://jsfiddle.net/P2BqP/3/

A: Thanks for the help, I actually ended up doing this: http://jsfiddle.net/P2BqP/13/
I was trying to make a carousel that wraps the text inside the child divs. Seems like i was trying a wrong approach.


text:
Q: Loading a video in a byte array form from spring is not playing on mobile I have a web service that loads a media file in a form of a byte array. It loads and plays perfectly on desktop web browser but fails on any mobile device.
Any tips on how to fix this?
I already set the necessary headers and still it doesn't play.
Update:
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Headers", "Content-Range, X-Chunked-Output, X-Stream-Output");
        headers.add("Access-Control-Allow-Methods", "GET");
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Expose-Headers", "Content-Range, X-Chunked-Output, X-Stream-Output");
        headers.add("Cache-Control", "public, max-age=29030400, immutable");
        headers.add("Accept-Ranges", "bytes");
        headers.add("Connection", "keep-alive");
        headers.add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(
                IOUtils.toByteArray(inputStream),
                headers,
                HttpStatus.OK);

It load pretty well on desktop apps but not on mobile.
TIA.

A: Solution for this (thanks to a colleague of mine) is that Apple devices such as iphone/ipad treats all videos as a stream content. This means that when a device request for a mp4 (for example), it tries to get a partial content of the request in bytes.
This means that if the request is coming from an Apple device, the code should set the user agent and range appropriately.
conn.setRequestProperty("User-Agent","<User agent depending on the device");
conn.setRequestProperty("Range","bytes: 0-1023");


text:
Q: how to integrate galleria theme into cakephp when i load images from database dynamically  jquery was not supported to gallery images  the following error displayed
Error: jQuery(".be-infired").jcarousel is not a function
and its my script given below

$(document).ready(function(){
  jQuery('.be-infired').jcarousel( function(){
  scroll: 1
 });
});

and cakephp code

          image("/img/user/".$img);?>

A: The error means that jCarousel files are not getting loaded correctly. Check the  paths carefully. Also check if you are unloading jquery.jcarousel.min.js anywhere later in your code.


text:
Q: Same activity only once in stack I can't get the following to work.
Activities: A (Launcher Activity), B (Picture Activity), C (UserProfile Activity)
User behavior: A -> B1 -> C -> B2 (B1/B2 are the same activity, but different pictures.)
What I want to happen when pressing the back button: B2 -> C -> A
With which FLAG do I have to start Activity B? What I tried so far and what got me the wrong result

*

*FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK: B2 -> App gets closed

*FLAG_ACTIVITY_NEW_TASK: B2 -> C -> B1 -> A

*FLAG_ACTIVITY_CLEAR_TOP: B2 -> A

*FLAG_ACTIVITY_REORDER_TO_FRONT: This FLAG does start B1 instead of B2, because Activity B is already in the stack. It looks promising, because when going back its B1 -> C -> A. Do I have to combine this FLAG with another? I don't want to reorder B1 to the top of the stack, but remove it and start B2.

The UserProfile Activity gets started without any flags. Any help appreciated.

A: FLAG_ACTIVITY_REORDER_TO_FRONT as you said looks promising. It starts the same activity again but moves it in the history stack.
At first, this will restore the original state (picture B1), but you do receive the new Intent in Activity B. Use this to update the data:
@Override
public void onNewIntent(Intent newIntent) {
    super.onNewIntent(newIntent)
    // update picture here from new newIntent
}

There are alternatives, such as setting singleInstance as launchmode in the manifest. But they all boil down to using onNewIntent to update the contents.


text:
Q: htaccess require host domain not working correctly I have a folder full of folders with json files. I want to restrict AJAX requests to these files to certain domains.
I made an htaccess file to restrict this but it isn't work. My htaccess is as follows:
<FilesMatch "\.json$">
    <RequireAny>
        Require host thedomain.com
        Require host thehurts.com
    </RequireAny>
</FilesMatch>

This is blocking everyone, including myself.
I read that Require local gives myself access but that didn't work when I added it.
if I add Require all granted I have access and can AJAX to the files from other domains but that also gives access to everyone on the internet, which is what I don't want.
Any ideas?


text:
Q: ActionListener only responding once I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:

*

*Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.

*For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.

WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;

public class WheelBuilder extends JApplet{

public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;

public void init()
{
    resize(540,600);
    spin = new JButton("SPIN!");
    spin.addActionListener(new spinListener());
    Container cp = getContentPane();
    cp.setVisible(true);
    cp.setBackground((Color.GREEN).darker().darker());
    Abet = new JButton("+BET+");
    Abet.addActionListener(new aListener());
    Sbet = new JButton("-BET-");
    Sbet.addActionListener(new sListener());

    cp.add(Sbet);
    cp.add(spin);
    cp.add(Abet);
    cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
    page.setColor((Color.GREEN).darker().darker());
    page.fillRect(0, 0, 1000, 1000);
    setBackground((Color.GREEN).darker().darker());
    wheel.paintWheel(page, wheel.getStatus());
    page.setColor(Color.BLACK);
    page.drawString("TOTAL: "+total, 400, 50);
    page.drawString("Current Bet: "+Tbet, 400, 25);
    page.drawString("Last Spin:", 50, 25);
    page.setColor(Color.WHITE);
    page.fillOval(260, 75, 20, 20);
    page.fillRect(50, 35, 60, 25);
    page.setColor(color);
    page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
    Timer tm = new Timer(100, this);
    int count = 0;
    int countEnd = randomSpin();

    public void actionPerformed(ActionEvent e)
    {
        tm.start();
        changeWheel();
        if (wheel.getStatus())
        {
            color = Color.RED;
            last = (int)(Math.random()*7)*2+1;
        }
        else
        {
            color = Color.BLACK;
            last = (int)(Math.random()*7)*2+2;
        }
    }
    public void changeWheel()
    {
        int countEnd = randomSpin();
        if (count <= countEnd)
        {
            wheel.setStatus(!(wheel.getStatus()));
            repaint();
            count++;
        }

    }
    public int randomSpin()
    {
        return ((int)(Math.random()*2)+21);
    }

}
public class aListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if (Tbet <= total-50)
        {
            Tbet+=50;
        }
        last = 0;
        repaint();
    }
}
public class sListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if (Tbet > 50)
        {
            Tbet-=50;
        }
        last = 0;
        repaint();
    }
}
}

RouletteWheel
import javax.swing.JApplet;
import java.awt.*;

public class RouletteWheel extends JApplet {

public boolean status;

public void paintWheel(Graphics page, boolean status)
{
    if (status){
        setBackground(Color.green);
        page.setColor(Color.orange.darker().darker());
        page.fillOval(20, 20, 500, 500);
        page.setColor(Color.WHITE);
        page.drawOval(40, 40, 460, 460);
        page.setColor(Color.BLACK);
        int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
        int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
        page.fillPolygon(xback, yback, 16);

        int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
        int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
        page.setColor(Color.BLACK);
        page.setColor(Color.RED);
        page.fillPolygon(xvals, yvals, 24);

        page.setColor(Color.orange.darker().darker());
        page.fillOval(140, 140, 260, 260);
        page.setColor(Color.lightGray);
        page.fillOval(220, 220, 100, 100);
        page.setColor(Color.GRAY);
        page.fillOval(240, 240, 60, 60);
        page.setColor(Color.DARK_GRAY);
        page.fillOval(260, 260, 20, 20);

        page.setColor(Color.WHITE);
        page.drawOval(100, 100, 340, 340);
        page.drawOval(110, 110, 320, 320);

    }
    if (!status)
    {
        setBackground(Color.green);
        page.setColor(Color.orange.darker().darker());
        page.fillOval(20, 20, 500, 500);
        page.setColor(Color.WHITE);
        page.drawOval(40, 40, 460, 460);
        page.setColor(Color.RED);
        int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
        int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
        page.fillPolygon(xback, yback, 16);

        int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
        int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
        page.setColor(Color.BLACK);
        page.fillPolygon(xvals, yvals, 24);

        page.setColor(Color.orange.darker().darker());
        page.fillOval(140, 140, 260, 260);
        page.setColor(Color.lightGray);
        page.fillOval(220, 220, 100, 100);
        page.setColor(Color.GRAY);
        page.fillOval(240, 240, 60, 60);
        page.setColor(Color.DARK_GRAY);
        page.fillOval(260, 260, 20, 20);

        page.setColor(Color.WHITE);
        page.drawOval(100, 100, 340, 340);
        page.drawOval(110, 110, 320, 320);

    }
}
public boolean getStatus()
{
    return status;
}
public void setStatus(boolean s)
{
    status = s;
}
}


text:
Q: Is there any andoid app to validate qr code? I am organizing an event for which I sold tickets using Holvi, which generates a QR codes upon successful payment.  Holvi generates an excel of all registered people.
Problem: I am searching for an android app to validate the ticket (with/without internet connection)
Looking for an app which can import the Registered Excel sheet, as  I scan the ticket on the event day it should automatically validate against the imported data and display SUCCESS/FAILED real-time.  It would be great if it can remove the duplicates while scanning as there are 4 volunteers taking care of check-in validation.
I searched through the entire heap of Google Playstore.


text:
Q: Segregate products in categories according to popularity I would like to segregate "out of style" items to go at the bottom of each category, all dependable on the popularity of the product or sold amount.
Basically, the most selling products to be at the top of the category.
Is there any easy way of doing it? What are the options?