text:
Q: Build XML with CSV data I am trying to build out a way to "upload" a csv file locally and have it build out an xml file based on data in the csv. I need to do all of this client-side, and I'm not too fluent with JS yet. I've figured out how to extract csv data...
<html>
<head>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
    <script>
       d3.select("body").append("input").attr("type", "file").attr("accept", ".csv").on("change", function() {
            var csv = d3.event.target.files[0];
                if (csv) {
                    var reader = new FileReader();
                        reader.onloadend = function(event) {
                        var Url = event.target.result;
                        d3.csv(Url, function(data) {
                            return {
                                name: data.name,
                                latitude: data.latitude,
                                longitude: data.longitude
                            };
                        }, function(rows) {
                            console.log(rows);
                        });
                    };
                reader.readAsDataURL(csv);
                }
            })
    </script>
</body>
</html>

...and I hope to iterate through the data to build the xml. Where I would like some guidance or suggestions is how I could build out the xml and have it downloaded as a file afterwards. Would DOM be right for the job? If so, how can I have it download abc.xml after it is generated from abc.csv? I am trying to turn cvs data "SomeName,40.987654,-70.123456" into...
<Entry>
    <name>SomeName</name>
    <Location>
        <coordinates>-70.123456,40.987654</coordinates>
    </Location>
</Entry>

I hope this was clear; if not, let me know and I'll try to better elaborate!

A: You can use the following example as a guide. This requires NPM package xml-parser as a dependency.

var xmlDoc = [
  {
    type: 'element',
    tagName: '?xml',
    attributes: {
      version: '1.0',
      encoding: 'UTF-8'
    },
    childNodes: [],
    innerXML: '>',
    closing: false,
    closingChar: '?'
  },
  {
    type: 'element',
    tagName: 'root',
    attributes: {},
    childNodes: [
      {
        type: 'text',
        text: 'Root Element'
      }
    ],
    innerXML: 'Root Element',
    closing: true,
    closingChar: null
  }
]

var xmlStr = xml.stringify(xmlDoc, 2); // 2 spaces

console.log(xmlStr);


text:
Q: What is the most efficient way to write a select statement with a "not in" subquery? What is the most efficient way to write a select statement similar to the below.
SELECT *
FROM Orders
WHERE Orders.Order_ID not in (Select Order_ID FROM HeldOrders)

The gist is you want the records from one table when the item is not in another table.

A: You can use a LEFT OUTER JOIN and check for NULL on the right table.
SELECT O1.*
FROM Orders O1
LEFT OUTER JOIN HeldOrders O2
ON O1.Order_ID = O2.Order_Id
WHERE O2.Order_Id IS NULL

A: For starters, a link to an old article in my blog on how NOT IN predicate works in SQL Server (and in other systems too):

*

*Counting missing rows: SQL Server

You can rewrite it as follows:
SELECT  *
FROM    Orders o
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    HeldOrders ho
        WHERE   ho.OrderID = o.OrderID
        )

, however, most databases will treat these queries the same.
Both these queries will use some kind of an ANTI JOIN.
This is useful for SQL Server if you want to check two or more columns, since SQL Server does not support this syntax:
SELECT  *
FROM    Orders o
WHERE   (col1, col2) NOT IN
        (
        SELECT  col1, col2
        FROM    HeldOrders ho
        )

Note, however, that NOT IN may be tricky due to the way it treats NULL values.
If Held.Orders is nullable, no records are found and the subquery returns but a single NULL, the whole query will return nothing (both IN and NOT IN will evaluate to NULL in this case).
Consider these data:
Orders:

OrderID
---
1

HeldOrders:

OrderID
---
2
NULL

This query:
SELECT  *
FROM    Orders o
WHERE   OrderID NOT IN
        (
        SELECT  OrderID
        FROM    HeldOrders ho
        )

will return nothing, which is probably not what you'd expect.
However, this one:
SELECT  *
FROM    Orders o
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    HeldOrders ho
        WHERE   ho.OrderID = o.OrderID
        )

will return the row with OrderID = 1.
Note that LEFT JOIN solutions proposed by others is far from being a most efficient solution.
This query:
SELECT  *
FROM    Orders o
LEFT JOIN
        HeldOrders ho
ON      ho.OrderID = o.OrderID
WHERE   ho.OrderID IS NULL

will use a filter condition that will need to evaluate and filter out all matching rows which can be numerius
An ANTI JOIN method used by both IN and EXISTS will just need to make sure that a record does not exists once per each row in Orders, so it will eliminate all possible duplicates first:

*

*NESTED LOOPS ANTI JOIN and MERGE ANTI JOIN will just skip the duplicates when evaluating HeldOrders.

*A HASH ANTI JOIN will eliminate duplicates when building the hash table.

A: "Most efficient" is going to be different depending on tables sizes, indexes, and so on.  In other words it's going to differ depending on the specific case you're using.
There are three ways I commonly use to accomplish what you want, depending on the situation.
1. Your example works fine if Orders.order_id is indexed, and HeldOrders is fairly small.
2. Another method is the "correlated subquery" which is a slight variation of what you have...
SELECT *
FROM Orders o
WHERE Orders.Order_ID not in (Select Order_ID
                              FROM HeldOrders h
                              where h.order_id = o.order_id)

Note the addition of the where clause.  This tends to work better when HeldOrders has a large number of rows.  Order_ID needs to be indexed in both tables.
3. Another method I use sometimes is left outer join...
SELECT *
FROM Orders o
left outer join HeldOrders h on h.order_id = o.order_id
where h.order_id is null

When using the left outer join, h.order_id will have a value in it matching o.order_id when there is a matching row.  If there isn't a matching row, h.order_id will be NULL.  By checking for the NULL values in the where clause you can filter on everything that doesn't have a match.
Each of these variations can work more or less efficiently in various scenarios.

A: I'm not sure what is the most efficient, but other options are:
1. Use EXISTS

SELECT *
FROM ORDERS O
WHERE NOT EXISTS (SELECT 1
                  FROM HeldOrders HO
                  WHERE O.Order_ID = HO.OrderID)

2. Use EXCEPT

SELECT O.Order_ID
FROM ORDERS O
EXCEPT
SELECT HO.Order_ID
FROM HeldOrders

A: Try
SELECT *
FROM Orders
LEFT JOIN HeldOrders
ON HeldOrders.Order_ID = Orders.Order_ID
WHERE HeldOrders.Order_ID IS NULL

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return value from firestore database? I am having a hard time returning a value from the firestore database.
I am trying to return the 'amount' from the database.
When setting the variable i am able to console.log the 'amount'. (see code)
But when i try to return the value at the end of the function, it does not return anything.('amount' is not defined  no-undef)
How can i return this value. Any help would be great. Please keep in mind that i am still quite new to this topic.
        import firebase from 'firebase/app';
        import 'firebase/firestore';
        import 'firebase/auth';

        export default function checkAmount() {

            let user = firebase.auth().currentUser;

            if (user) {
                let userUID = user.uid
                let docRef = firebase.firestore().collection("users").doc(userUID);

                docRef.get().then((doc) => {
                    if (doc.exists) {
                            let amount = doc.data().amount;
                            if (amount > 0){
                                console.log(amount) /// This does work
                            }
                        } else {
                            console.log("No such document!");
                        }
                    }).catch(function(error) {
                        console.log("Error getting document:", error);
                    });
            }

            return amount /// This **does not** return anything . How do i return the amount?
        }

A: The reason is because the get() method is asynchronous: it returns immediately with a promise that resolves some time later with the results of the query. The get() method does not block the function (it returns immediately, as said above): this is why the last line (return amount) is executed before the asynchronous work is finished but with an undefined value.
You can read more here on asynchronous JavaScript methods and here on why Firebase APIs are asynchronous.
You therefore need to wait that the promise returned by the get() resolves and use the then() method, as Alex mentioned, to receive the query results and send the response.
The following will work:
    export default function checkAmount() {

        let user = firebase.auth().currentUser;

        if (user) {
            let userUID = user.uid
            let docRef = firebase.firestore().collection("users").doc(userUID);

            return docRef.get().then((doc) => {  //Note the return here
                if (doc.exists) {
                        let amount = doc.data().amount;
                        if (amount > 0){
                            console.log(amount) /// This does work
                            return true;  //Note the return here
                        }
                    } else {
                        console.log("No such document!");
                        //Handle this situation the way you want! E.g. return false or throw an error
                        return false;
                    }
                }).catch(error => {
                    console.log("Error getting document:", error);
                    //Handle this situation the way you want
                });
        } else {
           //Handle this situation the way you want
        }

    }

But you need to note that your function is now also asynchronous. Therefore you should call it as follows:
checkAmount().
then(result => {
  //Do whatever you want with the result value
  console.log(result);
})


text:
Q: How to close Firefox? I want a javascript code for closing the whole Firefox not just a Tab. Could anyone has experience with this? I have tried the methods that I have found over Google but I can not solve this problem

A: You can't exit the program with JavaScript.  That is a system command that JS doesn't have access to.

A: A webpage will never have permission to shut down the browser entirely.

A: I assume you're trying to use Javascript in a web page to do this.
The short answer is: You can't.
The Javascript code running within a given web page will only ever know anything about it's own context -- ie the page it is running on. It will know nothing about any other tabs or browser windows, and it cannot access them.
You can tell Javascript to close the current window, because it has access to its own window, but you cannot tell it to close all windows because it doesn't have access to them.
The only exception to this where you can use JS to jump context between different windows and tabs is where one window/tab has caused another to open. In this case, the parent window should have a handle to the one that was opened, and that window should in turn be able to access it's parent using the window.opener object.
So, if the windows/tabs open in Firefox have all been opened by each other, then you might be able to generate a call chain which allows you to close them all. But it'll still be a tricky task, and it still definitely won't allow you to touch any windows or tabs which have been opened separately by the user.
I hope that helps.


