text:
Q: java.lang.StringIndexOutOfBoundsException while playing video in videoView : Android v 4.2.1 I am getting this crash when I play video on videoView in Android version 4.2.1. I found this out specifically on Micromax Canvas A210 device. It is not showing any message where the error is occurring. Is this a bug or something wrong in application? The crash log is as below:
09-18 11:05:53.245: E/AndroidRuntime(2323): FATAL EXCEPTION: main
09-18 11:05:53.245: E/AndroidRuntime(2323): java.lang.StringIndexOutOfBoundsException: length=11; regionStart=0; regionLength=-1
09-18 11:05:53.245: E/AndroidRuntime(2323):     at java.lang.String.startEndAndLength(String.java:583)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at java.lang.String.substring(String.java:1464)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.widget.VideoView.openVideo(VideoView.java:407)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.widget.VideoView$6.surfaceCreated(VideoView.java:730)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.SurfaceView.updateWindow(SurfaceView.java:606)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.SurfaceView.access$000(SurfaceView.java:88)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:183)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:692)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2123)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4879)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.Choreographer.doCallbacks(Choreographer.java:579)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.Choreographer.doFrame(Choreographer.java:548)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.os.Handler.handleCallback(Handler.java:725)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.os.Looper.loop(Looper.java:153)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at android.app.ActivityThread.main(ActivityThread.java:5297)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at java.lang.reflect.Method.invokeNative(Native Method)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at java.lang.reflect.Method.invoke(Method.java:511)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
09-18 11:05:53.245: E/AndroidRuntime(2323):     at dalvik.system.NativeStart.main(Native Method)

Other versions and devices that I have tested my app on and is working fine are:
Android versions: 4.1.2, 4.2.2, 4.3, 2.3.3, 4.0.3, 4.0.4
Devices: Samsung Galaxy s2, Samsung Galaxy Tab 2 (7" and 10"), Samsung Galaxy s plus, Sony Xperia Tipo dual, Samsung Galaxy Grand (Quatro and Mega), Nexus 4

A: Are you a developer and using Video View in you application. If so try to debug and verify that you provide a valid uri/url to the Video View. Though there is a null check in the openVideo() of the android.widget.VideoView class, the uri may be empty string.
Here is the source of the Video View class for the android version you mentioned.

A: I had the same problem and found that it is a micromax specific bug while using videoview.
here's an alternate way to do it using "TextureView" in android
BackGroundVideo.java
public class BackGroundVideo extends AppCompatActivity implements TextureView.SurfaceTextureListener {
ProfileTracker profileTracker;
private MediaPlayer mMediaPlayer;
private TextureView mTextureView;
private static final String TAG = sus.class.getName();

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

    initView();

}

private void initView() {
    mTextureView = (TextureView) findViewById(R.id.play_video_texture);
    // SurfaceTexture is available only after the TextureView
    // is attached to a window and onAttachedToWindow() has been invoked.
    // We need to use SurfaceTextureListener to be notified when the SurfaceTexture
    // becomes available.
    mTextureView.setSurfaceTextureListener(this);
}

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
    Surface surface = new Surface(surfaceTexture);

        mMediaPlayer.prepareAsync();

        // Play video when the media source is ready for playback.
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });

    } catch (IllegalArgumentException e) {
        Log.d(TAG, e.getMessage());
    } catch (SecurityException e) {
        Log.d(TAG, e.getMessage());
    } catch (IllegalStateException e) {
        Log.d(TAG, e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }

}

@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

}

@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    return false;
}

@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {

}

}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.test.sus">
<TextureView
    android:id="@+id/play_video_texture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true"
    android:fitsSystemWindows="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"/>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button2"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="167dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/te"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="122dp" />
</RelativeLayout>

splash_layout.xml
Hope this works for you!


text:
Q: SharePoint Custom Module Development and Deployment Good Day,
We're working on custom module (Information Management System) for SharePoint. The project file of this module is a Class Library which contains User Controls. The User Controls was based upon SmartPart and AJAX Extension Toolkit. The module has a separate database which has tables/views/stored procedure.
On development environment, we deploy the module in following steps:

*

*Restore the backup copy of the module database
on the pre-production or test
environment

*Install AJAX Extension Toolkit

*Modify web.config of web application for connection string, safecontrol entry of AJAX Extension, enablesessionstate set to true of pages, add AJAX Extension tag entry, and uncomment the following line:
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>

*Create a UserControls folder in web application root and copy all User Controls there. As SmartPart will (can only, I assume) locate User Controls
This is how we do. I sure this is not a good practice and there should be ways to do this in much better way.

One of my question is can we create a
  separate web.config file which will
  have all required tags and settings
  there so we won't need to change web
  application web.config? Just guessing!

As all WSPBuilder users are aware of this, that you cannot modify the manifest.xml file and no good integration with web application folder. I don't why SmartPart pick the web application root folder to locate User Controls. Is it possible that SmartPart can start picking User Controls from 12-Hive's TEMPLATE\CONTROLTEMPLATES folder?
We are looking for a more appropriate way of doing this. And for me, specific to this case, a good practice would be eliminate all the manual configuration/setup steps. The module user doesn't even need to do a single manual setup to make this thing up and running. I am sure there are many ways of doing this much better than this but what would be the best way to handle it.

Also, I would like to have suggestions
  on Custom Module development on
  SharePoint good (or best) practices.

We are using a set of tools like WSPBuilder, Visual Studio Extension for WSS, STSDEV, SPVisualDev, SharePoint Content Deployment Wizard, SharePoint Administration Tools, SharePoint Installer.
Thanks.
Have a Good Day!

A: There is a way to point SmartPart to point to the ControlTempltes folder but it requires recompilation of the SmartPart solution. To get SmartPart to look inside the 12\CustomTemplates\YourFolder\ you'll need to get the code for SmartPart from codeplex, alter the code inside the point to where you need and recompile it and repackage as a WSP. This is how I got around the issue. If you do that and maintain your own version of it, you'll save development time in the future. We've done this and will reuse our own version with other clients in the future.
Hopefully the SmartPart's original code will get updated to accommodate this.
Tip for SmartPart controls:
Make sure you turn of any validators in he your controls when you're in edit mode else you'll end up filling out the all the fields in order to publish the page. SharePoint does funny things in edit mode so make sure you test all your usercontrols with the SmartPart in edit mode.
Deploying to resources
I think this may be a permissions issues, usually people deploy assemblies to 80\bin and I don't remember doing anything special to make that work.
Since wsp's are deployed via SharePoint, if SharePoint doesn't have permissions to the 'resources' folder, then that might fail.
Possible issues:
a) Resource folder doesn't exist in inetpub or wherever you're root folder is. (Try creating the structure)
b) Resource folder doesn't have the same permissions set as the bin folder. (Test to see if you can deploy an assembly to the bin)
c) Resource folder is readonly and thats causing the problem. (Take off read only)
d) SharePoint never allows for files other than assemblies to be displayed to the root folder via WSP (Unlikely and not sure about this)
My recommendation for troubleshooting such an issue would be to extract the contents of the wsp into a folder (Rename the .wsp extention to .cab and extract the .cab) .  Fiddle with the files and structure > create a cab file from it (google this) > Rename extention back to .wsp > Deploy > Test > If it doesn't work, fiddle with the structure again and try again.

A: *

*
Modify web.config of web application
  for connection string, safecontrol
  entry of AJAX Extension,
  enablesessionstate set to true of
  pages, add AJAX Extension tag entry,
  and uncomment the following line:
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>

Use class SPWebConfigModification to add entries in web.config (examples on adding ajax entries in web.config with code).

*

*
Create a UserControls folder in web
  application root and copy all User
  Controls there. As SmartPart will (can
  only, I assume) locate User Controls