text:
Q: How activate OSPF in a router Cisco-IOS-XE using RESTCONF? I'm trying to activate OSPF routing protocol in a router using a python script with restconf. I send the request to this url https://(router ip)/restconf/data/Cisco-IOS-XE-ospf-native-router:10 but i get this return message: {                                                                                "errors": {                                                                                "error": [                                                                                {                                                                                "error-message": "uri keypath not found",                                                     "error-tag": "invalid-value",                                                                 "error-type": "application"                                                              }                                                                                ]                                                                                }                                                                                }
I tried with differents urls but no one was the correct and i don't know what is wrong, the url  or the content of the body , can someone help me?
This is the content of my script:
import json
import requests

requests.packages.urllib3.disable_warnings()

api_url = "https://(ip)/restconf/data/Cisco-IOS-XE-ospf-native-router:10"
headers = {"Accept": "application/yang-data+json",
           "Content-type": "application/yang-data+json"}
basicauth = ("user", "password")

body = '{"router":{"ospf":[{"id":10, "router-id":"1.1.1.1", "network":[{"ip": "172.16.199.1", "mask": "0.0.0.0", "area": 0},{"ip":"192.168.56.101", "mask": "0.0.0.0", "area":0}]}]}}'

requests.put(api_url, auth=basicauth, headers=headers, data=body, verify=False)

resp = requests.get(api_url, auth=basicauth, headers=headers, verify=False)

response_json = resp.json()

print(json.dumps(response_json, indent=5))

A: OSPF config with RESTCONF can just be modify, not create.

ospf_data = '''
{
    "Cisco-IOS-XE-native:router": {
        "Cisco-IOS-XE-ospf:router-ospf": {
            "ospf": {
                "process-id": [
                    {
                        "id": 10
                    }
                ]
            }
        }
    }
}
'''

def modify_ospf(data):
    ospf_api = "/restconf/data/Cisco-IOS-XE-native:native/router"
    ospf_uri = "https://" + host + ospf_api
    headers = {'Content-Type': 'application/yang-data+json','Accept': 'application/yang-data+json'}

    ospf_config_result = requests.request("PUT",
                                         url=ospf_uri,
                                         auth=(username,password),
                                         data=data,
                                         headers=headers,
                                         verify=False)

modify_ospf(ospf_data)

A: Your body seems not vaild YANG format.

body = '{"router":{"ospf":[{"id":10, "router-id":"1.1.1.1", "network":[{"ip": "172.16.199.1", "mask": "0.0.0.0", "area": 0},{"ip":"192.168.56.101", "mask": "0.0.0.0", "area":0}]}]}}'

You have to follow YANG format like:
$ curl -k -s -u user:password -X GET -H 'Accept: application/yang-data+json' https://172.31.5.1/restconf/data/Cisco-IOS-XE-native:native/Cisco-IOS-XE-native:router/ospf

{
  "Cisco-IOS-XE-ospf:ospf": [
    {
      "id": 10,
      "router-id": "1.1.1.1",
      "network": [
        {
          "ip": "172.16.199.1",
          "mask": "0.0.0.0",
          "area": 0
        },
        {
          "ip": "192.168.56.101",
          "mask": "0.0.0.0",
          "area": 0
        }
      ]
    }
  ]
}


text:
Q: Android: java.lang.IllegalStateException: Could not execute method of the activity Why am i getting this error??
04-27 16:09:19.823  32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823  32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823  32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 32255
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:3830)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
            at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)

What my application does is, opens up the camera application via an intent. Then loads the image/bitmao into an imageview. Whenever i click the save_btn button it gives me this error. Could anybody tell me why and give me a solution? Thank you.
package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;

public class MainActivity extends Activity {

    static final int REQUEST_IMAGE_CAPTURE = 1;
    ImageView imageView;
    private static final String TAG = "MyActivity";
    Bitmap image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openCamera();
        setContentView(R.layout.activity_main);
        findViewById(R.id.captureImage).bringToFront();
        findViewById(R.id.saveImage).bringToFront();
        imageView = (ImageView) findViewById(R.id.imageView2);

    }

    protected void onSaveInstanceState(Bundle outState){
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        file.delete();
    }

    public void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Check that request code matches ours:
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            //Get our saved file into a bitmap object:
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
            Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
            imageView.setImageBitmap(image);
        }
    }

// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
    public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
        //First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize, Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        }
        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }

        options.inSampleSize = inSampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }

    public void capture_btn(View v) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

    /** Create a File for saving an image or video */
    private  File getOutputMediaFile(){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Pictures/Wiki_Camera"
                + getApplicationContext().getPackageName()
                + "/Files");

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
        String mImageName="camera_wiki"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        return mediaFile;
    }

    public void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d(TAG,
                    "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

    public void save_btn(View v) {

        storeImage(image);
    }
}

A: Just guessing but it seems you store taken image only for local variable
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);

While later in the code you try to store image from class variable with the same name
image.compress(Bitmap.CompressFormat.PNG, 90, fos);

A:   public void storeImage(Bitmap image) {
            imageView.buildDrawingCache();
            Bitmap bm_img = imageView.getDrawingCache();
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                Log.d(TAG,
                        "Error creating media file, check storage permissions: ");// e.getMessage());
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                bm_img.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            }
        }


text:
Q: ColdFusion Conditional RecordCount Alright SO users... Here's a seemingly impossible to go wrong conditional statement. It is very simple, however, I cannot figure out why it won't work the way it is expected to.
<cfoutput query="checkForAd">
        <!--- also used the line <cfif RecordCount eq 0> --->
    <cfif checkForAd.RecordCount eq 0>
        <!--- Display some message. (Perhaps using a table, undecided) --->
    <cfelse>
        <!--- Display some other message. (Happens to be a table) --->
    </cfif>
</cfoutput>

When the RecordCount returns a number greater than 0, the else case displays properly. When RecordCount returns 0, nothing is displayed and the form continues along its path. I've become very frustrated as this should be quite simple...

A: As nykash has pointed out, the body of a cfoutput query (or a cfloop query) never executes if there are no records, so doing a check for a zero recordcount will never be true inside of one.
However, I find the following example a more readable one:
<cfif NOT checkForAd.RecordCount >
    <!--- Display some message. --->
</cfif>

<cfoutput query="checkForAd">
        <!--- loop through data --->
</cfoutput>

It might not seem much in isolation, but I think it's a bit cleaner and easier to see what's going on, especially when combined with other code.
Specifically on the RecordCount check, if I care about the specific number then I'll use EQ (or NEQ/GT/etc) but if I only care about "having records" vs "not having records" then I use the implicit boolean conversion that CFML provides to simplify the code. This really makes it easier to identify when I'm using the common binary choice or a more significant one, so navigating through the code is easier.

A: The output won't return any results if the query set is empty. Try:
<cfif checkForAd.RecordCount eq 0>
    <!--- Display some message. (Perhaps using a table, undecided) --->
<cfelse>
    <cfoutput query="checkForAd">
        <!--- Display some other message. (Happens to be a table) --->
    </cfoutput>
</cfif>

I assume that you're looking to return a number of records... if you were just returning one, the query="checkForAd" isn't necessary. You can simply reference the query & variables in a <cfoutput></cfoutput>.
Edit
Here's one way to access a query variable: QueryName["ColumnName"][RowNum]
(As you look to expand your coding, there's a lot you can do with query variables. There's a great rundown of the different approaches at ColdFusion and getting data from MySQL)


text:
Q: Getting boost::spirit::qi to use stl containers I'm trying to parse something with boost.spirit's qi library, and I'm running into an issue. According to the spirit docs, a >> b should produce something with the type tuple<A, B>. But this is a boost::tuple (aka fusion vector), and not a std::tuple (which I want).
Is there any easy way to make this conversion between boost::tuple => std::tuple?
The same documentation page says that *a should produce something with the type vector<A>. This seems to be producing a std::vector<A> (or some kind of boost::vector<A> that can implicitly convert to a std::vector<A>). I just wanted to know if this same behavior was available for tuples.

A: SHORT ANSWER:
Use #include <boost/fusion/adapted/std_tuple.hpp>.
MORE COMPLETE ANSWER:
As you can see here:

In the attribute tables, we will use vector<A> and tuple<A, B...> as placeholders only. The notation of vector<A> stands for any STL container holding elements of type A and the notation tuple<A, B...> stands for any Boost.Fusion sequence holding A, B, ... etc. elements. Finally, Unused stands for unused_type.

So when a parser/generator has an attribute of tuple<A,B...> you can use any fusion sequence (such as fusion::vector or fusion::list) or anything that can be adapted to a fusion sequence (such as boost::array, boost::tuple, std::pair, std::tuple, your own struct using BOOST_FUSION_ADAPT_STRUCT).
And when it has vector<A> you can use std::vector, std::list, and even std::map if your elements are pairs. You can also use your own struct if you also specialize several customization points (at least is_container, container_value and push_back_container in boost::spirit::traits).
std::pair
In order to be able to use std::pair with spirit you just need to add a single header:
#include <boost/fusion/include/std_pair.hpp>
...
qi::rule<Iterator,std::pair<int,double>()> rule =
    qi::int_ >> qi::lit(',') >> qi::double_;

std::tuple
Starting with boost 1.48.0 you can do the same for std::tuple:
#include <boost/fusion/adapted/std_tuple.hpp>
...
qi::rule<Iterator,std::tuple<int,std::string,double>()> rule =
    qi::int_ >> qi::lit(',') >> +~qi::char_(',') >> qi::lit(',') >> qi::double_;