If i`m correct, you can just create folder with name "80" (just like folder "12") and within predefined folders, deploy your own.
From WSPBuilder documentation:

The 80 folder represents the
  WebApplication folder and contains
  following subfolders 80\bin,
  80\wpcatalog, 80\resources. The 80\bin
  contains the dll's. If you have some
  webpart definitions (webpart, dwp)
  files, they goes into the wpcatalog
  folder. Any file can be added to the
  resource folder.

So maybe it would be a good idea to drop them inside resources folder?

redpajama_set_name: RedPajamaStackExchange


text:
Q: why the text path are not rendered? I really got puzzled why these two text are not displayed along the line and path. Could someone point me out?

  <svg width="300px" height="300px">
    <line id="ok" x1="10" y1="20" x2="100" y2="100" stroke="red" stroke-width=10>
      <text>
        <textPath stroke="black" xlink:href="#ok">OHHHHSUHDIAU</textPath>
      </text>
    </line>
    <path id="io" d="M10,10 L100,10" stroke="blue" stroke-width=10>
      <text>
        <textPath stroke="black" xlink:href="#io">io</textPath>
      </text>
    </path>
  </svg>

A: you can only do a <textPath> on a <path>
placing the <text> inside the <line> or <path> elements were causing them not to be rendered.
here is my best guess at what you're trying to accomplish, I hope this helps

<svg width="300px" height="300px">
  <defs>
    <path id="io" d="M10,10 L100,10" />
    <path id="ok" d="M10,20 L100,100" />
  </defs>
  <use xlink:href="#io" stroke-width="10" stroke="blue" />
  <use xlink:href="#ok" stroke-width="10" stroke="red" />
  <text>
    <textPath stroke="black" xlink:href="#io">io</textPath>
    <textPath stroke="black" xlink:href="#ok">OHHHHSUHDIAU</textPath>
  </text>
</svg>


text:
Q: Junit for anonymous class Class ABCD{

private int startProcess(String actualPath) {
    Task<Integer>  runDriverTask = new Task<Integer>() {
    @Override
    protected Integer call() throws Exception {
        int exitCode = -1;
        return 1;
    }
  };
  ....
  ....
}

Some one please suggest how to write JUnits to invoke call method.
I have to do code coverage but unable to reach upto call() method.
What can we use ? Easymock, Power mock, Mockito or anything else.

A: Your problem is that you want to control something that is completely out of your control.
If your "code under test" creates the objects it is dealing with (and it really doesn't matter if you do "new WhateverClass" or a "new anonymous class instance please".
So, if you have to gain control, the only good way is to turn to dependency injection to provide pre-created objects to your code under test (see here for more information how/why to do that).
In addition to that, you probably could create a factory that creates such tasks for you - then you can write unit tests for the factory; that that simply create tasks and check their properties.


text:
Q: Data not give back correctly with json.parse() I am having issues about getting data when check date availability, the data gave back to me not correctly
Here is my code base:
searchFakeMonthlyAvailability(query: FormData): Promise<Results> {
    return new Promise<Results>((resolve, reject) => {
        setTimeout(() => {
            let srStr: string = JSON.stringify(searchMonthlyResults);
            let sr: Results = JSON.parse(srStr);
            console.log('srStr: ', srStr)
            console.log("sr: ", sr)
            sr.monthlyresults = sr.monthlyresults.filter(result => moment(result.date).toDate().getMonth() === moment(query.startDate).toDate().getMonth())
            resolve(sr);
        }, 1500);
    });
}

so when I console.log(stStr) this is what i got:

{"filters":{"roomType":[{"value":"2BR","description":"2
Bedroom","priority":800,"minimumPoints":650},{"value":"3BR","description":"3
Bedroom","priority":900,"minimumPoints":800}],"views":[{"value":"GV","description":"Garden
View","minimumPoints":650},{"value":"OS","description":"Ocean
Side","minimumPoints":650},{"value":"OV","description":"Ocean
View","minimumPoints":650}],"activities":[],"area":[{"name":"St. Kitts
and Nevis","continent":"Caribbean","states":[{"name":"","cities":["St.
Kitts"]}]}]},"results":[],"monthlyresults":[{"date":"20211120","minimumPoints":925},{"date":"20211117","minimumPoints":1050},{"date":"20211129","minimumPoints":750},{"date":"20211116","minimumPoints":1050},{"date":"20211111","minimumPoints":925},{"date":"20211101","minimumPoints":650},{"date":"20211127","minimumPoints":925},{"date":"20211108","minimumPoints":1050},{"date":"20211119","minimumPoints":1100},{"date":"20211107","minimumPoints":850},{"date":"20211118","minimumPoints":1500},{"date":"20211102","minimumPoints":650},{"date":"20211128","minimumPoints":750}],"dailyresults":[],"minimumNights":0,"maxOutMonth":"20220906"}

and when I do console.log(sr): this is what I got:

dailyresults: [] filters: activities: [] area: [{…}] roomType:
Array(2) 0: {value: '2BR', description: '2 Bedroom', priority: 800,
minimumPoints: 650} 1: {value: '3BR', description: '3 Bedroom',
priority: 900, minimumPoints: 800} length: 2 [[Prototype]]: Array(0)
views: Array(3) 0: {value: 'GV', description: 'Garden View',
minimumPoints: 650} 1: {value: 'OS', description: 'Ocean Side',
minimumPoints: 650} 2: {value: 'OV', description: 'Ocean View',
minimumPoints: 650} length: 3 [[Prototype]]: Array(0) [[Prototype]]:
Object maxOutMonth: "20220906" minimumNights: 0 monthlyresults: []
monthlyunavailableresults: (3) [{…}, {…}, {…}] results: []

my data missing monthlyresults. How can I fix this ?
Updated


text:
Q: How to fetch specified element from Stack implemented in ArrayList by using only primitives I have a situation where Stack data structure is implemented using ArrayList in Java and have to make use of a method which has to use only primitives and return the corresponding element specified through the index.
The code is mentioned below:
public class StackTest {
    public static void main(String... s) throws Exception {
        MyStack stack = new MyStack();
        int random = (int)(Math.random() * 100);
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(random);
        stack.push(50);
        stack.push(60);

        assertTrue(getStackElement(stack, 0) == 60);
        assertTrue(getStackElement(stack, 1) == 50);
        assertTrue(getStackElement(stack, 3) == 30);
        assertTrue(getStackElement(stack, 4) == 20);
        assertTrue(getStackElement(stack, 5) == 10);
        try {
            getStackElement(stack, 6);
            assertTrue(false);
        } catch(Exception e) {
            assertTrue(true);
        }
        assertTrue(getStackElement(stack, 2) == random);
    }
    public static void assertTrue(boolean v) {
        if(!v) {
            Thread.dumpStack();
            System.exit(0);
        }
    }
    public static int getStackElement(MyStack stack, int index) throws Exception
    {
        // 1) I CAN ONLY WRITE CODE HERE
        // 2) DO NOT MODIFY ANYTHING ELSE
        // 3) USE OF new KEYWORD IS NOT ALLOWED
        // 4) DO NOT USE REFLECTION
        // 5) DO NOT USE STRING CONCATENATION

    }

}
class MyStack {
    private java.util.List<Integer> list;
    public MyStack() {
        list = new java.util.ArrayList<Integer>();
    }
    public int pop() {
        if(isEmpty()) throw new RuntimeException("Stack is empty!");
        return list.remove(list.size() - 1);
    }
    public void push(int i) {
        list.add(i);
    }
    public int peek() {
        if(isEmpty()) throw new RuntimeException("Stack is empty!");
        return list.get(list.size() - 1);
    }
    public boolean isEmpty() {
        return list.size() == 0;
    }
}

*
The following rules have to be followed:
• If the index is out of range, an Exception must be thrown (any Exception will do) but you can assume that no negative index will be passed in
• The stack object passed into the method must remain unmodified upon return (even if an Exception was thrown)
• Do not create any other objects in the method, including Strings, arrays; use only primitive types
• Do not define any other classes and methods
• Do not use reflection
• Do not modify the MyStack class
Please find my code below:
public static int getStackElement(MyStack stack, int index) throws Exception
    {
        int returnCode = 0;
        int count = 0;

        int first=0,second=0,third=0,fourth=0,fifth=0,sixth=0;

        /* Counting & Fetching the elements from Stack  START */

        if(!stack.isEmpty())
        {
            count++;
            sixth = stack.pop();
        }
        if(!stack.isEmpty())
        {
            count++;
            fifth = stack.pop();
        }
        if(!stack.isEmpty())
        {
            count++;
            fourth = stack.pop();
        }
        if(!stack.isEmpty())
        {
            count++;
            third = stack.pop();
        }
        if(!stack.isEmpty())
        {
            count++;
            second = stack.pop();
        }
        if(!stack.isEmpty())
        {
            count++;
            first = stack.pop();
        }
        /* Counting & Fetching the elements from Stack  END */

        /*  Inserting elements into Stack   START   */
        if(count == 1)
        {
            stack.push(sixth);
        }
        else if(count == 2)
        {
            stack.push(fifth);
            stack.push(sixth);
        }
        else if(count == 3)
        {
            stack.push(fourth);
            stack.push(fifth);
            stack.push(sixth);
        }
        else if(count == 4)
        {
            stack.push(third);
            stack.push(fourth);
            stack.push(fifth);
            stack.push(sixth);
        }
        else if(count == 5)
        {
            stack.push(second);
            stack.push(third);
            stack.push(fourth);
            stack.push(fifth);
            stack.push(sixth);
        }
        else if(count == 6)
        {
            stack.push(first);
            stack.push(second);
            stack.push(third);
            stack.push(fourth);
            stack.push(fifth);
            stack.push(sixth);
        }
        /*  Inserting elements into Stack   END */

        if(index >= count)
        {
            System.out.println("Throwing Exception");
            throw new Exception("Index out of range");
        }

        if(index == 0)
            returnCode = sixth;
        else if(index == 1)
            returnCode = fifth;
        else if(index == 2)
            returnCode = fourth;
        else if(index == 3)
            returnCode = third;
        else if(index == 4)
            returnCode = second;
        else if(index == 5)
            returnCode = first;

        return returnCode;
    }

This solution is not efficient and I am looking for better solution than this.
Thanks,


text:
Q: Get declared parameters Data type and add the parameters dynamically I'm having a problem in retrieving declared parameters in SQL query in C#.
Here is my SQL query in SQL server.
Declare @param1 int =1
Declare @param2 varhar(255)='Admin'

SELECT * FROM tblUsers WHERE role=@param2 AND id=@param1`

The query is executing successfully on SQL server.
I'd like to use C# to get all declared parameters and Data types. In this case:
PARAMETER    DATA TYPE
@param1      int
@param2.     Varchar

Finally, I'd like to assign the values of the parameters dynamically using a textbox.


text:
Q: How to get the number of unique ingredients per recipe id in a table of recipe ingredients. MySQL I'm running a query that finds recipes that has specific ingredients in them. These ingredients are sent with the query e.g. "sugar, milk, egg".The recipes (recipe_id's) are then ordered by the amount of ingredients found in them, so if a recipe has sugar, milk and egg in it, it will get ordered before a recipe that only has 2 of the ingredients.
Query
SELECT
    recipe_id, COUNT(ingredient) AS ingredient_count
FROM
    ingredients
WHERE
    ingredient LIKE '%sugar%'
    OR ingredient LIKE '%milk%'
    OR ingredient LIKE '%egg%'
GROUP BY
    recipe_id
ORDER BY
    ingredient_count DESC;

Ingredients table
id | recipe_id | ingredient      |
---|-----------|-----------------|
1  | 1         | 2 cups of sugar |

...

Due to all the data being scraped the ingredients table has a bad structure. The ingredients are mixed with unit and amount e.g. "2 cups of sugar". That's the reason I have to use wildcards to find the ingredients. One recipe can also have an ingredient multiple times e.g. "1 cup of sugar" and "2 cups of sugar" (this is due to sub recipes), this is where I start to get problems. Because my where clause will find 2 "sugar" in a recipe the ingredient_count will increase by 2 (ofc), but I only want it to increase by 1 as there is only one ingredient, "sugar".
So what I want to accomplish is to somehow count all the ingredients the query returns BUT if an ingredient is found multiple times e.g. "2 cups of sugar", "1 cups of sugar" I only want to count that as 1, because they both have "sugar" in them.
This query does what I want with the counting but for some reason only returns very few recipes when it should return a lot more.
This query is not made by me
SELECT result.recipe_id, COUNT(*) FROM (
    SELECT
        recipe_id, ingredient
    FROM
        ingredients
    WHERE
        (ingredient LIKE '%sugar%')
        OR (ingredient LIKE '%milk%')
        OR (ingredient LIKE '%egg%')
    GROUP BY
        CASE
            WHEN ingredient LIKE '%sugar%' THEN 'sugar'
            WHEN ingredient LIKE '%milk%' THEN 'milk'
            WHEN ingredient LIKE '%egg%' THEN 'egg'
            ELSE NULL
        END
    ) AS result
GROUP BY result.recipe_id;

A: SELECT *,
       IF(ingredient LIKE '%sugar%', 1, 0) as sgr,
       IF(ingredient LIKE '%milk%', 1, 0) as mlk,
       IF(ingredient LIKE '%egg%', 1, 0) as gg
FROM
    ingredients
    WHERE
        (ingredient LIKE '%sugar%')
        OR (ingredient LIKE '%milk%')
        OR (ingredient LIKE '%egg%')
ORDER BY sgr + mlk + gg DESC;

A: If you can separate "unit" and "ingredient_name" into 2 separate columns, then you might accomplish it with this:
SELECT
    recipe_id, COUNT(DISTINCT ingredient_name) AS ingredient_count
FROM
    ingredients
WHERE
    ingredient_name LIKE '%sugar%'
    OR ingredient_name LIKE '%milk%'
    OR ingredient_name LIKE '%egg%'
GROUP BY
    recipe_id
ORDER BY
    ingredient_count DESC;

But what you are asking, is for MySQL to know that with a string like "1 cup of sugar", that "1 cup" and "sugar" are 2 separate values it can operate on.
However, If you can Always count on "of" being a separator, you could  try computing the ingredient_name on the fly using some clever use of MySQL string searching and chopping functions.  Tho very poor performance, this would replace "ingredient_name" in the above query with this:
SUBSTR(ingredient,LOCATE(' of ', ingredient)+4)

A: Expansion of @ast-tm answer:
That answer still didn't solve the "ingredient multiple times" double-counting.  Also, the original question wanted results Grouped by Recipe.
However, still I'm not sure it's technically giving you "the number of unique ingredients", only the number of Sugar-or-Milk-or-Eggs ingredients.  E.g. If a recipe had 10 other ingredients (not Milk or Sugar OR Eggs) those ingredients would be ignored in the counting altogether.
The idea of having to put into your query all the possible ingredient names is bad design in general.  And the query gets messy real-quick.  But in case it helps:
SELECT *,
       IF(ingredient LIKE '%sugar%', 1, 0) as sgr,
       IF(ingredient LIKE '%milk%', 1, 0) as mlk,
       IF(ingredient LIKE '%egg%', 1, 0) as gg
FROM
    ingredients
    WHERE
        (ingredient LIKE '%sugar%')
        OR (ingredient LIKE '%milk%')
        OR (ingredient LIKE '%egg%')
GROUP BY
    recipe_id
ORDER BY
    (MAX(sgr) + AMX(mlk) + MAX(gg)) DESC;

I you wanted to also consider other ingredients, you could try moving your WHERE to a HAVING clause, and use GROUP_CONCAT (tho still doesn't solve the double-counting problem for anything but "sugar", "milk" or "eggs").
This may help get closer to what you need:
SELECT *,
       IF((ingredient NOT LIKE '%sugar%' AND ingredient NOT LIKE '%milk%' AND ingredient NOT LIKE '%egg%'), 1, 0) as others,
       IF(ingredient LIKE '%sugar%', 1, 0) as sgr,
       IF(ingredient LIKE '%milk%', 1, 0) as mlk,
       IF(ingredient LIKE '%egg%', 1, 0) as gg
FROM
    ingredients
GROUP BY
    recipe_id
HAVING
        (GROUP_CONCAT(ingredient) LIKE '%sugar%')
        OR (GROUP_CONCAT(ingredient) LIKE '%milk%')
        OR (GROUP_CONCAT(ingredient) LIKE '%egg%')
ORDER BY
    (others + MAX(sgr) + AMX(mlk) + MAX(gg)) DESC;


text:
Q: hadoop hdfs java - what is the best way to copy a list of files from hdfs to hdfs I have a file that has two columns, the first column is the hdfs path to source files, the second column is the hdfs path to target file:
s1, t1
s2, t2
.., ..
sn, tn
what is the fastest way for me to copy the source path to their respective target path.  is there such a tool for hadoop?
The list is probably 100-200 lines long each file is a few megabytes.

A:
The list is probably 100-200 lines long each file is a few megabytes.

If this a one-off kind of situation, then this isn't large enough to worry about. A dumb ol' shell loop will do fine:
cat pairs-file | while read pair; do hdfs dfs -cp $pair; done


text:
Q: How did the derivative shift? (Turbojet Thrust Equation) While deriving the Turbojet Thrust Equation this is what the author does
$$F=m\cdot a$$
$$F=m\frac{\mathrm{d}v}{\mathrm{d}t}$$
$$F=\frac{\mathrm{d}m}{\mathrm{d}t}v$$
$$F= m^*\cdot v$$
(where $m^*$ is the mass rate flow)
What I don't understand in the above derivtion is that how did they just transform the dv/dt into  a dm/dt

A:
What I don't understand in the above derivation is that how did they
just transform the dv/dt into a dm/dt?

It's not possible. But it might have something to do with the following reasoning, where $p$ is the linear momentum:
$$p=mv$$
Newton's Second Law:
$$F=\frac{\mathrm{d}p}{\mathrm{d}t}=\frac{\mathrm{d}(mv)}{\mathrm{d}t}$$
Apply product rule:
$$F=m\frac{\mathrm{d}v}{\mathrm{d}t}+v\frac{\mathrm{d}m}{\mathrm{d}t}$$
$$F=ma+\dot{m}v$$
Of course, in most problems $\dot{m}=0$.

A: I can't exactly speak for the derivation as you have laid it out here because it doesn't really make sense... perhaps there is additional text that sheds light on what the set of equations means.
However, let's look at what the thrust equation is saying. Newton's second law is often expressed as $F = ma$, but in reality Newton's second law says that the time rate of change of momentum is due to forces on the body:
$$ F = \frac{d}{dt}(mv) $$
and in the classical Newtonian mechanics sense of things where we talk about point particles or spheres or what have you, the mass is usually held constant and so we end up with $F = m\,dv/dt = ma$.
Back to the turbojet thrust equation. What we're interested in is the time rate of change of momentum due to the engine. We can use the product rule to say:
$$ F = \frac{dm}{dt} v + m \frac{dv}{dt} = \dot{m} v + m a$$
If we are at steady state in the reference frame of the engine, meaning we are not accelerating or decelerating, we're just cruising along at constant speed $v$, then the acceleration is zero and we're just left with:
$$ F = \dot{m} v $$
which is the thrust equation saying that an engine's thrust is to mass flow rate through it times the velocity of the exhaust.
Also note that this equation is for the gross thrust at steady state. To get the net thrust or effective thrust, you would need to account for the change in mass flow rate and velocity across the engine by subtracting off ram drag, as in:
$$ F = \dot{m}_{\text{exhaust}} v_{\text{exhaust}} - \dot{m}_{\text{inlet}} v_{\text{inlet}} $$
It also assumes the inlet and exhaust pressures are the same, which is not always the case. The generalized thrust equation has an additional term to account for that situation.


text:
Q: Given the result of diagonalization of a matrix, determine the two invertible matrices. Determine $3$ by $3$ invertible matrices P and Q, such that
$$P\left( \begin{array}{ccc}
                             0 & 1 & 0 \\
                             1 & 0 & 1 \\
                             0 & 1 & 0
                        \end{array} \right)Q = \left( \begin{array}{ccc}
                             1 & 0 & 0 \\
                             0 & 1 & 0 \\
                             0 & 0 & 0
                        \end{array} \right).
$$
I tried to diagonalize the first matrix but the result diagonalized matrix I got is
$$\left( \begin{array}{ccc}
                             0 & 0 & 0 \\
                             0 & -\sqrt{2} & 0 \\
                             0 & 0 & \sqrt{2}
                        \end{array} \right).
$$
The signal doesn't seem to be right...

A: As it stands, the question does not require $P$ and $Q$ to be inverses of each other, or real orthogonal, etc.. So, there is no need to diagonalise the matrix on the left by similarity or by congruence. In fact, since the matrix on the LHS has a zero diagonal and the one on the RHS is positive semidefinite, they are neither similar nor congruent to each other. Thus there does not exist any pair of invertible real matrices $P$ and $Q$ that solves the equation with $P=Q^{-1}$ or $P=Q^T$.
The equation is satisfied if and only if
$$
\pmatrix{1&0\\ 0&1\\ 1&0}\pmatrix{0&1&0\\ 1&0&1}
=\pmatrix{0&1&0\\ 1&0&1\\ 0&1&0}
=P^{-1}\pmatrix{1\\ &1\\ &&0}Q^{-1}
=P^{-1}\pmatrix{1&0\\ 0&1\\ 0&0}\pmatrix{1&0&0\\ 0&1&0}Q^{-1}.
$$
So, it suffices to pick $P$ and $Q$ such that
$$
P^{-1}=\pmatrix{1&0&\ast\\ 0&1&\ast\\ 1&0&\ast},
\ Q^{-1}=\pmatrix{0&1&0\\ 1&0&1\\ \ast&\ast&\ast}.
$$
For instance, we may set
$$
P^{-1}=\pmatrix{1&0&1\\ 0&1&0\\ 1&0&0},
\ Q^{-1}=\pmatrix{0&1&0\\ 1&0&1\\ 1&0&0},
$$
so that
$$
P=\pmatrix{0&0&1\\ 0&1&0\\ 1&0&-1},
\ Q=\pmatrix{0&0&1\\ 1&0&0\\ 0&1&-1}.
$$
Alternatively, you may also continue your work. Suppose you have found two invertible matrices $P_1$ and $Q_1$ such that
$$
P_1\pmatrix{0&1&0\\ 1&0&1\\ 0&1&0}Q_1=\pmatrix{0\\ &-\sqrt{2}\\ &&\sqrt{2}}.
$$
Then
$$
\pmatrix{0\\ &-\frac{1}{\sqrt{2}}\\ &&\frac{1}{\sqrt{2}}}P_1\pmatrix{0&1&0\\ 1&0&1\\ 0&1&0}Q_1=\pmatrix{0\\ &1\\ &&1},
$$
So, if we apply a further permutation to flip the first and the last diagonal entries on the RHS, we obtain
$$
\pmatrix{0&0&1\\ 0&1&0\\ 1&0&0}\pmatrix{0\\ &-\frac{1}{\sqrt{2}}\\ &&\frac{1}{\sqrt{2}}}\pmatrix{0&1&0\\ 1&0&1\\ 0&1&0}Q_1\pmatrix{0&0&1\\ 0&1&0\\ 1&0&0}=\pmatrix{1\\ &1\\ &&0}.
$$
Hence we may set
$$
P=\pmatrix{0&0&1\\ 0&1&0\\ 1&0&0}\pmatrix{0\\ &-\frac{1}{\sqrt{2}}\\ &&\frac{1}{\sqrt{2}}}P_1,
\quad Q=Q_1\pmatrix{0&0&1\\ 0&1&0\\ 1&0&0}.
$$

A: Denoting the matrix on the left-hand side by $A$, let $T:\mathbb R^3\to\mathbb R^3$, $T:\mathbf x\mapsto A\mathbf x$. Your exercise is then equivalent to finding bases for the domain and codomain of $T$ such that the matrix of $T$ relative to those bases is $\operatorname{diag}(1,1,0)$. The matrices $P$ and $Q$ that you are being asked to find are the corresponding change-of-basis matrices.
As explained in this answer, the basic process is to find a basis for the kernel of $T$ and extend that to a basis of $\mathbb R^3$. One way to find this extension is to compute a basis for the row space of $A$—the row and null spaces of a matrix are complementary. Collecting these basis vectors into the columns of a matrix gives you $Q$. Recalling that the columns of a transformation matrix are the images of the basis vectors, it should be clear that the codomain basis must include all of the nonzero images of these domain basis vectors (in the correct order, of course). Complete this basis any way you like and collect these vectors into the matrix $P^{-1}$.


text:
Q: Access a hyperlinked cell from another cell in same sheet vba Following is a set up of my worksheet:

Cell M7 is hyperlinked to the large merged cell E6. My code needs to access the address of the destination cell from M7 (which will be E6) and assign that address to a range variable called "testing".
Once I have the address of the hyperlinked destination cell (E6) using "testing", I can then format the range address of "testing" however i want.
Here is what I have tried so far
Dim lcell As Range
Dim testing As Range

        testing = lcell.Hyperlinks(1).Range
        testing.Value = "TEST"

This gives me the following error:
  Run-time error: 91

  Object variable or With block variable not set

A: This function will return a reference to a hyperlink's target range whether it is the hyperlink is set by the HYPERLINK WorkSheetFunction or in the cell's hyperlink collection.
Sub Example()

    Dim lcell As Range
    Dim TestRange As Range

    Set lcell = Range("A1")

    Set TestRange = getHyperLinkTarget(lcell)

    If Not TestRange Is Nothing Then

        TestRange.Value = "TEST"

    End If

End Sub

Function getHyperLinkTarget(HSource As Range) As Range
    Dim address As String, formula As String
    formula = HSource.formula
    If HSource.Hyperlinks.Count > 0 Then
        address = HSource.Hyperlinks(1).SubAddress
    ElseIf InStr(formula, "=HYPERLINK(") Then
        address = Mid(formula, InStr(formula, "(") + 1, InStr(formula, ",") - InStr(formula, "(") - 1)
    End If

    On Error Resume Next
    If Len(address) Then Set getHyperLinkTarget = Range(address)
    On Error GoTo 0
End Function

Thanks to ThunderFrame for pointing out the HYPERLINK Worksheet function.

A: This should do what you're after. You need to parse the contents of the M7 formula, so my code assumes the M7 formula only contains a Hyperlink formula like:
=HYPERLINK(E6,"RSDS")

And the VBA looks like:
Sub foo()

  Const hyperlinkSignature = "=HYPERLINK("

  Dim rng As Range
  Set rng = Range("M7")

  Dim hyperlinkFormula As String
  hyperlinkFormula = Range("M7").formula

  Dim testing As Range

  'Check the cell contains a hyperlink formula
  If StrComp(hyperlinkSignature, Left(hyperlinkFormula, Len(hyperlinkSignature)), vbTextCompare) = 0 Then
    Dim hyperlinkTarget As String
    hyperlinkTarget = Mid(Split(hyperlinkFormula, ",")(0), Len(hyperlinkSignature) + 1)

    Set testing = Range(hyperlinkTarget)

    testing.Value = "TEST"

  Else
    'Check if the cell is a hyperlinked cell
    If Range("M7").Hyperlinks.Count = 1 Then
      'Credit to Thomas for this line
      Set testing = Range(Range("M7").Hyperlinks(1).SubAddress)
      testing.Value = "TEST"
    End If

  End If

End Sub

Or, if you want a briefer method that doesn't bother checking the M7 formula contains a hyperlink, you could use:
Dim target As Range
Set target = Range(Range("M7").DirectPrecedents.Address)
target.Value = "Test"


text:
Q: RegEx pattern oversteps the target I am working with a RegPattern to identify and capture URL's in a CSS file and appends a version identifier. This pattern works most of the time. However, one of the packaged CSS files is foiling it.
url\((\""|\')?(?<path>(.*))?(\""|\')?\)

When used with this chunk of CSS:
.ui-widget-overlay { background: #252526 url(images/ui-bg_flat_0_252526_40x100.png) 50% 50% repeat-x; opacity: .50;filter:Alpha(Opacity=50); }

It captures this chunk of text:
url(images/ui-bg_flat_0_252526_40x100.png) 50% 50% repeat-x; opacity: .50;filter:Alpha(Opacity=50)

This is being used in C# with a call to the Replace method.

A: Your problem is greedy Regex. Since you have another bracket in your CSS, it makes .* as the whole strin.
Use this:
 url\((\""|\')?(?<path>([^\)]+))?(\""|\')?\)

I have replaced .* with [^\)]+ (you can use [^\)]*  but I feel URL cannot be blank) => so it will find all characters that are not closin brackets.

A: The simplest fix is to make the .* non-greedy by adding ? after the .*
Before:
url\((\""|\')?(?<path>(.*))?(\""|\')?\)

After:
url\((\""|\')?(?<path>(.*?))?(\""|\')?\)

Note that the simplest fix is not necessarily the most efficient.

A: The .* bit is "greedy" - it'll match as much as it possibly can.  And because there's another right parenthesis later on in that line, that lets it count the first left parenthesis as part of the .* - which it's more than happy to do!
As long as none of your URLs have parentheses in them, changing .* to [^)]* (you might need to escape it - not sure) should take care of everything.
Hope this helps!

A: Try this expression:

url\([^)]+\)

A: The immediate problem is that you've got the second question mark in the wrong place.  The first part of (?<path>(.*))? matches zero or more of any characters and saves them in a group named "path", and the ? makes the whole thing optional.  You probably meant to make the .* non-greedy, which you would do by moving the question mark inside the group: (?<path>.*?) (I also got rid of the unneeded inner group.)
But that still leaves you with a very brittle regex.  It doesn't account for optional whitespace surrounding the URL, and it can be fooled by quotes or parentheses in the URL, which are legal if they're escaped with backslashes.  You could probably with that for quite some time, but there are plenty of perfectly legal inputs that it won't match, and illegal inputs that it won't match.  The same is true of (?<path>[^)]*), which others have suggested.
Here's a more robust regex:
Regex cssUrls = new Regex(@"(?i)
  url\(\s*
  (?>
    ([""'])(?<path>(?>(?:(?!\1).)*))\1
   |
    (?<path>(?>(?:[^()'""\s]+|\\.)*))
  )
  \s*\)
");

The first alternative matches a URL in quotes, ensuring that the opening and closing quotes are of the same type.  The second alternative matches a non-quoted URL, optionally containing escaped parentheses, quotes, or whitespace.


text: Q: Is there any way to access .couch files with other owner and group set on the couchdb files? Let's say I have my .couch in some directory A (owner x group x). But I want to use this particular directory as the database_dir of CouchDB. But as soon as I use the directory A as database directory the CouchDB fails to start. Is there any way I can allow read and write access to the .couch files in the directory A to the CouchDB user?


text:
Q: Closing powershell window closes my program as well This is my first attempt at automating some of my development environment setup. I have the following powershell script:
& "C:\MAMP\MAMP.exe"
& "C:\Program Files\Microsoft VS Code\Code.exe"

I run it and it works fine, but when I close the powershell window it closes my VS Code window as well. MAMP stays open.
I'm sure this is a simple fix. Thanks!

A: Have you tried with Start-Process?
Start-Process "C:\Program Files\Microsoft VS Code\Code.exe"


text:
Q: migrar un campo de una tabla a otra sin que sea clave primaria Buenas, estoy diseñando una base de datos de venta.
Pero tengo un problema. Necesito que a la hora de insertar datos en mi tabla, se vea de la siguiente forma:
Tabla detalle_venta

Ahora, la id de mi tabla detalle_venta tiene que viajar hasta mi tabla venta como clave foranea:

El problema esta en que para insertar datos en mi tabla detalle_venta el id no tiene que repetirse, por que esta como clave primaria, y solo como clave primaria puedo mandarlo a la otra tabla. Agradecería cualquier sugerencia.

A: "id_det_venta" en la tabla "detalle_venta" es clave primaria y no puede tener repetidos (así que no comprendo que es "id" en el ejemplo que pones al principio).
"id_det_venta" en "venta" es clave foránea, puede repetirse tanto como sea necesario; lo que indicas con esa relación es que cada "venta" tiene un sólo y único "detalle_venta" relacionado.
Si lo que quieres es que cada "venta" pueda tener varios "detalle_venta" relacionados debes tener una tabla intermedia que guarde esa relación.
Algo como:
tabla "venta_detalleVenta"
id_venta int(11)
id_det_venta int(11)

siendo ambos campos (id_venta e id_det_venta) claves primarias en esa tabla.
Entonces, cada vez que quieras establecer la relación de una "venta" con un "detalle_venta" sólo tendrás que guardar ambas id en la tabla "venta_detalleVenta"; con tantos "detalle_venta" por "venta" como necesites.

A: La PK (id_det_venta) de tu tabla detalle_venta debe ser FK en la tabla venta. De ese modo, cada venta tiene un detalle (ya que la FK es la PK de la otra tabla). Esto te garantiza la unicidad. En realidad no lo mandas a la otra tabla, sino que desde la tabla ventas hacés referencia a la PK de la tabla detalle_venta que hace de FK.


text:
Q: Pause a CCMoveBy Cocos2d 2.0 ios im developing a game where i have time to finish the level, during wich i have a filling bar animation, on that particular animation im using CCMoveBy:
  self.animatedBar = [CCMoveBy actionWithDuration:time position: ccp(12, -20)];
  CCNode* animatedContainer = [self getChildByTag:1];
  [animatedContainer runAction:self.animatedBar];

is there any way to say something like [animatedBar pause] and [animatedBar resume] ?
Or the best bet is to put this into my game loop and pause it there? ( im doing a return if the BOOL paused is set to true ).
I will have more animations attached to this on the future ( not game core related, but just to make it more "shinny" ) so i want to avoid using:
  [animatedContainer pauseSchedulerAndActions];

A: There is no pause/resume method for action in cocos2d, so the first way - you can implement your own CCAction subclass, that will allow this, or just stop current action and recreate it instead of unpause.


text:
Q: uwsgi cannot find Flask application: (callable not found or import error) I am roughly following this deployment guide for Flask. When I launch my app through uwsgi, I receive the error:

*** Operational MODE: preforking ***
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***

It is the same issue as this other SO question, so it is a python path problem, but I still can't get my app to run. Here is my setup:
/home/btw/prod/
.... app.py
.... inits.py
.... templates/
.... wsgi.py
.... prod.ini
.... env/       <--- virtualenv dir

inits.py
# This initializes everything

from flask import Flask
#... other imports

app = Flask(__name__)
app.debug = False

# Flask-Migrate
migrate = Migrate(app,db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

app.py
# This holds the main application code and routes

from inits import *

@app.route('/doit')
def doit():
    return render_template('doit.html')

if __name__ == '__main__':
    manager.run()

prod.ini
[uwsgi]
module = wsgi

master = true
processes = 5

socket = prod.sock
chmod-socket = 660
vacuum = true

die-on-term = true

prod.conf (used to start the flask app):
description "uWSGI server instance configured to serve prod"

start on runlevel [2345]
stop on runlevel [!2345]

setuid btw
setgid www-data

env PATH=/home/btw/prod/env/bin
chdir /home/btw/prod
exec uwsgi --ini prod.ini

wsgi.py
from app import manager

if __name__ == '__main__':
    manager.run()

I also tried doing:
from prod import app

if __name__ == '__main__':
    manager.run()

But this complains about ImportError: No module named prod.
Can someone help me out with why uwsgi can't find my application?
EDIT:
I think I found the problem, but I dont know what the solution is. Calling manager.run() causes the application to not be found, but if I just use app.run() instead, bypassing Flask's manager, uwsgi successfully locates the application.
Why is that?

A: Okay, so after a few hours of exploring this mess, I figured it out!
When running uwsgi, app must be conflicting with some other internal module. I've changed my initialization to be application = Flask(__name__) and did from app import application. Now my application is being loaded correctly.


text:
Q: Page load timeout in Selenium Sometime my automated test fails because of page load timeout.
I wonder if the issue is not with the website but with my automated test script doing something to the page because:

*

*Even when I change the page load timeout to 30 sec to say 50, the frequency of the error seems to be about the same

*When I access to the website manually it never takes that long to load a page

*When I kill the automated test while loading the page for a while, it finishes loading and displays the page fine

*Sometime, I can see the page is still loading from the browser tab, but the contents of the page is fully displayed

Has anyone come across to this issue?
I am using:

*

*selenium-java : 2.53.1

*Chrome Driver: 2.30

*Selenide: 4.5

and I use webDriver.get(url); method to open an URL in the browser.
Here is the error trace-back:

org.openqa.selenium.TimeoutException: timeout
    (Session info: chrome=59.0.3071.86)
    (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
  Command duration or timeout: 50.81 seconds
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
      at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:316)
      at org.openqa.selenium.remote.RemoteWebDriver$$FastClassBySpringCGLIB$$589f8ff4.invoke()
      at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
      at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
      at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
      at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
      at org.openqa.selenium.remote.RemoteWebDriver$$EnhancerBySpringCGLIB$$c8c4bedf.get()

A: I faced same kind of issue due to chrome driver incompatibility with selenium.Try to update your chrome driver.

A: There is no issue with your code. I think you should try updating your Chrome driver to the latest version and see if that issue still come. Please let me know the update.


text:
Q: PHP mail sent before finish uploading the attachment I am making a PHP form which allow users to upload attachment and send it to my e-mail. I have been searching for quite a long time to make it.
And, finally, I found this. http://www.shotdev.com/php/php-mail/php-send-email-upload-form-attachment-file/. It works fine.
However, when I modify it myself (change the fields), something doesn't go well.
<?php

$location=$_POST['location'];
$name_ha=$_POST['name_ha'];
$name_person=$_POST['name_person'];
$email=$_POST['email'];
$date_sent=$_POST['date_sent'];
$date_completed=$_POST['date_completed'];
$date_received=$_POST['date_received'];

$to="admin@admin.com" . "$email";

$message="to";

//*** Uniqid Session ***//
$sid = md5(uniqid(time()));

$header = "";
$header .= "From: ".$_POST["name_ha"]."<".$_POST["email"].">\nReply-To: ".$_POST["email"]."";

$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$sid."\"\n\n";
$header .= "This is a multi-part message in MIME format.\n";

$header .= "--".$sid."\n";
$header .= "Content-type: text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$header .= $message."\n\n";

//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
    $FilesName = $_FILES["fileAttach"]["name"];
    $Content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
    $header .= "--".$sid."\n";
    $header .= "Content-Type: application/octet-eam; name=\"".$FilesName."\"\n";
    $header .= "Content-Transfer-Encoding: base64\n";
    $header .= "Content-Disposition: attachment; filename=\"".$FilesName."\"\n\n";
    $header .= $Content."\n\n";
}

$flgSend = @mail($to,"A new file for you!",null,$header);  // @ = No Show Error //

if ($flgSend)
{
    echo "Mail sent.";
}

?>

The files I downloaded from shotdev.com and the one I modified are being hosted on the same server and under the same folder.
But, for the one I have modified, the email is sent before the attachment is uploaded (~ 45% of the uploading process) if the file size is greater than 1MB. The email I received, there is no attachment and no information of sender ($name_ha).
On the other hand, for the files downloaded on shotdev.com, the email will only be sent after the attachment is uploaded completely no matter how big it is.
Is there any error of the script, or something is missing, causing such an occurrence? Your time and help is much appreciated.

A: First, in code that you showed as example you have error on this line:
$to="admin@admin.com" . "$email";

Change it to:
$to="admin@admin.com, " . "$email";

*

*Notice comma that you are missing... It needed to be there for every new receivers email you want to add on that particular way...

Also I have tested code on my server, everything works well.
I have 100 mbps upload and tried file that is 4.5 MB and it works.
So maybe there is a problem with your upload speed and allowed execution time of php script that you are calling to send this email.
Try to add the following just after <?php in php file that you setted in HTML form as action="something.php":
set_time_limit(0);

That means that there is no liimt in execution time of script, change 0 to desired number of seconds...
Also remove @ before @mail() function if there are errors you need to see them, hiding them will not do any good for you.
EDIT:
I have altered your code so that it does check if, firstly if there is file, if not sends mail without attachment. And if there is file it checks if it is encoded to base64 and splited and in that case it send the mail with attachment...
<?php

$location=$_POST['location'];
$name_ha=$_POST['name_ha'];
$name_person=$_POST['name_person'];
$email=$_POST['email'];
$date_sent=$_POST['date_sent'];
$date_completed=$_POST['date_completed'];
$date_received=$_POST['date_received'];
$FilesName = $_FILES["fileAttach"]["name"];

$to = "admin@mail.com," . "$email";

$message = "to";

$sid = md5(uniqid(time()));

$header = "";
$header .= "From: ".$_POST["name_ha"]."<".$_POST["email"].">\nReply-To: ".$_POST["email"]."";

$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$sid."\"\n\n";
$header .= "This is a multi-part message in MIME format.\n";

$header .= "--".$sid."\n";
$header .= "Content-type: text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$header .= $message."\n\n";

if($_FILES["fileAttach"]["name"] != "") {

    $Content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
    $header .= "--".$sid."\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$FilesName."\"\n";
    $header .= "Content-Transfer-Encoding: base64\n";
    $header .= "Content-Disposition: attachment; filename=\"".$FilesName."\"\n\n";
    $header .= $Content."\n\n";

}

if (strlen($FilesName) > 0) {

    if ($Content) {

        $flgSend = mail($to,"Here is that file",null,$header);

    }
    else {

        echo "problem with file...";

    }

}
else {

    $flgSend = mail($to,"Here is that file",null,$header);

}

if ($flgSend) {

    echo "Mail sent.";

}

?>

HERE IS HTML FOR IT:

<form method="post" action="sender.php" enctype="multipart/form-data" >
    location: <input type="text" name="location" />

    name_ha: <input type="text" name="name_ha" />

    name_person: <input type="text" name="name_person" />

    email: <input type="text" name="email" />

    date_sent: <input type="text" name="date_sent" />

    date_completed: <input type="text" name="date_completed" />

    date_received: <input type="text" name="date_received" />

    file: <input type="file" name="fileAttach" />

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


text:
Q: place Processing language on top of DataTable Is there a way to put the "Processing..." language on the top of the DataTable object instead of in the middle vertically? If I have a long table, it is hidden off the page because its default position is in the middle.
$('#example').dataTable( {
  "language": {
      "processing": "DataTables is currently busy"
  }
} );

A: Use the following CSS rule and adjust top as you wish.
div.dataTables_wrapper div.dataTables_processing {
   top: 5%;
}

See this jsFiddle for demonstration.


text:
Q: Android. ldpi, mdpi, hdpi clarification So, in regards to this stackoverflow accepted answer: How do I convert ppi into dpi for Android images?
So, ok, i make each background image the dimensions that that guy specifies in the answer.
BUT, if i define the other ImageViews (smaller ones), that are placed on the screen, in relation to the sizes defined above (e.g. let's say an ImageView has dimensions 20x20 for the hdpi devices, if i calculate this dimensions for the ldpi devices, the image would have to be 7x7 pixels, which is terribly small) then the ldpi devices won't be able to see anything on the screen :) Or will they? Am i doing it right, or not?
I'm terribly confused. Can someone clarify this for me please? :)

A: The resolutions mentioned in the other question will always fill the screen, but you should provide different layout files for each screen size to stay dpi independent (if you so wish).
Look at the example from the dev page
Also, it always helps to fire up the appropriate simulator (middle size with mdpi, smallest size with ldpi and biggest size with hdpi, depending on what devices you are planning to support) and try your layouts out.

A: Your images should be at least the size which can be easily viewable, or even clickable for the user on his/her devices.
The guidelines are for specific images, like launcher icons, or menu items, and not necessarily for any images you use in your app. For these kind of images, you are the best judge of specifying the image sizes and resolutions.
You could well have those images as only mdpi, and supply an hdpi version, so that it atleast has a higher resolution image for hdpi and xdpi devices.


text:
Q: How to force GetTextExtentPoint32 to take into account kerning? I've got an application which is using GDI+ and calling DrawTextExW to draw text to the screen. I'm also trying to position a flashing carat at the edit point. I'm calculating the position of the carat using GetTextExtentPoint32W. This works perfectly with monospaced fonts, but using something like Helvetica, if I encounter a character pair which has kerning (i.e. "Yo" "To", etc.) the values I get back from GetTextExtentPoint32W are off, and continue to get farther and farther off the more of these characters I include. As you can see in the screenshot below the carat and the highlighted text are positioned as if there were no kerning:

I checked the documentation and saw this:

Because some devices kern characters, the sum of the extents of the characters in a string may not be equal to the extent of the string.

Unfortunately that doesn't really clear things up. Is it saying that if I were to sum up the extents of each individual character I would get a different number than what GetTextExtentPoint32W returns, or that GetTextExtentPoint32W is summing up the characters and so you shouldn't expect it to be accurate to what's drawn on the screen? What constitutes a "device" in this context?
At this point I'd be happy to either disable kerning in DrawTextExW or figure out how to make GetTextExtentPoint32W consider kerning if that's possible.


text:
Q: Charles Web Debugging Proxy rewrite not working Here is the response:
{"xxx", "yyy", "zzz":"abc,def"}

(abc,def is not a constant string, every time it will change.)
For example, I want to rewrite "abc,def" so I use this Regex expression "zzz":"(*)+" and rewrite as "zzz":"rewrote!", but I got fail, Charles won't regex it, I think the Regex expression may wrong. If I want to rewrite it, what should be put in the Regex expression?

A: Considering your example "zzz":"(*)+", here (*)+ doesn't mean anything to your example.
You can replace it with "[^"]+" to match anything between quotes except the quote itself. For example:
"zzz":"[^"]+"
+ for at least a character in it. If you replace + with * it will be zero or more character.


text:
Q: Possible to reduce number of queries from 5 to 1? I have a gallery of "Leaders" on my site, where the top users in 5 different categories are selected by a DESC LIMIT 1; the gallery is generated with 5 separate INNER JOIN between the stats and login tables, but all the SELECT clauses are identical:
$cat1wins="SELECT stats.login_id, stats.cat1wins, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id ORDER by
stats.cat1wins DESC LIMIT 1";

$cat2wins="SELECT stats.login_id, stats.cat2wins, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id ORDER by
stats.cat2wins DESC LIMIT 1";

$cat3wins="SELECT stats.login_id, stats.cat3wins, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id ORDER by
stats.cat3wins DESC LIMIT 1";

$cat4wins="SELECT stats.login_id, stats.cat4wins, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id ORDER by
stats.cat4wins DESC LIMIT 1";

$cat5wins="SELECT stats.login_id, stats.cat5wins, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id ORDER by
stats.cat5wins DESC LIMIT 1";

For each category, a WHILE loop extracts the proper table cell (shown here with cat1)
$result1 = mysqli_query($con,$cat1wins);
WHILE ($Category1Wins = mysqli_fetch_assoc($result1)) {
$Cat1User = $Category1Wins['user'];
$Cat1Statement = $Category1Wins['statement'];
echo "code"; //etc
}

I imagine there must be a better way to do this; I imagine I could start like this:
$catAllwins="SELECT stats.cat1wins, stats.login_id, login.user, login.picture,
login.statement, SELECT stats.cat2wins, stats.login_id, login.user, login.picture,
login.statement,.....SELECT stats.cat5wins, stats.login_id, login.user, login.picture,
login.statement FROM stats INNER JOIN login ON stats.login_id=login.login_id";

and then use a WHILE loop on the results of each SELECT statement within $catAllwins to generate 5 separate arrays that can then be sorted with a natsort. However, I am not sure how to extract the proper SELECT statements. I was thinking I could say something like:
$catAllwins="SELECT stats.cat1wins, stats.login_id, login.user, login.picture,
login.statement AS 'array1', SELECT stats.cat2wins, stats.login_id, login.user,
login.picture, login.statement AS 'array2',.....SELECT stats.cat5wins, stats.login_id,
login.user, login.picture, login.statement AS 'array5' FROM stats INNER JOIN login ON
stats.login_id=login.login_id";

$resultAll = mysqli_query($con, $catAllwins)
$Cat1WinsArray = $resultAll['array1'];
$Cat2WinsArray = $resultAll['array2'];
$Cat3WinsArray = $resultAll['array3'];
$Cat4WinsArray = $resultAll['array4'];
$Cat5WinsArray = $resultAll['array5'];

then sort the arrays with natsort (one example shown)
$SortedCat1WinsArray = natsort($Cat1WinsArray);

then add array_reverse for descending order:
$DescSortedCat1WinsArray = array_reverse($SortedCat1WinsArray);

then WHILE this array to extract each component I need (e.g., $row['picture'], $row['login_id'], etc.). Does this sound remotely plausible? I would appreciate any feedback! Is there an easier way?

A: You can just UNION the individual select statements together and apply a sort to the resulting union.  Here is an example:
(SELECT stats.login_id, stats.cat1wins, login.user, login.picture, login.statement
FROM stats INNER JOIN login ON stats.login_id=login.login_id
ORDER by stats.cat1wins DESC LIMIT 1)
UNION
(SELECT stats.login_id, stats.cat2wins, login.user, login.picture, login.statement
FROM stats INNER JOIN login ON stats.login_id=login.login_id
ORDER by stats.cat2wins DESC LIMIT 1)
UNION
(SELECT stats.login_id, stats.cat3wins, login.user, login.picture, login.statement
FROM stats INNER JOIN login ON stats.login_id=login.login_id
ORDER by stats.cat3wins DESC LIMIT 1)
UNION
(SELECT stats.login_id, stats.cat4wins, login.user, login.picture, login.statement
FROM stats INNER JOIN login ON stats.login_id=login.login_id
ORDER by stats.cat4wins DESC LIMIT 1)
UNION
(SELECT stats.login_id, stats.cat5wins, login.user, login.picture, login.statement
FROM stats INNER JOIN login ON stats.login_id=login.login_id
ORDER by stats.cat5wins DESC LIMIT 1)
ORDER BY /* Whatever you want to sort by. Wasn't clear in the questoin */

A: Sorting by five different variables is expensive.  You might find the following approach to be more efficient:
select l.login_id,
       (case when s.cat1wins = smax.max_cat1wins then 'cat1'
             when s.cat2wins = smax.max_cat2wins then 'cat2'
             when s.cat3wins = smax.max_cat3wins then 'cat3'
             when s.cat4wins = smax.max_cat4wins then 'cat4'
             when s.cat5wins = smax.max_cat5wins then 'cat5'
         end) as which,
       (case when s.cat1wins = smax.max_cat1wins then s.cat1wins
             when s.cat2wins = smax.max_cat2wins then s.cat2wins
             when s.cat3wins = smax.max_cat3wins then s.cat3wins
             when s.cat4wins = smax.max_cat4wins then s.cat4wins
             when s.cat5wins = smax.max_cat5wins then s.cat5wins
         end) as numwins,
       l.user, l.picture, l.statement,
from stats s inner join
     (select max(stats.cat1wins) as max_cat1wins,
             max(stats.cat2wins) as max_cat2wins,
             max(stats.cat3wins) as max_cat3wins,
             max(stats.cat4wins) as max_cat4wins,
             max(stats.cat5wins) as max_cat5wins
      from stats
     ) smax
     on s.cat1wins = smax.max_cat1wins or
        s.cat2wins = smax.max_cat2wins or
        s.cat3wins = smax.max_cat3wins or
        s.cat4wins = smax.max_cat4wins or
        s.cat5wins = smax.max_cat5wins join
     login l
     on s.login_id = l.login_id;

There are two important differences in doing it this way, compared to your original five queries.  First, if someone is tops in two or more categories, they only appear once here.  Second, if mutliple people are tied for the best in one category, all are included.

A: Updated
getting userid for each max categories
What about this? this has no GROUP BY and needs just 1 full scan.
    SELECT
        IF(cat1wins >= @mxc1, @mxu1 := login_id, @mxu1) AS userid1,
        IF(cat1wins >= @mxc1, @mxc1 := cat1wins, @mxc1) AS max_cat1wins,

        IF(cat2wins >= @mxc2, @mxu2 := login_id, @mxu2) AS userid2,
        IF(cat2wins >= @mxc2, @mxc2 := cat2wins, @mxc2) AS max_cat2wins,

        IF(cat3wins >= @mxc3, @mxu3 := login_id, @mxu3) AS userid3,
        IF(cat3wins >= @mxc3, @mxc3 := cat3wins, @mxc3) AS max_cat3wins,

        IF(cat4wins >= @mxc4, @mxu4 := login_id, @mxu4) AS userid4,
        IF(cat4wins >= @mxc4, @mxc4 := cat4wins, @mxc4) AS max_cat4wins,

        IF(cat5wins >= @mxc5, @mxu5 := login_id, @mxu5) AS userid5,
        IF(cat5wins >= @mxc5, @mxc5 := cat5wins, @mxc5) AS max_cat5wins
    FROM stats, (
        SELECT
          @mxc1 := 0, @mxc2 := 0, @mxc3 := 0, @mxc4 := 0, @mxc5 := 0,
          @mxu1 := 0, @mxu2 := 0, @mxu3 := 0, @mxu4 := 0, @mxu5 := 0
    ) x;

finally we get login information using join with login table
Please note that following query returns 1~5 records. (1 for all max user are same. 5 for each max user are diffrent)
SELECT
    y.*, login.login_id, login.user, login.picture, login.statement,
    IF(y.userid1 = login.login_id, max_cat1wins, NULL) AS max1,
    IF(y.userid2 = login.login_id, max_cat2wins, NULL) AS max2,
    IF(y.userid3 = login.login_id, max_cat3wins, NULL) AS max3,
    IF(y.userid4 = login.login_id, max_cat4wins, NULL) AS max4,
    IF(y.userid5 = login.login_id, max_cat5wins, NULL) AS max5
FROM
(
    SELECT
        IF(cat1wins >= @mxc1, @mxu1 := login_id, @mxu1) AS userid1,
        IF(cat1wins >= @mxc1, @mxc1 := cat1wins, @mxc1) AS max_cat1wins,

        IF(cat2wins >= @mxc2, @mxu2 := login_id, @mxu2) AS userid2,
        IF(cat2wins >= @mxc2, @mxc2 := cat2wins, @mxc2) AS max_cat2wins,

        IF(cat3wins >= @mxc3, @mxu3 := login_id, @mxu3) AS userid3,
        IF(cat3wins >= @mxc3, @mxc3 := cat3wins, @mxc3) AS max_cat3wins,

        IF(cat4wins >= @mxc4, @mxu4 := login_id, @mxu4) AS userid4,
        IF(cat4wins >= @mxc4, @mxc4 := cat4wins, @mxc4) AS max_cat4wins,

        IF(cat5wins >= @mxc5, @mxu5 := login_id, @mxu5) AS userid5,
        IF(cat5wins >= @mxc5, @mxc5 := cat5wins, @mxc5) AS max_cat5wins
    FROM stats, (
        SELECT
          @mxc1 := 0, @mxc2 := 0, @mxc3 := 0, @mxc4 := 0, @mxc5 := 0,
          @mxu1 := 0, @mxu2 := 0, @mxu3 := 0, @mxu4 := 0, @mxu5 := 0
    ) x
) y INNER JOIN login
WHERE login.login_id IN (userid1, userid2, userid3, userid4, userid5);


text:
Q: express-validator - Customize errors output I am using express validator to validate the json body.
router
router.post('/login', [
  body('mobno')
    .exists().withMessage('Required')
    .isLength({ min: 10, max: 12 }).withMessage('10-12 characters')
    .isNumeric().withMessage('Numeric'),
  body('password')
    .not().isEmpty().withMessage('Password is required'),
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.json({ errors: errors.array(), success: false, msg: 'Check Parameters' });
  }
 // do stuff and respond
});

response
{
  "errors": [
    {
      "value": "998716***658()",
      "msg": "10-12 characters",
      "param": "mobno",
      "location": "body"
    },
    {
      "value": "998716***658()",
      "msg": "Numeric",
      "param": "mobno",
      "location": "body"
    }
  ],
  "success": false,
  "msg": "Check Parameters"
}

In the frontend, I am using Vuetify, hence I need the resonse to be in a format which can easily be consumed by the frontend.
Expected output
{
  "errors": {
    "mobno": [
      "10-12 characters",
      "Numeric"
    ]
  },
  "success": false,
  "msg": "Check Parameters"
}

Question

*

*Is there any option/function which I can hook into which will format the errors in the way I want it.

*I am thinking to use Lodash for this transformation, any suggestions on how can this be achieved?

A: You can use a lodash chain to group the errors by the param, and then map the items in each group to the msg property. Then you can combine the errors object with the previous result using object spread.

const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}

const errors = _(data.errors)
  .groupBy('param')
  .mapValues(group => _.map(group, 'msg'))
  .value()

const result = {
  ...data,
  errors
}

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>

And a pipeline approach using lodash/fp and _.flow():

const { flow, groupBy, mapValues, map } = _

const transform = flow(
  groupBy('param'),
  mapValues(map('msg'))
)

const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}

const result = {
  ...data,
  errors: transform(data.errors)
}

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>


text:
Q: How to sort localStorage by key For some reason localStorage don't sort by the order you add data to it.
I have stored JS date milliseconds as keys in localStorage.
How can i output the key and the value from localStorage sorted by key asc?
Do i need to create another VAR from localStorage and then sort the VAR?

A: How about saving the times as a single object using JSON.stringify(yourObject)
Something like
const jsTimes = localStorage.getItem("times");
const times = jsTimes ? JSON.parse(jsTimes) : {};
...
times[new Date().getTime()] = "Now is the time";
localStorage.setItem("times",JSON.stringify(times));

Alternatively if you must
const times = Object.keys(localStorage)
  .filter(key => key.length === 13 && !isNaN(new Date(key))
  .map(key => key)
  .sort() // alphabetic sort is ok on a timestamp
  .map(key => ({[key]: localStorage[key] }));


text:
Q: Creating Orientation Sensor for Android Application I am trying to make an orientation sensor for an android application, but my code still doesn't seem to work. I looked on the android application website for help, but still can't get any results. My code doesn't yield an error, it just doesn't display/collect the results.
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        //Orientation sensor
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
            mGravity = event.values;
        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
            mGeomagnetic = event.values;
        if (mGravity != null && mGeomagnetic != null) {
            float R[] = new float[9];
            float I[] = new float[9];
            boolean success = SensorManager.getRotationMatrix(R, I,    mGravity, mGeomagnetic);
            if (success) {
                float orientation2[] = new float[3];
                SensorManager.getOrientation(R, orientation2);

                String orientationText = "Orientation: \n -Z: " + df.format(orientation2[0]) +"\n-X: " + df.format(orientation2[1]) + "\nY: " + df.format(orientation2[2]);
                orientation.setText(orientationText);

                Log.d(TAG, "Gyroscope:" + orientation2[0] + "," + orientation2[1] + "," + orientation2[2]);

                MagnetometerData mData = new MagnetometerData( orientation2[0], orientation2[1], orientation2[2]) ;
                instance.addMagnetometerData( mData );
            }
        }


text:
Q: Webcam names are confusing My laptop has two webcams, one is the integrated webcam and another is a USB webcam PnP webcam. They both show up when listed, but they have the same name: Video Capture 5. I was hoping to be able to write some code to identify the webcams based on their name.
v4l2-ctl --list-devices
Video Capture 5 (usb-0000:00:14.0-3.1.1.1):
    /dev/video2
    /dev/video3

Video Capture 5 (usb-0000:00:14.0-4):
    /dev/video0
    /dev/video1

Looking at other posts where people run this command, the result is often a much better more user friendly name


text:
Q: luatex: token.set_macro() issue In the MWE below, I first define \command(A|B|C|D) which expands to \cmd(A|B|C|D) which all expand to THE COMMAND. None of these use \edef, so I should have no issue with defining \commandX first. But what I do notice, is if I use the lua function token.set_macro to define \commandB -> \cmdB first then \cmdB -> THE COMMAND, the results are not identical to and the \ seems to be ignored. However, if I swap the order, it works as expected. Perhaps this is a bug? Please note, I also tested this in a separate .lua file, this is not a luacode issue.
I expect to see THE COMMAND four times. The result I get is:

\documentclass{article}
\usepackage{luacode}
\begin{document}

% \edef\commandA{\cmdE} % error, because \cmd is not defined yet
% \edef\cmdE{THE COMMAND} %

\gdef\commandA{\cmdA}
\gdef\cmdA{THE COMMAND}

\begin{luacode*}
  -- the problem: the \\ seems to be ignored
  token.set_macro('commandB', '\\cmdB', 'global')
  token.set_macro('cmdB', 'THE COMMAND', 'global')

  -- but if I do define \cmdC first, it accepts it as I like
  token.set_macro('cmdC', 'THE COMMAND', 'global')
  token.set_macro('commandC', '\\cmdC', 'global')

  -- should I forego token.set_macro and just do this?
  tex.print('\\gdef\\commandD{\\cmdD}')
  tex.print('\\gdef\\cmdD{THE COMMAND}')
\end{luacode*}

\commandA\\
\commandB\\
\commandC\\
\commandD

% https://www.pragma-ade.com/general/manuals/luatex.pdf
% manual page 217 says "the results are like \gdef

\end{document}

A: There is a warning in the luatex manual somewhere about this. token.set_macro really needs the token to be already in the hash table.
If you split up your code
\documentclass{article}
\usepackage{luacode}
\begin{document}

% \edef\commandA{\cmdE} % error, because \cmd is not defined yet
% \edef\cmdE{THE COMMAND} %

\gdef\commandA{\cmdA}
\gdef\cmdA{THE COMMAND}

\begin{luacode*}
  -- the problem: the \\ seems to be ignored
  token.set_macro('commandB', '\\cmdB', 'global')
\end{luacode*}

\show\commandB

then it reports
> \commandB=macro:
->BADcmdB.
l.16 \show\commandB

?

as \cmdB did not refer to an entry in the hash table of csnames.
If you do more or less anything earlier using  that \cmdB csname then it works as you expect:
\documentclass{article}
\usepackage{luacode}
\begin{document}

% \edef\commandA{\cmdE} % error, because \cmd is not defined yet
% \edef\cmdE{THE COMMAND} %

\gdef\commandA{\cmdA}
\gdef\cmdA{THE COMMAND}
\def\wibble{\cmdB}

\begin{luacode*}
  -- the problem: the \\ seems to be ignored
  token.set_macro('commandB', '\\cmdB', 'global')
\end{luacode*}

\show\commandB

makes
> \commandB=macro:
->\cmdB .
l.17 \show\commandB

?


text:
Q: Android: Automatic update of my app I am beginner android developer.I wrote some simple app,witch adding to the calendar informations about calls.Now i want to add automatic update,if somebody call me,it automaticly update calendar.
Source code:
 DateFormat date = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        String[] projection = new String[] { "_id", "name" };
        ContentValues event = new ContentValues();
        long currentTime = System.currentTimeMillis();

        Cursor callCur = getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");
        Uri calendarsUri = Uri.parse("content://com.android.calendar/calendars");
        Cursor managedCursor = managedQuery(calendarsUri, projection, "selected=1", null, null);

        int typeOfCall = 0;
        String callCachedName = null;
        String callName = null;
        int duration = 0;
        String compareNumbers = null;

        while(callCur.moveToNext()){

        compareNumbers = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));

        int callDateIn = callCur.getColumnIndexOrThrow(android.provider.CallLog.Calls.DATE);
        long callDateLong = new Long(callCur.getLong(callDateIn));

        event.put("calendar_id", 2);

        typeOfCall = callCur.getInt(callCur.getColumnIndex(android.provider.CallLog.Calls.TYPE));
        Log.d(TAG, "Type of Call: " + typeOfCall);

        if (typeOfCall == 1){
            duration = callCur.getInt(callCur.getColumnIndex(android.provider.CallLog.Calls.DURATION));
            Log.d(TAG, "Duration: " + duration);

            if (duration == 0){
                event.put("description", "Number wasn't avaibled");
                }
            else{
                event.put("description", "Duration of call was: " + duration);
            }
            if (compareNumbers == null){
                callName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
                Log.d(TAG, "callName: " + callName);
                event.put("title", "Called to: " + callName);
            }
            else {
                callCachedName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
                Log.d(TAG, "cachedName: " + callCachedName);
                event.put("title", "Called to: " + callCachedName);
            }

        }
        if (typeOfCall == 2){
            duration = callCur.getInt(callCur.getColumnIndex(android.provider.CallLog.Calls.DURATION));
            Log.d(TAG, "Duration: " + duration);
            if (duration == 0){
                event.put("description", "Call was interupted");
                }
            else{
                event.put("description", "Duration of call was: " + duration);
            }
            if (compareNumbers == null){
                callName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
                Log.d(TAG, "callName: " + callName);
                event.put("title", "Call from : " + callName);
            }
            else {
                callCachedName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
                Log.d(TAG, "cachedName: " + callCachedName);
                event.put("title", "Call from : " + callCachedName);
            }

        }
        if (typeOfCall == 3){
             if (compareNumbers == null){
                callName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
                Log.d(TAG, "callName: " + callName);
                event.put("title", "Called to: " + callName);
             }
             else {
                callCachedName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
                Log.d(TAG, "cachedName: " + callCachedName);
                event.put("title", "Called to: " + callCachedName);
             }
             if (compareNumbers == null){
                callName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
                Log.d(TAG, "callName: " + callName);
                event.put("title", "Call from : " + callName);
             }
             else {
                callCachedName = callCur.getString(callCur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
                Log.d(TAG, "cachedName: " + callCachedName);
                event.put("title", "Call from : " + callCachedName);
             }

        }

        //event.put("eventLocation", "New Yorks");
        event.put("dtstart", callDateLong );

       Uri eventsUri = Uri.parse("content://com.android.calendar/events");
       Uri calUri = getContentResolver().insert(eventsUri, event);

        }
    }
}

A: Extend BroadcastReceiver and add an entry in your AndroidManifest.xml with an intent-filter of ACTION_ANSWER.  You can then call your calender update method from the onReceive method of your myBroadcastReceiver class.


text:
Q: How to get text between dynamic created lines So i try to get the text between dynamic created lines.
Example string,
KOR/4
1/FI222/24NOV/DOK
PLO
134-57623905WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
/STACKI
89a7/SOMET
134-12389783WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/BLA
2736/2832
134-34389783WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/DYN
asdjadhjahd
134-57627905WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/STACKI
SSR/TROPPER5
FINAL

So i tried with .match() and exec().
I couldn't figure out a way to get the textual between the numbers in array
REQUIRED OUTPUT
// OUTPUT EXAMPLE

[0][
    134-57623905WINLOSE/WINNER/ROBO
    /TRY
    DIM/K0/CMT44-30-30/5
    /STACKI
    89a7/SOMET
],
[2][
    134-12389783WINLOSE/WINNER/ROBO
    /TRY
    DIM/K0/CMT44-30-30/5
    DIM/K0/CMT44-30-30/5
    DIM/K0/CMT44-30-30/5
    DIM/K0/CMT44-30-30/5
    DIM/K0/CMT44-30-30/5
    /BLA
    2736/2832
],
[3][
    134-34389783WINLOSE/WINNER/ROBO
    /TRY
    DIM/K0/CMT44-30-30/5
    DIM/K0/CMT44-30-30/5
    /DYN
    asdjadhjahd
]

etc..

A: You can use regex to get target part of string.
var match = str.match(/\d{3}-.*?(?=\d{3}-|FINAL)/sg);

The regex select any part of string that start with digit with length 3 and end with digit with length 3

var str = document.getElementById("str").innerHTML;
var match = str.match(/\d{3}-.*?(?=\d{3}-|FINAL)/sg);
console.log(match.join('\n\n'));

KOR/4
1/FI222/24NOV/DOK
PLO
134-57623905WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
/STACKI
89a7/SOMET
134-12389783WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/BLA
2736/2832
134-34389783WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/DYN
asdjadhjahd
134-57627905WINLOSE/WINNER/ROBO
/TRY
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
DIM/K0/CMT44-30-30/5
/STACKI
SSR/TROPPER5
FINAL


text:
Q: What is the difference between "Local" and "LocalLow" folders?
Possible Duplicate:
Why are there directories called Local, LocalLow, and Roaming under \Users\<username>?

I know what Local and Roaming are for.  But what's the difference between Local and LocalLow?   I LocalLow really another form of Roaming, but uses only a small bandwidth to slowly update files across the domain for the user?


text:
Q: Build dictionary from array using Linq I have a class A containing an array of key/values pairs described by class B. One of the key is called "name". I want to use Linq to build a Dictionary<string, Dictionary<string, string>> where key of first dictionary is the attribute called "name" in the B array and the value is a second dictionary that contains the key/value pairs of B.
public class A
{
    public int a;
    public B[] b;
}

public class B
{
    public string key;
    public string value;
}

A[] a = new A[]
{
    new A { a = 1, b = new B[] { new B { key = "name", value = "n1"}, new B { key = "test", value = "t1" } }, },
    new A { a = 2, b = new B[] { new B { key = "name", value = "n2"}, new B { key = "test", value = "t2" } }, },
};

So in fact I would like to build the following dictionary using Linq on array "a":
Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>()
{
    { "n1",  new Dictionary<string, string>() { { "name", "n1" }, { "test", "t1" } } },
    { "n2",  new Dictionary<string, string>() { { "name", "n2" }, { "test", "t2" } } },
};

A: It should be:
var dict = a.ToDictionary(
    x => x.b[0].value,
    y => y.b.ToDictionary(z => z.key, z => z.value)
);

The only "fun" part of this LINQ expression is that I had to use up to z parameters (x, y, z)... It took me three compilations to get it right (I always name the parameters x)
Revised for comment:
var dict = a.ToDictionary(
    x => x.b.First(y => y.key == "name").value,
    y => y.b.ToDictionary(z => z.key, z => z.value)
);


text:
Q: update data in existing row in mysql database I have a table called pack_details with 4 columns. I'm trying to insert new data into an existing table. Can somebody tell me what's wrong with my codes and why i have a parse error?
$sql_query = "UPDATE pack_details SET $delivery_date = $_POST["delivery_date"], $delivery_time = $_POST["delivery_time"]
WHERE $delivery_building = $_POST["delivery_building"]
AND $delivery_room = $_POST["delivery_room"]";

A: Try any from below options:
 $sql_query = "UPDATE pack_details SET $delivery_date = '{$_POST['delivery_date']}', $delivery_time = '{$_POST['delivery_time']}' WHERE $delivery_building = '{$_POST['delivery_building']}' AND $delivery_room = '{$_POST['delivery_room']}'";

or
 $sql_query = "UPDATE pack_details SET delivery_date = '".$_POST["delivery_date"]."', delivery_time = '".$_POST["delivery_time"]."' WHERE delivery_building = '".$_POST["delivery_building"]."' AND delivery_room = '".$_POST["delivery_room"]."'";

Note: If field name doesn't contain $, remove $ from field name in query. For eg. "$delivery_date" should be "delivery_date"
Suggestion: Instead of using string concatenation for building, You should use bind parameters to pass value to query. It helps to prevent SQL injection as well as code look well.


text:
Q: ggplot in Shiny r does not show I am trying to create a dynamic plot in R Shiny but the plot does not show in the Dashboard.
I have the following test data which I will upload in the shiny app:
Region.1=c( 375.00,375.00,370.00,350.00,350.00,305.00,300.00,250.00,245.00,240.00,235.00,225.00,215.00,200.00,100.00,100.00,100.00,100.00,100.00,100.00)
Region.2 =c(0.00,0.00,0.00,0.00,0.00,200.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,20.00,500.00,235.00,0.00)
Region.3 =c(100000.00,76000.00,60000.00,50000.00,50000.00,30000.00,30000.00,26000.00,19000.00,11000.00,10000.00,8000.00,7000.00,5000.00,4070.00,4000.00,3660.00,2585.00,2550.00,250.00)
Type=c("B","F","F","B","B","A","A","F","F","B","A","B","F","B","F","F","A","A","F","B")
data <- data.frame("Region.1"=Region.1, "Region.2"=Region.2, "Region.3"=Region.3, "Type"=Type)

My Script for Shiny looks like this (simplified code)
server.R
function(input, output,session) {

  myData <- reactive({
    req(input$file)
    inFile <- input$file
    if(is.null(inFile)){return(NULL)}
    read.csv(inFile$datapath, header = TRUE, sep = input$sep,
             quote = '""')

  })

  df<-reactive({

    df<-myData()
    dfType <- df[ , grepl( "Type" , names( df ) ) ]
    dfRegion<-df[ , grepl( "Region" , names( df ) ) ]

    df4<-cbind(dfType, dfRegion)
    colnames(df4)[which(names(df4) == "dfType")] <- "Type"
    colnames(df4)[which(names(df4) == "dfRegion")] <- "Region"
    df4[df4==""] <- NA
    df4 <- na.omit(df4)
    return(df4)
  })

  df.datasets <- reactive({
      df<-df()
      df<- melt(df,id.vars=c("Type"),
                measure.vars=c("Region.1", "Region.2", "Region.3"))
      test<-aggregate(df$value, by=list(Region=df$variable, Type=df$Type), FUN=sum)
      test<-test %>% group_by(Region) %>% transmute(Type, percent = (x/sum(x))*100)
      test$percent<-round(test$percent, digits = 0)
      test[test==0] <- NA
      test<-test[complete.cases(test),]

  })

  output$plot1<-renderPlot({
    blank_theme <- theme_minimal()+
      theme(
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.border = element_blank(),
        panel.grid=element_blank(),
        axis.ticks = element_blank(),
        plot.title=element_text(size=14, face="bold")
      )

    test<-df.datasets()
    levels(test$"Region")[levels(test$"Region") %in% c("Region.1")] <- "Region 1"
    levels(test$"Region")[levels(test$"Region") %in% c("Region.2")] <- "Region 2"
    levels(test$"Region")[levels(test$"Region") %in% c("Region.3")] <- "Region 3"
    levels(test$"Region")[levels(test$"Region") %in% c("Region.4")] <- "Region 4"

    p<-ggplot(test,
              aes(x =" ", y = percent, fill = Type))+
      geom_bar(width = 1, stat = "identity",position="fill", color="grey35")+
      coord_polar("y")+
      facet_grid(.~Region)+
      geom_text(aes( label= paste(percent, "%")) ,
                position=position_fill(0.5),  size=4.5)+
                 theme(axis.text.x=element_blank(),
                       strip.text.x = element_text(size=15, color="black", face="bold"),
                       strip.text.y = element_text(size=15, color="black", face="bold"),
                       legend.text = element_text(size=15),
                       legend.title = element_text(size=15, face="bold"),
                       plot.title = element_text(hjust = 0.5, size = 25),
                       axis.text=element_text(size=10))
      })
}

my ui.R
myData <- NULL
sidebar <- dashboardSidebar(
  sidebarMenu(
    fileInput('file', 'Upload File (.csv | .txt)',
              accept=c('text/csv',
                       'text/comma-separated-values,text/plain',
                       '.csv')),
    radioButtons('sep', 'File Type',
                 c(CSV=';',
                   Text='\t'))
    #actionButton("goButton", "  Legenda", icon = icon("play-circle"))

  )
)

dashboardPage(
  dashboardHeader(title = "Overview"),

  sidebar,
  dashboardBody(tags$style("image {max-width: 100%; width: 100%; height: auto}"),
                fluidRow(
                  tabBox(
                    title = " ",
                    # The id lets us use input$tabset1 on the server to find the current tab
                    id = "tabset1",
                    height = "1200px", width = "1000px"
                    ,
                    tabPanel( "Plots",
                              column(12,
                                     plotOutput("plot1"))

                  )

                )
  )))

I tried to strip down my code to detect the error but I can't find it. When I run the code outside of Shiny, the plot does show like it suppose to:

I Also don't get any error message. So I think that the plot is working but somehow it doesn't show. I tried modifying the size of the column but that didn't work..
I would like a result like this:

Anybody got an idea? I would really appreciate it, thank you :)

A: It looks like you assigned the plot to p then never called p in the renderPlot block, what happens if you just add p at the end of the block?


text:
Q: Is there a way to clone objects in Dart? I went through a few questions about this on Stackoverflow but nothing made sense to me. What's the easiest way?

A: Check below class for reference:
class Customer {
  final String id;
  final String name;
  final String address;
  final String phoneNo;
  final String gstin;
  final String state;

Customer({
    this.id = '',
    @required this.name,
    @required this.address,
    @required this.phoneNo,
    this.gstin,
    @required this.state,
  });

  Customer copyWith({
    String name,
    String address,
    String phoneNo,
    String gstin,
    String state,
  }) {
    return Customer(
      name: name ?? this.name,
      address: address ?? this.address,
      phoneNo: phoneNo ?? this.phoneNo,
      gstin: gstin ?? this.gstin,
      state: state ?? this.state,
    );
  }

}

using copyWith constructor you can create a copy of an object.
if you don't pass any argument to copyWith constructor it returns a new object with the same values
But, if you wish to change any argument you do with copyWith constructor it will return the object copy with the new argument value you pass
Note: In copyWith constructor, suppose if you change one argument value then other argument value stays the same as the first object.


text:
Q: Google Search Results/ Beginner Python Just some questions regarding Python 3.
def AllMusic():
    myList1 = ["bob"]
    myList2 = ["dylan"]
    x = myList1[0]
    z = myList2[0]
    y = "-->Then 10 Numbers?"
    print("AllMusic")
    print("http://www.allmusic.com/artist/"+x+"-"+z+"-mn"+y)

This is my code so far.
I want to write a program that prints out the variable y.
When you go to AllMusic.com. The different artists have unique 10 numbers.
For example, www.allmusic.com/artist/the-beatles-mn0000754032, www.allmusic.com/artist/arcade-fire-mn0000185591.
x is the first word of the artist and y is the second word of the artist. Everything works but I can't figure out a way to find that 10 digit number and return it to me for each artist I input into my python program.
I figured out that when you go to google and type for example "Arcade Fire AllMusic", in the first result just under the heading it gives you the url of the site. www.allmusic.com/artist/arcade-fire-mn0000185591
How can I copy that 10 digit code, 0000185591, into my python program and print it out for me to see.

A: I wouldn't use Google at all - you can use the search on the site. There are many useful tools to help you do web scraping in python: I'd recommend installing BeautifulSoup. Here's a small script you can experiment with:
import urllib
from bs4 import BeautifulSoup

def get_artist_link(artist):
    base = 'http://www.allmusic.com/search/all/'
    # encode spaces
    query = artist.replace(' ', '%20')
    url = base + query
    page = urllib.urlopen(url)
    soup = BeautifulSoup(page.read())
    artists = soup.find_all("li", class_ = "artist")
    for artist in artists:
        print(artist.a.attrs['href'])

if __name__ == '__main__':
    get_artist_link('the beatles')
    get_artist_link('arcade fire')

For me this prints out:
/artist/the-beatles-mn0000754032
/artist/arcade-fire-mn0000185591


text:
Q: I'm getting this error: "Cross origin requests are only supported for protocol schemes" Total error message:
Access to script at 'file:///C:/Users/sain0/Documents/HTML/Assignmentd/as8.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
My HTML Code
I tried sending a list through the files
Exporting
Importing
I got the error, What are the solutions for this error?
I tried using modules and also tried defining module.


text:
Q: How to trigger filesystem User Consent Prompt and add app to 'Files and Folders' privacy pane? macOS 10.15 Catalina requires additional user consent to access directories such as Desktop, Documents, and Downloads.

Advances in macOS Security - WWDC 2019
https://developer.apple.com/videos/play/wwdc2019/701/

Attempting to access these folders in some manner (the answer to this question) is designed to trigger a reactive User Consent Prompt:

"YOUR_APP.app" would like to access files in your Documents folder.

After the prompt has been shown, the app is added to the Files and Folders pane of System Preferences where it can then be checked or unchecked.
Even when the pane is unlocked, the "+" plus button is grayed out. Apps seemingly cannot be manually added. They are added by the system after triggering a User Consent Prompt.

I would like my app to show up in this pane.
I'm attempting to "access files" on the Desktop, but I'm never getting a prompt and my app never appears in System Preferences.
Which specific APIs will trigger these system prompts for the protected Catalina file locations?
Which file access methods will not trigger the prompts?
Are there any additional steps for Sandboxed apps attempting to access these file locations?
Are any Entitlements or Info.plist keys or other setup required in order for the prompts to appear or for you to gain access to these directories?
Can these prompts be triggered on command, without doing any "real" file system work?
Are there any situations where the prompts will not appear for an app? How can that app be made to appear in System Preferences?