Your own struct
You can adapt your custom struct very easily with the help of BOOST_FUSION_ADAPT_STRUCT:
#include <boost/fusion/include/adapt_struct.hpp>
...
struct normal_struct
{
    int integer;
    double real;
};

BOOST_FUSION_ADAPT_STRUCT(
    normal_struct,
    (int, integer)
    (double, real)
)
...
qi::rule<Iterator,normal_struct()> rule =
    qi::int_ >> qi::lit(',') >> qi::double_;

There is one known limitation though, when you try to use a struct that has a single element that is also a container compilation fails unless you add qi::eps >> ... to your rule.
struct struct_with_single_element_container
{
    std::vector<int> cont;
};

BOOST_FUSION_ADAPT_STRUCT(
    struct_with_single_element_container,
    (std::vector<int>, cont)
)
...
qi::rule<Iterator,struct_with_single_element_container()> rule =
    qi::eps >> qi::int_%qi::lit(',');

std::map
You can simply use std::map as a container of std::pairs. Keep in mind though that if there are repeated keys in your input, only the first one will be inserted to the map (if you use multimap everything will be inserted of course):
#include <boost/fusion/include/std_pair.hpp>
...
qi::rule<std::string::const_iterator, std::pair<double,int>()> pair_rule =
    qi::double_ >> qi::lit('=') >> qi::int_;
qi::rule<std::string::const_iterator, std::map<double,int>()> rule =
    pair_rule%qi::lit(',');
//You can also use
//qi::rule<std::string::const_iterator, std::map<double,int>()> rule =
    //(qi::double_ >> qi::lit('=') >> qi::int_)%qi::lit(',');

Your own struct as a container
Using spirit's customization points you can also make your struct behave as if it were a container when dealing with attributes. The minimum you need to specialize are is_container, container_value and push_back_container. Here are a couple of examples:

The first one is rather simple (and silly). It makes your struct have an attribute compatible with std::vector<int>. Every time an int is parsed it is added to the total in the accumulator. You can find less silly approaches here and here (in the "old answer").
struct accumulator
{
    accumulator(): total(){}
    int total;
};

namespace boost{ namespace spirit{ namespace traits
{
    template<>
    struct is_container<accumulator> : boost::mpl::true_
    {};

    template<>
    struct container_value<accumulator>
    {
        typedef int type;
    };

    template<>
    struct push_back_container<accumulator,int>
    {
        static bool call(accumulator& c, int val)
        {
            c.total+=val;
            return true;
        }
    };
}}}
...
qi::rule<Iterator,accumulator()> rule =
    qi::int_%qi::lit(',');

The second one is a little more complex (not much). It makes your struct have an attribute compatible with std::vector<boost::variant<int,std::string> >. When an int is parsed it is added to the ints container in the distributor, similarly strings are stored in the strings container. Examples using this (1, 2 and 3).
struct distributor
{
    distributor():ints(),strings(){}
    std::vector<int> ints;
    std::vector<std::string> strings;
};

namespace boost{ namespace spirit{ namespace traits
{
    template<>
    struct is_container<distributor> : boost::mpl::true_
    {};

    template<>
    struct container_value<distributor>
    {
        typedef boost::variant<int,std::string> type;
    };

    template<>
    struct push_back_container<distributor,int>
    {
        static bool call(distributor& c, int val)
        {
            c.ints.push_back(val);
            return true;
        }
    };

    template<>
    struct push_back_container<distributor,std::string>
    {
        static bool call(distributor& c, std::string const& val)
        {
            c.strings.push_back(val);
            return true;
        }
    };
}}}
...
qi::rule<std::string::const_iterator, std::string()> string_rule =
    +~qi::char_(',');
qi::rule<std::string::const_iterator, distributor()> rule =
    (qi::int_ | string_rule)%qi::lit(',');

All the tests in a single cpp file
#include <iostream>
#include <string>
#include <utility>
#include <tuple>
#include <list>
#include <vector>
#include <map>

#include <boost/fusion/include/std_pair.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>

#include <boost/spirit/include/qi.hpp>

#include <boost/variant.hpp>

namespace qi=boost::spirit::qi;

struct normal_struct
{
    int integer;
    double real;
};

struct struct_with_single_element_container
{
    std::vector<int> cont;
};

BOOST_FUSION_ADAPT_STRUCT(
    normal_struct,
    (int, integer)
    (double, real)
)

BOOST_FUSION_ADAPT_STRUCT(
    struct_with_single_element_container,
    (std::vector<int>, cont)
)

struct accumulator
{
    accumulator(): total(){}
    int total;
};

namespace boost{ namespace spirit{ namespace traits
{
    template<>
    struct is_container<accumulator> : boost::mpl::true_
    {};

    template<>
    struct container_value<accumulator>
    {
        typedef int type;
    };

    template<>
    struct push_back_container<accumulator,int>
    {
        static bool call(accumulator& c, int val)
        {
            c.total+=val;
            return true;
        }
    };
}}}

struct distributor
{
    distributor():ints(),strings(){}
    std::vector<int> ints;
    std::vector<std::string> strings;
};

namespace boost{ namespace spirit{ namespace traits
{
    template<>
    struct is_container<distributor> : boost::mpl::true_
    {};

    template<>
    struct container_value<distributor>
    {
        typedef boost::variant<int,std::string> type;
    };

    template<>
    struct push_back_container<distributor,int>
    {
        static bool call(distributor& c, int val)
        {
            c.ints.push_back(val);
            return true;
        }
    };

    template<>
    struct push_back_container<distributor,std::string>
    {
        static bool call(distributor& c, std::string const& val)
        {
            c.strings.push_back(val);
            return true;
        }
    };
}}}

int main()
{
    {
        std::pair<int,double> parsed;
        qi::rule<std::string::const_iterator, std::pair<int,double>()> rule =
                    qi::int_ >> qi::lit(',') >> qi::double_;
        std::string test="1,2.5";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "First: " << parsed.first << ", Second: " << parsed.second << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        std::tuple<int,std::string,double> parsed;
        qi::rule<std::string::const_iterator, std::tuple<int,std::string,double>()> rule =
                    qi::int_ >> qi::lit(',') >> +~qi::char_(',') >> qi::lit(',') >> qi::double_;
        std::string test="1,abc,2.5";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "get<0>: " << std::get<0>(parsed) << ", get<1>: " << std::get<1>(parsed) << ", get<2>: " << std::get<2>(parsed) << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        normal_struct parsed;
        qi::rule<std::string::const_iterator, normal_struct()> rule =
                    qi::int_ >> qi::lit(',') >> qi::double_;
        std::string test="1,2.5";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "integer: " << parsed.integer << ", real: " << parsed.real << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        struct_with_single_element_container parsed;
        //there is a problem when you have a struct with a single element container, the workaround is simply adding qi::eps to the rule
        qi::rule<std::string::const_iterator, struct_with_single_element_container()> rule =
                    qi::eps >> qi::int_%qi::lit(',');
        std::string test="1,2";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "[0]: " << parsed.cont[0] << ", [1]: " << parsed.cont[1] << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        std::list<int> parsed;
        qi::rule<std::string::const_iterator, std::list<int>()> rule =
                    qi::int_%qi::lit(',');
        std::string test="1,2";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "front: " << parsed.front() << ", back: " << parsed.back() << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        std::map<double,int> parsed;
        qi::rule<std::string::const_iterator, std::pair<double,int>()> pair_rule =
                    qi::double_ >> qi::lit('=') >> qi::int_;
        qi::rule<std::string::const_iterator, std::map<double,int>()> rule =
                    pair_rule%qi::lit(',');
        std::string test="2.5=1,3.5=2";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "map[2.5]: " << parsed[2.5] << ", map[3.5]: " << parsed[3.5] << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        accumulator parsed;
        qi::rule<std::string::const_iterator, accumulator()> rule =
                    qi::int_%qi::lit(',');
        std::string test="1,2,3";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "total: " << parsed.total << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

    {
        distributor parsed;
        qi::rule<std::string::const_iterator, std::string()> string_rule =
                    +~qi::char_(',');
        qi::rule<std::string::const_iterator, distributor()> rule =
                    (qi::int_ | string_rule)%qi::lit(',');
        std::string test="abc,1,2,def,ghi,3,jkl";
        std::string::const_iterator iter=test.begin(), end=test.end();
        bool result = qi::parse(iter,end,rule,parsed);
        if(result && iter==end)
        {
            std::cout << "Success." << std::endl;
            std::cout << "ints" << std::endl;
            for(auto val: parsed.ints)
                std::cout << val << std::endl;
            std::cout << "strings" << std::endl;
            for(const auto& val: parsed.strings)
                std::cout << val << std::endl;
        }
        else
        {
            std::cout << "Failure." << std::endl;
            std::cout << "Unparsed: " << std::string(iter,end) << std::endl;
        }
    }

}


text:
Q: How to parse json optimal way? I have a JSON document with 8kk objects that looks like this
{'_id': ObjectId('55d6e5114d02f49f998a08b5'),
 'created_at': 1440146705.612493,
 'message': 'Ð\x9fÑ\x80ивеÑ\x82! Ð\x97деÑ\x81Ñ\x8c вÑ\x8b можеÑ\x82е задаÑ\x82Ñ\x8c вопÑ\x80оÑ\x81 и бÑ\x8bÑ\x81Ñ\x82Ñ\x80о полÑ\x83Ñ\x87иÑ\x82Ñ\x8c оÑ\x82веÑ\x82 на него.',
 'room': '55d5928a4d02f4a55007344c',
 'sender': '55af71054d02f4571abe1f1f'}

I want to parse it and create a data frame. So I create a data frame and then concat it to already existing one so I do
import pandas as pd

df = pd.DataFrame(pd.Series(my_json[0],index=my_json[0].keys())).transpose()
for i in my_json:
    df = pd.concat([df,pd.DataFrame(pd.Series(i,index=i.keys())).transpose()])

But it takes too long. Is there any other proper way to do so?
_id 55db1fff4d02f4aeb974dc6e
message Привет! Здесь вы можете задать вопрос и быстро...
room    55db1ffe4d02f4aeb974dc6c
created_at  1.44042e+09
sender  55af71054d02f4571abe1f1f

Want to get something like that but transposed


text:
Q: Using ViewData to pass data from Controller to View I'm trying to pass data from a controller to view, and display these data. But after many tries I can't.
Controller code :
public ActionResult ValidSearch(ProductSearchParam gp)
{

    if (gp.IsCandidate)
    {
        ViewBag.abc="bob";
        List<ProductCandidate> prodClist = new List<ProductCandidate>();
        prodClist = Pcs.SearchParam(gp,0,100);
        ViewBag.total = prodClist.Count;
        return View("ValidSearchCandidate", prodClist);
    }
    else
    {
        List<Product> prodlist = new List<Product>();
        prodlist = Ps.SearchParam(gp,0,100);
        ViewBag.total = prodlist.Count;
        return View("ValidSearch", prodlist);
    }

    //return View();
}

View code :

Bonjour @ViewBag.abc

I've even try TempData or ViewBag, unsuccessfully.
I do not understand why the value is not getting passed to the View correctly
Can someone help me to solve this ?

A: Since you have set some property on the ViewData on the Controller, you will have it available on the ViewData on View. On the other hand, you have the TempData which is used when you need to transfer information between requests to another route (redirects to an action). For sample:
public ActionResult ValidSearch(ProductSearchParam gp)
{
   List<ProductCandidate> prodClist = new List<ProductCandidate>();

   ViewData["Nom"] = "bob";

   return View("ValidSearchCandidate", prodClist);
}

And in the view:
@ViewData["Nom"].ToString()

@foreach(var prod in  Model)
{

@prod.Name

}

A: You can use ViewBag for this
Controller :
ViewBag.name= "bob";

View :

Bonjour @ViewBag.name

A: In your example you've used ViewData in Controller and TempData in View
If you use ViewData["Nom"] in controller, you should use ViewData["Nom"] in view. Are you use that you are not misspelling the object?

A: Replace ViewBag["try"] to ViewData["try"] in your controller code.
And, In the else condition you have no any declaration of ViewData["try"] so
may be you have to check the ViewData before using it on your view.


text:
Q: How to prevent data loss when I want to update database by using db-migration? When I was making update my database by using db-migration, I faced a problem that was
Automatic migration was not applied because it would result in data loss.

(I used System.ComponentModel.DataAnnotations such as [Required] and [StringLength(25)] for some properties. For example Title property.)
I know if I set the AutomaticMigrationDataLossAllowed to true and Update-Database -Force, my database will be update but my data will be removed and I'm going to prevent from it. I want to protect my data.
I've used Entity Framework 6.x
How can I solve this problem?
Configuration class:
namespace Jahan.Blog.Web.Mvc.Migrations
{
   using System;
   using System.Data.Entity;
   using System.Data.Entity.Migrations;
   using System.Linq;

   internal sealed class Configuration
    : DbMigrationsConfiguration<Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext>
   {
       public Configuration()
       {
           AutomaticMigrationsEnabled = true;
           AutomaticMigrationDataLossAllowed = false;
       }

       protected override void Seed(Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext context)
       {

       }
   }
}

Initial class:
namespace Jahan.Blog.Web.Mvc.Migrations
{
   using System;
   using System.Data.Entity.Migrations;

   public partial class Initial : DbMigration
   {
       public override void Up()
       {
       }

       public override void Down()
       {
       }
   }
}

My DbContext:
namespace Jahan.Blog.DataAccess
{
   public class JahanBlogDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole,    UserClaim>
   {
       public JahanBlogDbContext()
           : base("name=JahanBlogDbConnectionString")
       {

       }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Comment>().HasRequired(t => t.Article).WithMany(t => t.Comments).HasForeignKey(d => d.ArticleId).WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
       }
       // ... codes ....
   }
}

A: You can add sql to fix the data in a way that is acceptable to you. You need to ensure that the alter statements generated BY EF do not cause data loss.
Use the Sql method in a migration to run your own sql:
public override void Up()
{
    //Add this to your migration...
    Sql("UPDATE dbo.Table SET Name = LEFT(Name, 25) WHERE LEN(Name) > 25")

    //...before the code generated by EF
    AlterColumn("dbo.Table", "Name ", c => c.String(nullable: false, maxLength: 25));
}


text:
Q: Scammer spam autocompletes when entering team name in profile

When I type "Google", "Microsoft", "Norton", "Canon", "Lexmark", or any of several other company names into the Company Name field in the Career section of my Stack Overflow profile, most of the suggestions are advertisements for known scammers.
This seems bad.

A: This is bad data coming from CrunchBase - I am working to address it now.

Update: I have done a huge amount of cleanup from the data source and just deployed a new Elastic indexing using it. Here's the old vs. new:

There's a x2 factor of replication, which means there were 59,494 entries removed from the index. Here's a current test:

Note there's still a crap entry there, so I did a good purge but far from perfect. We wanted to address this as soon as possible though, so a quick first pass it is. Hopefully this removed most of the immediate spam. Please feel free to comment here on additional finds and I'll take another pass Monday at cleaning this up further.
On a personal note: I pushed for this. I pushed to buy a clean data source to prevent duplication and have a good user experience with developer stories. This is not what we intended to do and I'm pissed. We also should have checked this further before indexing for developer story and that's on me - I failed here.
I'm sorry this ever showed up on our website. We'll be adding checks to, I sincerely hope, prevent this from ever happening again.


text:
Q: What privilege is required to preserve ownership of a file on copy, and how do you get it? I have a homework question about kernel programming in Linux. The question is:

What Linux-specific privilege is required to preserve ownership of a file when it's copied, and how do you get it?

Through experimentation, I've found that I need to be root or a superuser to get this to work. Is there a more specific way to explain this effect?

A: See the capabilities(7) manual page – you need the CAP_CHOWN capability to change file ownership via chown(). (Root has all capabilities enabled automatically. The manual page explains how to obtain capabilities in other cases.)
There is no separate method/capability to just preserve ownership, as Linux file copies are made by simply reading/writing data to the destination file, then doing the same with metadata. (For comparison, Windows NT has SeBackupPrivilege and SeRestorePrivilege privileges and the BackupRead()/BackupWrite() calls.)


text:
Q: What is the best way output the name of the class who's method is being called? I am aware of NSStringFromClass.
My question relates to the situation where the same method is implemented in multiple classes in an inheritance tree, and you want to debugging information as to which class it is executing from.
Example:
Let us have three classes: A-->B-->C , inheriting as displayed by the arrows.
If each of them has a method foo(), defined:
-(void) foo
{
 // Do some work particular to the class it is in.
  .....
  //Each method ends with the debugging statement:
  NSLog("In foo of class:%$",NSClassFromString([self class]));
}

The problem occurs when foo of Class B, calls [super foo]. When [super foo] (i.e. Class A) reaches the NSLog statement, [self class] returns class B, and not A.
Likewise if C called [super foo], the log statement in super would log class C.
What I want to do, is output the class whose method implementation is being executed - so if class B calls [super foo], then the log statement in [A foo] outputs Class A.
The simple way is to replace NSClassFromString with a hardcoded string representing the class name, but I was wondering if there is a better way to do this ?

A: You can use __PRETTY_FUNCTION__ to include both the class and the method name:
NSLog(@"Greetings from %s", __PRETTY_FUNCTION__);

I don't believe that there is a compiler-time macro for just the class name.

A: There might not be a macro for class, but there is __FILE__ and __LINE__ macros in the C language. They expand to the current file and line number. You can use them in NSLog. I use __PRETTY_FUNCTION__ when I remember it, but I remember __FILE__ and __LINE__ more.
Example:
NSLog( @"%s %d", __FILE__, __LINE__ );

Remember that __FILE__ isn't an Objective-C string.

A:
The problem occurs when foo of Class B, calls [super foo]. When [super
  foo] (i.e. Class A) reaches the NSLog statement, [self class] returns
  class B, and not A.

Sure. That's because self points to an object, and that object's class doesn't change just because you call a method of the superclass.

The simple way is to replace NSClassFromString with a hardcoded string
  representing the class name, but I was wondering if there is a better
  way to do this?

As others have pointed out, you can use a macro like __PRETTY_FUNCTION__, but I think the simple and obvious approach is the best. You know the name of the class when you're writing the code, so you can write:
NSLog("In foo of class: %@", @"ClassA");

Each of your classes has its own implementation of your method, so each one can print its own class name in the message. Something like __PRETTY_FUNCTION__ is useful when you're writing a debug macro that you're going to use in multiple functions. That's not the case here. Using the obvious approach makes it that much easier to see what's going on, and that's important during debugging (which I assume is what you're trying to do here).

A: i think you would have to walk up the class hierarchy using class_getSuperclass and class_getInstanceMethod, comparing differences in the methods. do that to determine the objc class, then use class_getName or NSStringFromClass to get its name.
This would look something like:
NSString* MONClassNameWhichImplementsMethod(id Self, SEL cmd);

and
- (void)method
{
  NSLog(@"%@ - %@",
    MONGetClassWhichImplementsMethod(self, _cmd),
    NSStringFromSelector(_cmd)
  );
}

and
// NOT COMPILED -- FOR ILLUSTRATION ONLY
Class MONClassWhichImplementsMethod(Class cls, SEL cmd) {
  assert(cls && cmd && "srsly?");

  Class super = class_getSuperclass(cls);
  Method m1 = class_getInstanceMethod(cls, cmd);
  assert(m1 && "srsly?");

  Method m2 = class_getInstanceMethod(super, cmd);
  if (0 == m2) {
    return cls;
  }
  else if (m1 != m2) {
    return cls;
  }
  else {
    return MONClassWhichImplementsMethod(super, cmd);
  }
}

NSString* MONClassNameWhichImplementsMethod(id Self, SEL cmd) {
  return NSStringFromClass(MONClassNameWhichImplementsMethod(Self.class, cmd));
}

if it blows up from deep recursion, you've another problem.


text:
Q: How do I make this word table into a latex table? VIEW HERE

In this table, the Name, Date, and Section boxes do not have an upper or lower boarder. But the other boxes do. Can you make this into a latex table for me?
Please make it span 7.5 inches.
Thanks,
Nathan
I have tried everything and I have not been able to convert it into a latex table.

A: Something like:
\documentclass[border=5mm]{standalone}

\begin{document}

\renewcommand{\arraystretch}{2}
\begin{tabular}{l|p{2in}|l|p{1in}|l|p{.5in}|}
\cline{2-2}\cline{4-4}\cline{6-6}
Name: & & Date: & & Section: & \\
\cline{2-2}\cline{4-4}\cline{6-6}
\end{tabular}

\end{document}

Then you can tune the widths in inches (in) as you prefer.


text:
Q: esp32 connect(): socket error on fd 48, errno: 104, "Connection reset by peer" I'm working on BasicHTTPClient for send the data from the esp32 cam board to webserver through GET method i have googled about this error can some explain me this error and tell me how to slove it
thank you in advance!

A: Reset means that either there was nothing listening on the TCP port you tried to connect to (for instance, the web server wasn't running, or you had the wrong port number for it, or there was a firewall blocking access), or if you had already connected that the server your software was talking to abruptly went away (crashed, exited, or a firewall was brought up).
I noticed that you tagged your question with localhost. If you're attempting to connect to http://localhost or http://127.0.0.1 from the ESP32, that will absolutely not work. localhost is shorthand for "the same computer" - it's not the name of some other computer your web server is running on. If you're trying to connect to localhost from the ESP32, you're trying to connect to a web server running on the ESP32, which is also certainly not the case, and you would in fact get a reset as a response. You need to use the correct name or IP address of the computer you're trying to connect to.


text:
Q: Where I can find Kubernetes PV on the host filesystem? I am trying to understand how Kubernetes handles the persistent volumes on the node's filesystem.
For example, if I have a minikube as my Kubernetes cluster node, and I create multiple PVs with PVC for may pods and if I ssh to minikube, where I can find the PV on minikube's filesystem?
If I type

lsblk

I get

sda      8:0    0  19.5G  0 disk

but no PV disks are listed.
Thank you for your answers.

A: You will not see it because it's inside API as an API Object.
I recommend reading Kubernetes documentation regarding Persistent Volumes.

A  PersistentVolume  (PV) is a piece of storage in the cluster that has been provisioned by an administrator. It is a resource in the cluster just like a node is a cluster resource. PVs are volume plugins like Volumes, but have a lifecycle independent of any individual pod that uses the PV. This API object captures the details of the implementation of the storage, be that NFS, iSCSI, or a cloud-provider-specific storage system.
A  PersistentVolumeClaim  (PVC) is a request for storage by a user. It is similar to a pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). Claims can request specific size and access modes (e.g., can be mounted once read/write or many times read-only).
While  PersistentVolumeClaims  allow a user to consume abstract storage resources, it is common that users need  PersistentVolumes  with varying properties, such as performance, for different problems. Cluster administrators need to be able to offer a variety of  PersistentVolumes  that differ in more ways than just size and access modes, without exposing users to the details of how those volumes are implemented. For these needs there is the  StorageClass  resource.
Please see the  detailed walkthrough with working examples.

You can also have a look at the Kubernetes Volumes Guide which explains the types of storage, how long do they last and how to use them in examples.

A: Because they are hostPath, you will not see them in lsblk. Use "kubectl describe pv PV_NAME" to understand where they are located.


text:
Q: Android cannot find symbol method getMap() I have a gps app that works fine on my phone. However, I see there were people having a null pointer exception in the production.
    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting GoogleMap object from the fragment
    googleMap = fm.getMap();

    // Enabling MyLocation Layer of Google Map
    googleMap.setMyLocationEnabled(true);

    googleMap.setPadding(0, 0, 0, 90);

The error I'm getting from production is
Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference

So I did some research and find out that getMap method has been removed and people recommend using getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;    //which doesn't seem to work
}

However, I'm referencing the googleMap variable in many different methods, and I cannot move all the code to onMapReady method. I tried using this.googleMap = googleMap inside the onMapReady method, but I'm still getting null pointer exceptions whenever I try to reference the googleMap variable. I defined the getMapAsync(this) in onCreated(), and then try to access the 'googleMap' object in onResume() and getting the null pointer exception. Is there a way to fix this?  Thank you.

A: You are getting null pointer exception because you are trying to use google map object but google map object is still null,so you need to follow this step.
write this code in onCreate() method
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

now impleents your class with public class Demo implements OnMapReadyCallback in short you need to override  onMapReady(Googlemap googleMap) methood.
you can perform all action after callback from onMapReady().
@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
 // Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
    }

A: As I suggest in this Answer.
getMap() is deprecated use getMapAsync() instead of it in the following way.
Replace this
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

with this
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMapAsync(this);

for more details visit this link

A: You can use the getMapAsync(this) method. Please check this link for more

A: Replace
googleMap = ((SupportMapFragment) getSupportFragmentManager()
    .findFragmentById(R.id.googleMap)).getMap();

with
googleMap = ((SupportMapFragment) getChildFragmentManager()
    .findFragmentById(R.id.map)).getMapAsync((OnMapReadyCallback) this);

A: Certainly you've mismatched the SupportMapFragment and MapFragment means if you have class attribute
class ="com.google.android.gms.maps.MapFragment"

in your XML then you should use
MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);

OR
If you have class attr like
class="com.google.android.gms.maps.SupportMapFragment"

then you can do like as you are doing.


text:
Q: Vaadin 23, component sizing optimization problem (Textfield, Select, etc.) I am trying to make my web app look identical on all screens. Essentially, I want my website to have the same appearance regardless of the resolution on user side.
I am already using vw and vh to set size, but some components (at least TextField, Select) have inner html code that seems to be completely unaffected by what I can do in Java, as well as parent css properties. For example:

Buttons looking not too bad, but TextField... I did set font size to be 1vw through css properties, but that only effects placeholder. I don't know, is there a way to bind all inner components of, for example TextField, to vw, vh of my choosing?

A: If you want all font sizes to adapt to the viewport width, you should override all Lumo font-size tokens/properties: https://vaadin.com/docs/latest/styling/lumo/design-tokens/typography/#lumo-font-size
For example:
frontend/themes/mytheme/styles.css:
html {
  --lumo-font-size-xxxl: 2.5vw;
  --lumo-font-size-xxl: 1.75vw;
  --lumo-font-size-xl: 1.375vw;
  --lumo-font-size-l: 1.125vw;
  --lumo-font-size-m: 1vw;
  --lumo-font-size-s: 0.875vw;
  --lumo-font-size-xs: 0.8125vw;
  --lumo-font-size-xxs: 0.75vw;
}


text:
Q: can anyone fix this. jQuery $.post i have a form like this (already add jquery latest)
echo '<form name="chat" id="chat" action="/pages/guicsdl.php" method="post">';
echo bbcode::auto_bb('chat', 'text');
echo '<textarea rows="3" name="text" id="text"></textarea><br/>';
echo '<input type="hidden" name="trave" value="'.$trave.'" /><input type="submit" name="submit" value="Gửi" /></form>';

and the js
$(document).ready(function() {
    $("chat").submit(function(){
        $.post('/pages/guicsdl.php', $("#chat").serialize() );
    });
});

and the file guicsdl.php
if(isset($_POST['submit'])) {
    $noidung = functions::check($_POST['text']);
    mysql_query("INSERT INTO `status` SET `user_id`='".$user_id."', `text`='".$noidung."', `time`='".time()."'");
    mysql_query("UPDATE `users` SET `tongchat`= tongchat+1 WHERE id = '".$user_id."' ");
    $trave = isset($_POST['trave']) ? base64_decode($_POST['trave']) : '';
    header("Location: $trave");
}

i only want when i submit the form, the page doesn't refresh, the data insert to database. can any one help me fix? pls, and thanks. sorry for bad english.

A: You have to add return false; so that the browser 'understands' that it should not submit the form directly.
$(document).ready(function(){
    $("#chat").submit(function(){
        $.post('/pages/guicsdl.php', $("#chat").serialize() );

        return false;
    });
});

Another way (which I myself prefer) is to tell the event to not do it's default behavior.
$(document).ready(function(){
    $("#chat").submit(function(ev){  // note the extra parameter
        ev.preventDefault();

        $.post('/pages/guicsdl.php', $("#chat").serialize() );
    });
});

Wilmer also noticed that you had forgotten to put a # for the jQuery identifier when selecting the chat form.


text:
Q: Chrome console jumps to sources tab unexpectedly in Codepen I try to test short lines of code on CodePen while chrome console is open:

After typing a single word console jumps to the source tab unexpectedly and I can't continue typing anymore?

I can remember that I've used Codepen without this annoying problem but now it made Codepen useless for me!
How I fix that?


text:
Q: RegEx looking both backwards and forward I'd like to get all the strings when it has a given term not followed by a set of given terms either preceded by the same terms using regular expressions, something like this:
(?<!(term1|term2)[\w\- ]{1,25})my_term(?![\w\- ]{1,25}(term1|term2))

Visualisation
but it seems it doesn't work with any of the following texts:
my_term good example.
Another good my_term example.
This one term1 shouldn't my_term work.
Neither my_term do term2 it.

Any idea?

A: Python re module doesn't support variable length lookbehinds. Your regex should throw a syntax error. A workaround would be using tempered dots:
^(?:(?!term1|term2).)*my_term(?:(?!term1|term2).)*$
 ^^^^^^^^^^^^^^^^^^^^^       ^^^^^^^^^^^^^^^^^^^^^

Live demo

A: Variable look behind is not supported in RegEx.
    (?<!(term1|term2)**[\w\- ]{1,25}**)my_term(?![\w\- ]{1,25}(term1|term2))

The part I have marked with  ** ** ie [\w- ]{1,25} is variable in the look behind group.
Can you give the input and expected output for a more specific answer?


text:
Q: Recommended Project Structure for multi-function SAM Template I have a new project that requires a relatively small amount of services, maybe 10 or less (and therefore it is not economical to place each in a separate project repository). Each service will be defined as an AWS::Serverless::Function via SAM Template. My question is: what is the recommended way to organize or structure such a project?
Currently the structure is:
|- src
    |- lambdas
        |- service-one
            |- stuff
            |- package.json
        |- service-two
            |- stuff
            |- package.json
    |- other-stuff
|- test
|- package.json

Is there a way to avoid having each lambda act as its own sub-project with unique package.json and etc?

A: I have designed the structure of my project like below
ProjectName
├── dependencies
│   └── package-pandas-requests.zip
├── deploy.sh
├── infrastructure
│   ├── packaged.yaml
│   └── template.yaml
└── src
    └── lambdas
        ├── lambdafunction1
        │   └── app.py
        ├── lambdafunction2
        │   └── app.py
        ├── lambdafunction3
        │   └── app.py

dependencies are layers package
infrastructure for yaml files of SAM framework
Hope this will clear your doubt.


text:
Q: Referenced Project Different Output folder I have a web site project with three referenced project.  The question is really simple.  For the refereneced project (say Project A and Project B referenced from Web Site Project).  All I want to do is to reference it in the Web Project but I don't want it to copy to the 'Bin' folder of the web site project.  I want it to copy to a folder that I define.  Is there a way to do that?  Many thanks.

A: I'm pretty sure you cannot change the ouput path if you build the referenced project. You can change the properties of the reference in the node references by right-clicking => properties, there is a property called copy local which will prevent the copy in the /bin folder. This means you will always reference whatever version of the dll is being pointed at in the Path property


text:
Q: Optimize the code for one command with only one different parameter I am not too familiar with ArcPy/Python, but since some commands are only available in ArcGIS, I try to implement my idea using ArcPy. I want to use a command several times, but each time only with a small change of a variable (distance) and the resulting output name.
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D100.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "10 Meters", "DIST_100")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D050.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "5 Meters", "DIST_050")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D040.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "4 Meters", "DIST_040")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D030.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "3 Meters", "DIST_030")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D020.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "2 Meters", "DIST_020")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D010.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "1 Meters", "DIST_010")
arcpy.SpatialJoin_analysis(outSP, outSP, inLAS[:-4] + '_D005.shp', "JOIN_ONE_TO_ONE", "KEEP_ALL","#", "WITHIN_A_DISTANCE_3D", "0.5 Meters", "DIST_005")

Since this does not look very nice in the code, I would like to optimize/compact the code. My idea was to do this with a list:
dist_list = (0.5, 1, 2, 3, 4, 5, 10)
    for n in dist_list:
    expression = "outSP, outSP, inLAS[:-4] + '_D' + str(int(n * 10) + '.shp', 'JOIN_ONE_TO_ONE', 'KEEP_ALL','#', 'WITHIN_A_DISTANCE_3D', n ' Meters', 'DIST_' + int(n * 10)"

Unfortunately I only get error messages that my command is not correct. I suppose it is related to the composition of the expression in which I combine the list items with the remaining strings.
I multiply the list item by 10 so that I don't get a second dot in the file name.
Is there someone who can tell me how to fix this problem?

A: expression is a string that spatial join will not understand. It wants comma separated parameters.
Replace expression = with arcpy.SpatialJoin_analysis( and remove the double quotes in the beginning and end. You should include the parameter names to be sure you are providing the correct one in correct place, for example target_features=
dist_list = (0.5, 1, 2, 3, 4, 5, 10) #btw (1,2,3) is a tuple, list: [1,2,3]. Does not matter in this case though.
for n in dist_list:
    arcpy.SpatialJoin_analysis(target_features=outSP, join_features=outSP,...


text:
Q: Group by on a really long query? My query because it's mandatory to add COD and DES on GROUP BY when I used them on CASE WHEN:
Select SUM(UNIVERSO)
CASE WHEN A.COD IN  ('A','B') THEN 5
  WHEN A.DES IN  ('D','E') THEN 5
END UNIVERSO,
FROM TABLEX
GROUP BY A.COD, A.DES

The result I'm getting:
The two columns at the right are "hidden" as I didn't write them on select but appear on group by
UNIVERSO [ COD  DES
    5       A    D
    5       B    E
  100       C    M ]

What I want:
UNIVERSO
  110

I don't need the resulting rows of the code (i have the right quantity on columns though), neverthless I do need the conditions on case when.
I thought on making another group by outside the whole table but it's really long (even to do it as a temporary table). Maybe there's another command I do not know about

A: Given your confirmation that you're aggregating on UNIVERSO, you can achieve what you're after with something like this (Note that the 'UNIVERSO' needs to be placed with the SUM(CASE WHEN) statement to get the result you appear to be after):
SELECT SUM(CASE WHEN A.COD IN ('A','B')
    THEN 0
    WHEN A.DES IN ('D','E')
    THEN 0
    ELSE UNIVERSO END) as UNIVERSO_AGG,
FROM TABLEX
GROUP BY A.COD, A.DES
HAVING SUM(CASE WHEN A.COD IN ('A','B')
    THEN 0
    WHEN A.DES IN ('D','E')
    THEN 0
    ELSE UNIVERSO END) > 0


text:
Q: Changing words used on 'No Results' Page I want to change the words 'bike', 'shed' and 'bike shed' on my 'Your search yielded no results' Drupal page. Is there anyway I can do this without editing the Drupal core? If I do have to edit the Drupal core, what file would I edit?
Any help on this appreciated.

A: If you are just wanting to replace text with other static text, take a look at the String Overrides Module.  From the project page:

Provides a quick and easy way to replace any text on the site.
Features

*

*Easily replace anything that's passed through t()

*Locale support, allowing you to override strings in any language

*Ability to import/export *.po files, for easy migration from the Locale module

*Note that this is not a replacement to Locale as having thousands of
  overrides can cause more pain then benefit. Use this only if you need
  a few easy text changes.


text:
Q: Rectangle in QML that is transparent, except for the borders Is there a way in QML to create a Rectangle with opacity: 0 that still have visible borders? If not, any suggestions on how to work around it?
Thanks

A: No, opacity is applied for complete visual aspect of item (and opacity:0 makes item full invisible). If you want rectangle with borders and without background, use "transparent" as color.
Rectangle { border.color: "black"; color: "transparent" }


text:
Q: Nobody in Big Town I've saved Red and Shorty, brought them back to Big Town, healed Timebomb and fixed the Sentry Bot. Then I went exploring further.
After some time, when I traveled back to the city, there was the Sentry Bot and a Protectron, but nobody else. Almost immediately about 5 Super Mutants attacked, so I shot them. But there is noone around aside from the bots. All the buildings are empty and there are no bodies.
I want my Lucky-8-Ball!
Anyone has any tips?

A: Try waiting in Megaton for a week and coming back, they may find their way back, if they are alive.
If you're on PC, you can use

prid 0002805b
moveto player

in the console to move Timebomb to your position

A: Big Town is notorious for being the victim of random creature attacks. If the creature killed the people and the robots killed the creature you will not see evidence unless the bpts are missing health (assuming they even got hit). The muties were caused by you fast traveling there and probably were not the cause of their deaths.


text:
Q: What does LoadWithPartialName("Microsoft.SharePoint") in PowerShell script do? I'm learning Powershell, I have this line at the top of example script, but it doesnt appear to be necessary. What does it do? Why would it be there?
# SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

For example this example script to get content types works if the above line is commented out.
# SharePoint DLL
# COMMENTED [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Cmdlet Install
 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# Get content types in a site collection.
# ----------------------------------------
function GetContentTypesInSite()
{
    $site = new-object Microsoft.SharePoint.SPSite($SiteURL)

    $web = $site.rootweb.ContentTypes
    ForEach ($id in $web)
    {
         '"' + $id.Name + $id.Id + '"'  | Out-File $OutputFile -append
    }
}

$SiteURL = "http://server:33333"
$OutputFile = "C:\temp\contenttypes.txt"
GetContentTypesInSite

I'm using the Windows PowerShell ISE to run the scripts

A: This used to be the way to load the sharepoint c# library in sharepoint 2007
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

In sharepoint 2010 this command does the same thing and more (adds 2010 commandlets)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

There is usually no harm in running both, and it gives you consistent includes across versions
And if you use the sharepoint powershell command line, it will do the includes for you


text:
Q: "Have the chance of" or "have a chance of" Which one is correct?

*

*Once you have a chance of reviewing the document, let me know what
you think.

*Once you have the chance of reviewing the document, let me know what
you think.


text:
Q: C Access 2D char array via Pointer I am trying to access a 2D array of chars. I have a pointer on right address but somehow dreferencing is not working.
    char ary[5][8];
char temp[8];
int i;

char **a_ptr = &ary;

    for(i=0; i<5; i++){
        sprintf(temp, "0x10%d" , i);
        strcpy(ary[i] , temp);
        printf("~~~%s@0x%x == 0x%x" , ary[i] , &ary[i] , (a_ptr + i));

    }

    for(i=0; i<5; i++){//This wont work.
        printf("~~~%s@0x%x" , *(a_ptr + i) ,  (a_ptr + i));

    }

Below is the output of this fucniton before it breaks to derefence the pointer.
Output Format : Value@Address
0x100@0x5fbff408 == 0x5fbff408
0x101@0x5fbff410 == 0x5fbff410
0x102@0x5fbff418 == 0x5fbff418
0x103@0x5fbff420 == 0x5fbff420
0x104@0x5fbff428 == 0x5fbff428

As we can see in above output that array values are filled correctly and a_ptr is pointing to correct addresses (&ary[i] == (a_ptr + i)).
But when the pointer is deference then it breaks there. Even using the [] operators does the same.
*(a_ptr + i); //Breaks
a_ptr[i]; //Breaks as well

However, (a_ptr + i) points to the right address.
Thanks,

A: char **a_ptr = &ary; - this makes no sense. char** a_ptr is a pointer to a pointer. What you need is a pointer to an array. The following will do:
char (*a_ptr)[8] = ary; // also don't take the address of the array

If you're trying to print the pointer address, printf has a format for this %p. Replace your 0x%xs with %p.
I've edited your code as follows and my compiler no longer issues warnings:
#include <stdio.h>
#include <string.h>

int main()
{
    char ary[5][8];
    char temp[8];
    int i;

    char (*a_ptr)[8] = ary;

    for(i=0; i<5; i++)
    {
        sprintf(temp, "0x10%d" , i);
        strcpy(ary[i] , temp);
        printf("~~~%s@%p == %p" , ary[i] , &ary[i] , (a_ptr + i));

    }

    for(i=0; i<5; i++)
    {
        printf("~~~%s@%p" , *(a_ptr + i) ,  (a_ptr + i));
    }

    return 0;
}

And now my output is:
$ ./a.out
~~~0x100@0xbfc77a74 == 0xbfc77a74~~~0x101@0xbfc77a7c == 0xbfc77a7c~~~0x102@0xbfc77a84 == 0xbfc77a84~~~0x103@0xbfc77a8c == 0xbfc77a8c~~~0x104@0xbfc77a94 == 0xbfc77a94~~~0x100@0xbfc77a74~~~0x101@0xbfc77a7c~~~0x102@0xbfc77a84~~~0x103@0xbfc77a8c~~~0x104@0xbfc77a94

Is this what you were hoping to get?
Some code that relies only on pointers and no arrays:
#include <stdio.h>
#include <string.h> /* for strcpy */
#include <stdlib.h> /* for free and malloc */

int main()
{

    char** two_d = malloc(sizeof(char*) * 5); /* allocate memory for 5 pointers to pointers */

    int i;
    for(i = 0; i < 5; i++) /* for each of the five elements */
    {
        two_d[i] = malloc(2); /* allocate memory to each member of two_d for a 2 char string */

        strcpy(two_d[i], "a"); /* store data in that particular element */

        printf("%s has address of %p\n", two_d[i], &two_d[i]); /* print the contents and the address */

        free(two_d[i]); /* free the memory pointer to by each pointer */
    }

    free(two_d); /* free the memory for the pointer to pointers */

    return 0;
}


text:
Q: How do I write a Linq query that needs a subquery? I need to extract some information about support tickets from a database. Each ticket is associated with a medical imaging system, and each system may or may not have service cover associated with it. If it does, there may be multiple service cover entries, but only one that interests us.
I know this is not valid Linq, but what I would really like to do is the following...
var tickets = cxt.SupportTickets
  .Select( t => new {
    ID = t.ID,
    Customer = t.Customer.Name,
    var cover = t.System.CoverItems.FirstOrDefault(ci => // some query)
    CoverLevel = cover?.Level.Name,
    Expiry = cover?.Expiry.ToLongDateString()
  });

Is there any way to do this? I know that I could repeat the t.CoverItems.FirstOrDefault(...) bit for every bit of data I want from the cover, but apart from the absolutely awful code mess this would produce, it would be very inefficient, as it would need to do the same subquery multiple times for every ticket.
I thought about breaking it all up into a foreach loop, but then I couldn't see how to create the tickets collection. I can't create an empty collection and then add objects to it, as they are anonymous types, and I wouldn't like to think about how you would specify the generic type!
Anyone any ideas?

A: You could improve readability:
var tickets = cxt.SupportTickets
  .Select(t => new {
       Ticket = t,
       CoverItem = t.System.CoverItems.FirstOrDefault(ci => // some query)
    })
  .Select(x => new {
    ID = x.Ticket.ID,
    Customer = x.Ticket.Customer.Name,
    CoverLevel = x.CoverItem?.Level.Name,
    Expiry = x.CoverItem?.Expiry.ToLongDateString()
  });

A: You could use query notation instead to use let clause:
var query=from t in cxt.SupportTickets
          let cover = t.System.CoverItems.FirstOrDefault(ci => some query)
          select new {
                      ID = t.ID,
                      Customer = t.Customer.Name,
                      CoverLevel = cover?.Level.Name,
                      Expiry = cover?.Expiry//.ToLongDateString()
                     };

At the end is going to do the same that @TimSchmelter answer, but for things like that you can use let. Another thing, I'm almost sure ToLongDateString() method is not supported in EF.

A: I've tried this (If you wanted to develop a subQuery separately, because of SoC principle):
var innerQuery =  cxt.SupportTickets
                    .Where(artist => artist.coverId == SomeParameter)
                    .Select(artist => new {
                        artistId = artist.artistId,
                        artistCompleteName = artist.artistName,
                        artistMasterPiece = artist.CoverName
                    });

var tickets = cxt.SupportTickets
  .Where(
    t => innerQuery.Contains(t.coverId)
  )
  .Select( t => new {
    ID = t.ID,
    Customer = t.Customer.Name,
    var cover = t.System.CoverItems.FirstOrDefault()
    CoverLevel = cover?.Level.Name,
    Expiry = cover?.Expiry.ToLongDateString()
  });


text:
Q: Is it possible to deploy elasticsearch in Webfaction? I'd like to deploy elasticsearch (ES) at Webfaction server. I have 256MB of memory and running a Django app that takes about 100MB. I need to index about 10,000 records. Is it possible to run ES in a pool with about 128MB of memory?

A: For just 10K documents I would say yes, but the best way to know is to try it. Remember to set ES_HEAP_SIZE to something sensible like 64Mb or it could happen that ES will grow to much in memory and the processes will be killed by Webfaction.


text:
Q: EnvJS/Rhino, setTimeout() not working I currently set up EnvJS on my system (installed from here).
My end goal is to load a page let it's javascript process for a few seconds, and then read the dom to get the information of interest. However I can not get setTimeout() to work to save my life (Or JQuery for that matter).
I have a php script that starts the process:
...
$ENVJS_PATH = "/var/www/project/src/envjs";
$RHINO_JAR = "rhino/js.jar";
$INIT_SCRIPT = "init.js";
$output = shell_exec("java -jar $ENVJS_PATH/$RHINO_JAR -opt -1 $ENVJS_PATH/$INIT_SCRIPT");
echo "Response from javascript:
 $output";
...

the init.js file looks like:
load('/var/www/project/src/envjs/dist/env.rhino.js');
print("Loaded env.rhino.js
");

// temporarily commented out
//var url = "http://www.ken-soft.com";
//window.location = url;
//print("
Loaded "+url+"
");

// Problem starts here
var runAfterPause=function() {
  print("got here..."); // never gets called
  print(document.getElementById('some_id').innerHTML);
}
setTimeout(runAfterPause, 3000); //wait three seconds before continuing
// i have also tried setTimeout("runAfterPause()", 3000);
print("
End
");

Any knowledge on this would be much appreciated. Thanks.

A: Try env.rhino.1.2.js - and if the server OS hosting rhino is Ubuntu, then try sudo apt-get install rhino -- and call rhino -opt -1 ... instead of java -jar ...
Seems to run like this for me on Ubuntu 11.04, when ran directly on the shell - not sure if PHP's shell_exec may influence things or not..
EDIT: Indeed it is not really working; I looked through the source a bit, and could see that setTimeout relies on Timer.prototype.start = function(){};, which is apparently empty. Browsing further, the only thing that seems to deal with timing is Envjs.wait() - and using that, I can finally get a sort of a timed loop; however, note that it seems to be strictly single-threaded (synchronous) now:
print("loading " + 1.2);
load('env.rhino.1.2.js'); // takes a while ...
print("loaded " + 1.2);
console.log(window);

var c=0;
function timedCount() // like this, when setTimeout calls a string!
{
  c=c+1;
  print("c=" + c);

  if (c<10) // make a limit for the run of script:
  {
    var t;
    //~ t=window.setTimeout(timedCount(),100); // TypeError: fn is not a function, it is undefined.
    t=window.setTimeout("timedCount()",1000); // must have `t=...` - else it locks on return even w/ wait(0)!
    Envjs.wait(); // waits, but "timer error  undefined   TypeError: fn is not a function, it is undefined." if setTimout doesn't call string; wait(0) exits immediately
  } else Envjs.wait(0); // "reset": execute all timers and return; else here will be left hanging from previous wait()
}

// main:

timedCount();
//~ eval("timedCount()", null); // works the same

print("after timedCount()");

... and the results are:
$ sudo apt-get install rhino
$ wget https://github.com/thatcher/env-js

$ rhino -opt -1 test.js
loading 1.2
[  Envjs/1.6 (Rhino; U; Linux i386 2.6.38-11-generic; en-US; rv:1.7.0.rc2) Resig/20070309 PilotFish/1.2.13  ]
loaded 1.2
[Window]
a
c=1
c=2
c=3
c=4
c=5
c=6
c=7
c=8
c=9
c=10
after timedCount()

If I recall correctly, in a browser setInterval is asynchronous/multithreaded - indeed, in a browser JavaScript Shell 1.4, the almost same code:
var c=0;
function timedCount()
{
  c=c+1;
  print("c=" + c);

  if (c<10)  {
    var t;
    t=window.setTimeout("timedCount()",1000);
  }
}

timedCount();
print("after timedCount()");

produces:
c=1
after timedCount()
c=2
c=3
c=4
c=5
c=6
c=7
c=8
c=9
c=10

A: The callback method is defined after the assignation. Try putting it before setTimeout

A: print is a method of window.
It's used to print a page, with a printer...
There might be a conflict with it and your print method.

A: Here are 2 things i want you to try for debugging. At least visually i cannot see something wrong in yout code, unless someone see it.
first does your function work when you call it by itself? not inside the set Timeout
var runAfterPause=function() {
  print("got here...");
  print(document.getElementById('some_id').innerHTML);
}

// call function by it self
runAfterPause();

2nd try running it as an anonymous function inside your setTimeout;
var delay = setTimeout(function () {
   print("got here..."); // never gets called
   print(document.getElementById('some_id').innerHTML);
},3000);

this should help you debug your code and see where the error is.


text:
Q: [Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions Estoy aprendiendo Laravel y VueJs pero en este sencillo ejemplo me esta devolviendo un error la consola:
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.

El codigo es este:
<template>

Mensaje: {{ message }}

</template>

Porque me devuelve este error si este devolviendo data como un objeto?
Gracias

A: Como lo indica el error: La opción "datos" debe ser una función, Entonces, al definir un componente, data debe declararse como una función que devuelve el objeto de datos inicial.
<template>

Mensaje: {{ message }}

</template>

Documentación oficial sobre su duda y el por qué de la misma


text:
Q: Ideals and Kernels of Homomorphisms We know in group theory, a normal subgroup is the same with the kernel of a (group) homomorphism. The analogue of normal subgroups in ring theory are ideals.
We know that, the kernel of any (ring) homomorphism is indeed an ideal, and we can construct an (ring) homomorphism given an ideal.
My question is, given an ideal $I\subseteq R$, can we construct more than one (ring) homomorphism?

I guess we can, but I cannot come up with another (ring) homomorphism besides the canonical projection from $R$ to $R/I$ giving the kernel as $I$. Thanks for help.

A: The answer is that in general there are many such homomorphisms, but from a certain point of view the canonical projection $\pi:R\to R/I$ is essentially the only homomorphism with kernel $I$, in the following sense:
Canonical decomposition of ring homomorphisms:
Let $f:R\to S$ be a ring homomorphism, and consider the canonical projection $\pi:R\twoheadrightarrow R/\ker f$ and the inclusion $i:\text{im }f \hookrightarrow S$.
There exists a unique isomorphism $\tilde f:R/\ker f\to \text{im }f$ such that
$$f=i\circ\tilde f\circ\pi $$
i.e. the following diagram commute:
$\require{AMScd}$
\begin{CD}
R @>{f}>> S\\
@V{\pi}VV @AA{i}A\\
R/\ker f @>{\tilde f}>> \text{im }f
\end{CD}
(You may have called an equivalent result first isomorphism theorem, even if this formulation is slightly more general and insightful, in my opinion).
Now, if $f:R\to S$ is any ring homomorphism with $\ker f=I$, then $f$ is equal to the canonical projection $\pi:R\to R/I$ followed by an isomorphism and an inclusion. Hence any different ring isomorphism $\tilde f:R/I\to T$ where $T$ is a subring of any ring $S$ gives rise to a different ring homomorphism $f:R\to S$ with kernel $I$ (by composition with $\pi$ on the right and $i:T\hookrightarrow S$ on the left).
For example, if you consider the ideal $(0)$, all injective ring homomorphisms $f:R\to S$ have kernel $(0)$: therefore in general there are lots of such homomorphisms, even though they are all the same, in the sense specified above.
In fact the question is slightly more sophisticated: all these different homomorphisms are actually the same, up to relabeling elements and extending the codomain, so that often we can just ignore them. However, if we fix the codomain (in such a way that we cannot "cheat" anymore extending it or considering an isomorphic one), the different homomorphisms with kernel $I$ are still equivalent up to isomorphism, but the number of them can be an insightful source of "algebraic information"
For example, there are exactly two homomorphisms
$\mathbb{Q}[x]\to \mathbb{R}$ with kernel $(x^2-5)$, defined by sending $x$ respectively to $\sqrt{5}$ and $-\sqrt{5}$, but there is only one homomorphism $\mathbb{Q}[x]\to \mathbb{R}$ with kernel $(x^3-2)$ (defined by sending $x$ to $\sqrt[3]2$). These observations are crucial in field theory.


text:
Q: ImportantForAccessibility=false vs. ContentDescription=null There is an element I want TalkBack to skip when reading out lout the screen.
I can set it's contentDescription to null.
I also read about ImportantForAccessibility: indicates whether an element is visible or not to the Accessibility API.
Which other APIs are there?
Is it cleaner to use ImportantForAccessibility=false over contentDescription=null?

A: ImportantForAccessibility=false is used to hide any element from the accessibility tree, including buttons, content etc.
contentDescription=null is only useful for things like images (there may be other items I can't think of) that you want to hide as otherwise the Accessibility Tree will do it's best to find a suitable name for an item.
A prime example would be an ImageButton - if you use contentDescription=null then it will announce 'button' and the destination / button text. If you use ImportantForAccessibility=falseit would hide that item completely from the accessibility tree.
The best analogy I can come up with (if you are familiar with Web Standards) is that contentDescription is like an alt attribute or aria-labelledby attribute and ImportantForAccessibility=false is similar to aria-hidden="true".
One thing I would caution you on - other than decorative items you should not really be hiding items from the accessibility tree, just be careful that you are not giving a different experience to screen reader users (you didn't specify your use case, just wanted to hammer that point home).
Final thing - try it with TalkBack, testing it on a device is the quickest way to know if you got it right!


text:
Q: Demo code is throwing a out_of_range exception but I don't know why I am writing code in C++ to remove any two consecutive characters which are the same.
for example:

 - aa -> empty string
 - aabb -> empty string
 - abba -> aa -> empty string (as removal of 'bb' makes it 'aa')
 - abab -> abab (not possible)

#include <iostream>
using namespace std;

int main()
{
    int i;
    string s;
    bool match = true;
    getline(cin, s);
    while (match) {
        match = false;
        for (i = 0; i < s.length() - 1; i++) {
            if (s.at(i) == s.at(i+1)) {
                s.erase(i,2);
                match = true;
           }
        }
    }
    if (s == "") {
        cout << "Empty!";
    }
    else {
        cout << s;
    }
    return 0;
}

A: s.length() is unsigned and s.length() - 1 will be very big when s.length() is 0.
You should check if s.length() is zero before performing subtraction like this:
for (i = 0; s.length() > 0 && i < s.length() - 1; i++) {


text:
Q: jQuery mobile dialog box source code for Windows Phone? I was developing an app for windows phone. I was displaying html pages in my app. I wanna use jQuery mobile dialog box in my html pages. So, I went through jquerymobile.com. Since, am very new to this, I cant understand anything from that.
Can anyone please tel me what should i do to have jquery mobile dialog box in my html page ?

A: are you using jQuery mobile throughout your app? Or do you want just the dialog box?
If you are working with jQuery mobile, you can do this in markup only. Just have a look at the following code; this is the page you want your popup to appear (HTML):

Page Title

            Open dialog

Page Footer

This is your popup header

             This is your popup content
             Do something here

I have made a working example at jsfiddle:
http://jsfiddle.net/mwfire/qaNZD/
Do not forget to include all scripts and css, explained at "anatomy of a page" section of the documentation.
And have (again) a look at the documentation for options:
http://view.jquerymobile.com/1.3.2/dist/demos/widgets/dialog/


text:
Q: what meta-tags in the header of an (x)html page should be enough for SEO whitout overload it? what meta-tags in the header of an (x)html page should be enough for SEO whitout overload it?

A: A few years back, meta tags were important to search engine optimization. However, they've been abused and are generally ignored by almost all search engines (including Google, Yahoo and Live search).
The most important tags for SEO that you can include in your (X)HTML are the <title> and <meta name="description"...> tags.

*

*<title> should generally be what you'd want the search engine to name your page in it's listing.

*<meta name="description"...> can sometimes give the search engine a basic idea of how to describe your page when
indexing it.

However, using these two tags will not necessarily make a difference in increasing your site's visibility on a search engines listings. For more information on that aspect, Google has a nice section on SEO on their site.

A: <meta name="description"> can be used to display a short summary of the site in search engine results, although that's not strictly 'SEO'.
No others are necessary; in particular <meta name="keywords"> is a no-longer-relevant waste of your time.

A: Description tags though not critical for higher ranking are absolutely critical for true Search Engine Optimization. The goal is not solely to rank highly but to get traffic to your site and conversions. The Description since it is shown on the results is absolutely critical for that purpose. Title and Description are the key elements. Page content is the most critical.