Q: Code not working. Dropdown menu in Android This is the java file of the code followed by xml file.
The programs shows an error "Unexpectedly stopped working"
I cannot find the error through logCat also. Can someone suggest something ?
Java file:
package com.example.ui;

import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Tp extends ListActivity implements OnItemSelectedListener{

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

    String[] technology = {"PHP", "Ruby", "Java", "SQL"};
    ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
    final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
    spinnertech.setAdapter(adp);
    spinnertech.setOnItemSelectedListener(this);

}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    int position = arg0.getSelectedItemPosition();

    if(position == 0) {
        Toast.makeText(getApplicationContext(), " 0 selected",
                   Toast.LENGTH_LONG).show();
    } else if(position == 1) {
        Toast.makeText(getApplicationContext(), " 1 selected",
                   Toast.LENGTH_LONG).show();
    }

    else {
        Toast.makeText(getApplicationContext(), " extra selected",
                   Toast.LENGTH_LONG).show();}
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {

}

}

XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

    <TextView
    android:id="@+id/textView100"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<Spinner
    android:id="@+id/spinner"
    android:layout_width="248dp"
    android:layout_height="36dp"
    android:prompt="@string/title" />

</LinearLayout>

Here's the LogCat
05-25 16:33:31.270: D/AndroidRuntime(566): Shutting down VM

05-25 16:33:31.270: W/dalvikvm(566): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

05-25 16:33:31.289: E/AndroidRuntime(566): FATAL EXCEPTION: main

05-25 16:33:31.289: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ui/com.example.ui.Tp}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.os.Handler.dispatchMessage(Handler.java:99)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.os.Looper.loop(Looper.java:123)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.main(ActivityThread.java:4627)

05-25 16:33:31.289: E/AndroidRuntime(566):  at java.lang.reflect.Method.invokeNative(Native Method)

05-25 16:33:31.289: E/AndroidRuntime(566):  at java.lang.reflect.Method.invoke(Method.java:521)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

05-25 16:33:31.289: E/AndroidRuntime(566):  at dalvik.system.NativeStart.main(Native Method)

05-25 16:33:31.289: E/AndroidRuntime(566): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ListActivity.onContentChanged(ListActivity.java:245)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.Activity.setContentView(Activity.java:1647)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.example.ui.Tp.onCreate(Tp.java:18)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

05-25 16:33:31.289: E/AndroidRuntime(566):  ... 11 more

05-25 16:33:33.089: I/Process(566): Sending signal. PID: 566 SIG: 9

A: I guess problem in below statement
Toast.makeText(getApplicationContext(), " 0 selected",
                   Toast.LENGTH_LONG).show();

change to
Toast.makeText(this, " 0 selected",
                   Toast.LENGTH_LONG).show();

or
Toast.makeText(tp.this, " 0 selected",
                   Toast.LENGTH_LONG).show();

Edit:--------------------------------------------------------------------------
public class Tp extends Activity implements OnItemSelectedListener{

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

        String[] technology = {"PHP", "Ruby", "Java", "SQL"};
        ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
        final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
        spinnertech.setAdapter(adp);
        spinnertech.setOnItemSelectedListener(this);

    }

if this is not working then include listview in xml file.

A: This is your problem
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

If you are using ListActivity, your layout file R.layout.activity_tp must have a ListView with android:id="@android:id/list" attribute. Look here: http://developer.android.com/reference/android/app/ListActivity.html for example.


Q: Eclipse LDT doesn't run local Lua interpreter I have problem with Eclipse LDT. When I run my test Lua app, it executes just fine using JNLua inside JavaVM environment. But according to this tutorial, when I reference native lua.exe interpreter and set it in Run Configuration as Runtime Interpreter, Run Configuration disables Launch script: and nothing is executed. When I run a same script with a same native local Lua interpreter 5.1, everything works just fine.
So, what is the problem with LDT? Has anyone had the same experience?
EDIT
I've managed to run local lua.exe from Lua Development Tools stand-alone product, but still it doesn't work as Eclipse plug-in.

A: I'm not sure it's a bug.
I guess when you register your interpreter, you uncheck the checkbox : "Accept file as argument"
This mean LDT will not manage the file to launch (that's why the Launch script is disabled)
The standard lua interpreter support file as argument and -e option, so the two check box should be checked. (It's the default value)

A: It looks like a bug ... Would you mind filing it in the Koneki bug tracker?


Q: How do I calculate subtotals using onblur and javascript? How do I calculate subtotals for each row of a product listing by using an input text field to enter one of the numbers?
example:
colA    colB            colC

100 - [text input] = [calculated result]

880 - [text input] = [calculated result]

720 - [text input] = [calculated result]

130 - [text input] = [calculated result]
...

I'm sure this is fairly easy to do with Javascript, but I've looked and can't find a simple answer.  I'm not very familiar with Javascript so I need a simple solution.  Thanks in advance for all the help! :)

A: Welcome to StackOverflow!  In the future, you can probably get a good answer faster if you write your question more clearly.
You can use document.getElementById('id_of_text_input').value to get or set the value of any text input.  Note that you are using id, not name.
You can use parseFloat to get a read a string as a floating number value.
In order to attach a function to the onblur event, you can use the setAttribute function.
So, for example, if you have a text input with id colA and you want to subtract 100 from the value the user enters and save the result in a text input with id colB.
You could write code like this:
<html>
<head runat="server">
    <title></title>
</head>
<body>
    <input type='text' id='colA' />
    <input type="text" id='colB' />
</body>
<script type="text/javascript">
    var colA = document.getElementById('colA');
    var colB = document.getElementById('colB');
    colA.setAttribute('onblur',
    function () {
        var value = colA.value;
        var number = parseFloat(value)-100;
        colB.value = number;
    });
</script>
</html>

A: Very useful for me. Thanks, Daniel
If you want to calculate a percentage (5% for example) and use Jquery, you have to
    $(function(){
        $(".input-valorinicial").blur(function(){
            var valorinicial = document.getElementById('valorinicial');
            var fee = document.getElementById('fee');
            var value = valorinicial.value;
            var number = parseFloat(value)*5/100;
            fee.value = number;
        });
    });


Q: Manually sanitize SQL parameters I would like to run a script like:
CREATE LOGIN [me] WITH PASSWORD = @0

and run it like:
var createUserCommand = conn.CreateCommand();
createUserCommand.CommandText = script;
createUserCommand.Parameters.AddWithValue("@0", passwordDecrypted);

However, this throws:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
  Additional information: Incorrect syntax near '@0'.

From what I read online (nowhere official, just from SO answers/comments) it is not possible to use SQL parameters with DDL statements. Link to official docs for this are welcome!
OK. I do need this parametrized. As I see it, there are 2 options:

*

*I manually sanitize (.Replace("'", "''") => how can I do this best?

*I call into .NET to sanitize for me. However I assume this is not sanitized within ADO.NET, but just past to SQL Server, and sanitized there...

What would be the best approach?

A: All you need to escape is the single ' to 2 x '
commandText = string.Format("CREATE LOGIN [me] WITH PASSWORD = '{0}'", pass.Replace("'", "''"));

An alternative would be to create a stored procedure with a password parameter and use it to build a CREATE LOGIN string which you then sp_executeSQL.


Q: OpenCV. detectMultiScale() function return error I'm new to OpenCV. Took an example from official documentation. When I try to run the code, an error pops up. When you try to run the code, an error pops up when you call the function detectMultiScale ()
Mat image;
image = imread("1.jpg", CV_LOAD_IMAGE_COLOR);
imshow("cam", image);
// Load Face cascade (.xml file)
CascadeClassifier face_cascade;
face_cascade.load("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml");

// Detect faces
std::vector<Rect> faces;

Mat frame_gray;
cvtColor(image, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

Tell me how to solve this problem?
enter image description here

A: It is because of your xml file path, be sure about that your path directory is true. I checked your code in my pc and worked well. Search your "haarcascade_frontalface_alt2.xml" file in your pc and copy it to your code.
The same problem was also mentioned here


Q: Java. HSSF. Apache-poi. How to modificate code
My data is stored in a format(look down): [-] means a blank cell, on the right may
  be only 10 columns, after the space. Something like this:
     [string0] [-] [string1] [string2] [string3] .. [string10] [-]

How to change this code for:
1) obtain only [string0]
2) obtain only [string1] [string2] [string3] .. [string10] [-]
    try {

    FileInputStream file = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xls");

    //Get the workbook instance for XLS file
    HSSFWorkbook workbook = new HSSFWorkbook(file);

    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);

    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();

        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    list1.add(cell.getStringCellValue());
                    break;
            }
        }
        System.out.println("");
    }
    file.close();
    FileOutputStream out =
            new FileOutputStream("C:\\Users\\student3\\"+sfilename+".xls");
    workbook.write(out);
    out.close();

I don't know how to stop Iterator. He absorbs all..

A: If I am clear you just want to filter your first column string and rest seperately.
Why not you just use a simple counter for this:
 while(rowIterator.hasNext()) {
    Row row = rowIterator.next();
    String RowContent = null;
    Iterator<Cell> cellIterator = row.cellIterator();
    while(cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        RowContent=RowContent+cell.toString();
    }
    //Code for saving RowContent or printing or whatever you want for text in complete row
}

RowContent will give concatenation of each cells of a single row in each iteration.

A: Like you did in the switch block with "break".
But what i think you want is this:
Iterator<Cell> cellIterator = row.cellIterator();
boolean stop = false;
while(cellIterator.hasNext()) {

  Cell cell = cellIterator.next();

  switch(cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
      System.out.print(cell.getStringCellValue() + "\t\t");
      list1.add(cell.getStringCellValue());
      stop = true;
      break;
  }

  if (stop) {
    break;
  }
}

This would stop the while loop when you found a string cell and will then operate on the next row.
Make any possible condition you need to break the while loop. For example collect string columns and when you found the desired set stop to true, to get to the next row.

A: External Link: Busy Developers' Guide to HSSF and XSSF Features
Here is an example that should work.
Maven Dependencies:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

Code:
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class StackOverflowQuestion18095443 {

    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("Please specify the file name as a parameter");
            System.exit(-1);
        }
        String sfilename = args[0];
        File file = new File("C:\\Users\\student3\\" + sfilename + ".xls");
        read(file);
    }

    public static void read(File file) {
        try (InputStream in = new FileInputStream(file)) {
            HSSFDataFormatter formatter = new HSSFDataFormatter();
            Workbook workbook = WorkbookFactory.create(in);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                StringBuilder rowText = new StringBuilder();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellAsStringValue = formatter.formatCellValue(cell);
                    rowText.append(cellAsStringValue).append(" ");
                }
                System.out.println(rowText.toString().trim());
            }
        } catch (InvalidFormatException | IOException e) {
            e.printStackTrace();
        }
    }
}

As for terminating the iteration you can conditionally break from the loop. Or, you could also just not use an iterator. Notice that you can obtain a Cell from a Row using a named reference (this allows you to refer to a cell by name, such as "A2", just like you would in Excel) or simply by the column index within the row.


Q: How to populate additive field via JOIN with Doctrine Suppose i have an entity with a ManyToOne relation (with EXTRA_LAZY) and obviously a join column.
eg. Article (main entity) -> Author (external entity)

suppose i add  a field author_name to the Article that NOT mapped to the ORM and that in certain contexts this field should contain the article->author->name value (usually it can stay null).
When i query a list of articles, i would like to populate automatically that article-author_name without implementing a getter that perform a select on each element of the query result. I would like Doctrine to fetch and hydrate that value in with a simple JOIN in the original query...
I don't want to set fetch mode to EAGER for performance as in my project Author is a really complex entity.
Is this possible?
Thanks

A: Probably i've found a solution. Don't know if it is the best way to do it but it works.
I've added to the main class a field getter
public getAuthorName() {
  return $this->author->name
}

in my context this getter will only be called by a serializer in certain conditions.
In my repository code i have a special method (that i refactored so that any method could implicitly call it) to impose the population of the Article->author field when queried. The method simply use the querybuilder to add LEFT JOIN to the Author class and temporarily set FetchMode to EAGER on Article->author.
At the end a simple repository method could be this
public findAllWithCustomHydration() {
    $qb = $this->createQueryBuilder('obj');
    $qb->leftJoin("obj.author", "a")
       -> addSelect("a"); //add a left join and a select so the query automatically retrive all needed values to populate Article and Author entities
    //you can chain left join for nested entities like the following
    //->leftJoin("a.address", "a_address")
    //-> addSelect("a_address");

    $q = $qb->getQuery()
              ->setFetchMode(Article::class, "author", ClassMetadata::FETCH_EAGER);
   //setFetchMode + EAGER tells Doctrine to prepopulate the entites NOW and not when the getter of  $article->author is called.
   //I don't think that line is strictly required because Doctrine could populate it at later time from the same query result or maybe doctrine automatically set the field as EAGER fetch when a LEFT JOIN is included in the query, but i've not yet tested my code without this line.

    return $q->getResult();
}

The con is that you have to customize each query or better use a DQL / SQL / QueryBuilder for each method of the repo but with a good refactoring, for simple inclusion cases, you can write a generic method that inject that join on a field_name array basis.
Hope this help and add your answer if you find a better way.
PS. i've wrote the above code on the fly because now i'm not on my notebook, hope it works at first execution.


Q: class that extends AbstractGoogleJsonClient constructor expecting Builder, rather than 5 params from Android Developers  Tic Tac Toe client (Android), https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-android
there is....
public class Tictactoe extends AbstractGoogleJsonClient { etc}

with the constructor:
public Tictactoe(HttpTransport transport, JsonFactory jsonFactory,
      HttpRequestInitializer httpRequestInitializer) {

    super(transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer
       , false);
  }

I get compile errors on the super(), and I'm told that super expects Builder, not the 6 params,
BUT the class Tictactoe extends has a constructor that takes the 6 arguments.
(see
https://code.google.com/p/google-api-java-client/source/browse/google-api-client/src/main/java/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java?r=32555da5a2e95a90154f278184f3be9e230486b3 )
for
  protected AbstractGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory,
  String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer,
  boolean legacyDataWrapper) {
super(transport, httpRequestInitializer, rootUrl, servicePath, newObjectParser(
    jsonFactory, legacyDataWrapper));

}
So...
What's happening here?  Why does 'super' expect Builder rather than the 6 args?


Q: Android get unique firebase token and authenticate with cloud functions I'm building a multi-player Android game, and it uses Firebase Cloud Functions.
There are some tutorials that explains how to allow only users of my application to use my cloud function (link below), but I don't want to allow all the users to use all my functions, I want to give access based on Id. How to generate unique tokens for every user, from Android (Using Java not Kotlin) and how to get the Id from that token in node.js (Javascript not TypeScript)?
The tutorial link: https://firebase.google.com/docs/cloud-messaging/auth-server

A: Starting Firebase Functions 1.0+, there are 2 kinds of HTTP functions that you can use for your Android app.

*

*Call Functions directly. Via functions.https.onCall

*Call Functions through HTTP Request. Via functions.https.onRequest
I recommend you to use onCall as your functions endpoint, and call directly by using FirebaseFunctions. This way, you don't need to get FirebaseUser token, as it will be automatically included when you call using FirebaseFunctions.
And remember, TypeScript is just superset of Javascript. I will still give examples in Node.js, but it is recommended to type your Javascript code in TypeScript.
Example
index.js (CloudFunctions endpoint)
exports.importantfunc = functions.https.onCall((data, context) => {
   // Authentication / user information is automatically added to the request.
   if (!context.auth) {
       // Throwing an HttpsError so that the client gets the error details.
       throw new functions.https.HttpsError('not-authorised',
                         'The function must be called while authenticated.');
   }

   const uid = context.auth.uid;
   const email = context.auth.token.email;

   //Do whatever you want
});

MyFragment.java
//Just some snippets of code examples
private void callFunction() {
    FirebaseFunctions func = FirebaseFunctions.getInstance();
    func.getHttpsCallable("importantfunc")
            .call()
            .addOnCompleteListener(new OnCompleteListener<HttpsCallableResult>() {

                @Override
                public void onComplete(@NonNull Task<HttpsCallableResult > task) {
                    if (task.isSuccessful()) {
                         //Success
                    } else {
                         //Failed
                    }
                }
            });
}

More information about callable function, read here


Q: Getting smallest value from column that holds numbers as strings I'm saving numbers as strings because they are generally larger than the maximum limits MySQL allows for integers.
What I'm trying to get is the smallest and largest values from this column, but just comparing as strings returns very different results.
I've tried to add a CONVERT clause to my query like so:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CONVERT('end_timestamp', SIGNED INTEGER) DESC LIMIT 1"

But the result coming through is not correct. I think the CONVERT clause is not converting to integers in the way I was expecting it to.
So what is the best way to convert strings to integers and get the smallest value?

A: If you have a number as a string and it is an integer with no leading 0s, you can compare it by comparing the length first and then the value.  For instance, the following will order by col1 correctly (assuming the above):
select t.*
from t
order by char_length(col1), col1;

So, one way to get the minimum is:
select col1
from t
order by char_length(col1), col1
limit 1;

You can also get both in a group by by doing:
select substring_index(group_concat(col1 order by char_length(col1), col1), ',', 1
                      ) as mincol1,
       substring_index(group_concat(col1 order by char_length(col1) desc, col1 desc), ',', 1
                      ) as maxcol1
from t;

If you have zeros in front of the numbers and or decimal places, the ideas are the same, but the coding is a bit more complicated.

A: I don't have a MySQL instance to test on, but it looks like a workaround may solve your problem. I don't know that the issue here is the numbers are too large for conversion, but if they can't be integers in the database, why should it be possible to convert them to integers outside the database?
Try something like this:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CHAR_LENGTH(end_timestamp) DESC, end_timestamp DESC LIMIT 1"

That will sort by the number of characters first, which is where string sorts on numbers fall apart (as long as you don't have any leading zeros), followed by a numerical sort on numbers which are the same length. If that still doesn't work you may need to `SELECT CHAR_LENGTH(end_timestamp) AS ts_len' to calculate the value outside of the sort command. That is where I really don't know which will work because I don't have a MySQL instance available to test on.
You also may want to consider a data type more suited to timestamps, like TIMESTAMP or DATETIME, which could likely be converted to the format you need once they're outside the database.


Q: Debugger Visualizer and "Type is not marked as serializable" I am trying to create a debugger visualizer that would show control hierarchy for any Control. It's done but I'm getting the exception "Type  is not marked as serializable".
How do I overcome that? Control is a .NET Windows Forms framework type, I can't mark it as serializable.

A: You'll need to also implement a VisualizerObjectSource to perform custom serialization.
Example:
public class ControlVisualizerObjectSource : VisualizerObjectSource
{
    public override void GetData(object target, Stream outgoingData)
    {
        var writer = new StreamWriter(outgoingData);
        writer.WriteLine(((Control)target).Text);
        writer.Flush();
    }
}
public class ControlVisualizer : DialogDebuggerVisualizer
{
    protected override void Show(
        IDialogVisualizerService windowService,
        IVisualizerObjectProvider objectProvider)
    {
        string text = new StreamReader(objectProvider.GetData()).ReadLine();
    }
    public static void TestShowVisualizer(object objectToVisualize)
    {
        var visualizerHost = new VisualizerDevelopmentHost(
            objectToVisualize,
            typeof(ControlVisualizer),
            typeof(ControlVisualizerObjectSource));
        visualizerHost.ShowVisualizer();
    }
}
class Program
{
    static void Main(string[] args)
    {
        ControlVisualizer.TestShowVisualizer(new Control("Hello World!"));
    }
}

You'll also need to register the visualizer with the appropriated VisualizarObjectSource, which for this example could be something like this:
[assembly: DebuggerVisualizer(
    typeof(ControlVisualizer),
    typeof(ControlVisualizerObjectSource),
    Target = typeof(System.Windows.Forms.Control),
    Description = "Control Visualizer")]


Q: Continue on exception I get a few exceptions when I run my code.
What I want to do is, I want to continue on FileNotFoundException and NullPointerException and break on any other exception.
How can I go about it?
Thanks

A: try {
    stuff()
} catch( NullPointerException e ) {
   // Do nothing... go on
} catch( FileNotFoundException e ) {
   // Do nothing... go on
} catch( Exception e ) {
   // Now.. handle it!
}

A: You can do this as @daniel suggested, but I have some additional thoughts.

*

*You never want to 'do nothing'.  At least log the fact that there was an exception.

*catching NullPointerExceptions can be dangerous.  They can come from anywhere, not just the code where you expect the exception from.  If you catch and proceed, you might get unintended results if you don't tightly control the code between the try/catch block.

A: multiple catch block to caught exception arised in try block

try{

// Code that may exception arise.

}catch(<exception-class1> <parameter1>){

//User code

}catch(<exception-class2> <parameter2>){

//User code

}catch(<exception-class3> <parameter3>){

//User code

}

Source : Tutorial Data - Exception handling


Q: import file into skype for business calender I created a patient schedule file outside of Skype for business. I want to associate a patient with a selected physician. How can I import the file to the Skype for business calendar? What format should the imported file be?

A: Skype for Business does not support its own calendar. Instead, it gets calendar data from the Exchange account of the signed in user. You can easily add a new event to the user's calendar by using the Microsoft Graph RESTful API: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_post_events


Q: Replace a word in a sentence using preg_replace How can I replace a string like

style="color:red;width:90%;" class="textbox"

to

style="color:red;width:65%;" class="textbox"

using preg_replace?
I just want to replace "width:90%" with "width:65%" and the rest of the string should stay as it is. What regular expression should I use to accomplish this?

A: str_replace("width:90%", "width:65%", $string)

A: $string = preg_replace("/width:90%/", "width:65%", $string);

if you want to make sure only elements with the class="textbox" are affected:
$string = preg_replace("/(style=\".+)(width:90%)(.+class=\"textbox\")/", "$1width:65%$3", $string);

having it work with any value and unit:
$string = preg_replace("/width:(\d+)(%|px)/", "width:65($2)", $string);

A: Thanks a lot jairajs
this worked for me
preg_replace("/width:\d+(%|px)/", "width:65%", $string)

and thanks to Gerald Schneider for helping me out


Q: How to multiply index values looped in a list I get this error when I run my code however I had converted the data in my list to an int
I have been working on this for weeks and cannot figure it out
ValueError: invalid literal for int() with base 10: '95.7'
How can I by pass this error to get the total ,
import csv
counter = 0
sum = 0
avg = 0
with open('sales_data_sample (3).csv','r') as csv_file: # opens the csv
    csv_reader = csv.reader(csv_file)
    next(csv_reader) # skips the header so we can work only with raw data
    for  ((lines)) in csv_reader: # loop through all data in the file
        counter =+ 1 # counter
        lines[1] = int(lines[1])
        lines[2] = int(lines[2])
        avg = avg + (lines[1]* lines[2])
    total = avg/counter

A: I think the issue is in the data maybe somewhere in your data you have 95.7 and since you are converting it into int so that's why it is breaking your code. You should try
lines[1] = int(float(lines[1]))
lines[2] = int(float(lines[2]))

A: Your problem is you're using integers (whole numbers). Either your lines in the csv are not whole numbers, or when calculating total, you are dividing into decimals.
To solve this, you have to use a floating-point number. Replace your uses of integers with floats.
eg.
lines[1] = int(lines[1]) should become lines[1] = float(lines[1])
You will however find you start getting numbers with long decimal places, so you can round them with the round() function, like this:
lines[1] = round(float(lines[1]), '.2f') Which will set it to 2 decimal places. You can change that 2 to any number of decimal places you'd like.
lines[1] = round(float(lines[1]), '.2f')
lines[2] = round(float(lines[2]), '.2f')


Q: How to use OrderBy to sort a custom object ascending by Date I have a collection of a custom object as follows:
public struct Record {
    public string Caller { get; set; }
    public DateTime Started { get; set; }
    public string Dialed { get; set; }
    public decimal Duration { get; set; }
    public decimal Cost { get; set; }
    public string Location { get; set; }
    public Switch Switch { get; set; }
}

public static List<Record> Records { get; set; }

Using LINQ, how can I sort Records in ascending order using the value stored in Record.Started ?

A: Just use the OrderBy method:
Records.OrderBy(record => record.Started)

or:
from r in Records
order by r.Started
select r

A: Could it be this easy?
records.OrderBy(r=>r.Started)


Q: Unable to extract key-value pairs from BigQuery table which has arrays and structs I have integrated Firebase analytics data with google BigQuery and everyday a new table gets created with the DATE stamp.
one sample table is "projectID.com_dev_sambhav_ANDROID.app_events_20170821"
One sample table is shown below
sample table
My requirement is to get result in the below desired format for event_dim.name="notification_received"
desired output
To get this desired output I execute the below query(standardSQL)
SELECT event.name
 (SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="notification_title") as notification_title,
 (SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"

But I got this error

Error: Each function argument is an expression, not a query. To use a
  query as an expression, the query must be wrapped with additional
  parentheses to make it a scalar subquery expression.

can anybody help me get out of this problem

A: The problem is a comma and an alias. This query works:
#standardSQL
WITH `projectID.com_dev_sambhav_ANDROID.app_events_2017` AS(
  SELECT ARRAY< STRUCT<date STRING, name STRING, params ARRAY< STRUCT<key STRING, value STRUCT<string_value STRING> > > > > [STRUCT('20170814' AS date, 'notification_received' AS name, [STRUCT('notification_title' AS key, STRUCT('Amazing Offers two' AS string_value) AS value ),
                                                                                STRUCT('firebase_screen_class' AS key, STRUCT('RetailerHomeActivity' AS string_value) AS value),
                                                                                STRUCT('notification_id' AS key, STRUCT('12345' AS string_value) AS value),
                                                                                STRUCT('firebase_screen_id' AS key, STRUCT('app' AS string_value) AS value),
                                                                                STRUCT('item_id' AS key, STRUCT('DEMO-02' AS string_value) AS value),
                                                                                STRUCT('firebase_screen' AS key, STRUCT('My Order' AS string_value) AS value)] AS params)] event_dim
)

SELECT
 event.name,
 (SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="notification_title") as notification_title,
 (SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"

If you UNNEST the field event_dim and call it event, then you should use this alias as reference in your query.
As a complement, here's another way of solving your problem as well (it's just another possibility so you have more techniques in your belt when working with BigQuery):
#standardSQL
SELECT
  (SELECT date FROM UNNEST(event_dim)) date,
  (SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'notification_title') AS notification_title,
  (SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'item_id') AS item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_2017`
WHERE EXISTS(SELECT 1 FROM UNNEST(event_dim) WHERE name = 'notification_received')

When processing up to terabytes you may find this query still perform quite well.


Q: shortcut for creating an javascript object from an array of objects using lodash I often have an array of objects and want to make it into an object of objects by keying on a specific key of the contained objects.
Currently I'm doing something like:
_.zipObject(_.pluck(results, '_id'), results);
However, this is such a common thing I wondered if there's a shortcut to do this using Lodash / underscore.
Anyone?

A: You are looking for  _.indexBy() http://lodash.com/docs#indexBy
Example from the docs:
var keys = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];

_.indexBy(keys, 'dir');
// → { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }


Q: Setting the name of cells inside a vba function While inside a VBA function I'm attempting to change the name of certain cells to flag them and use them later. I have a searching function that searches excel docs for keywords from a .txt file and need to know which cells don't include any of the search terms. To do this I was going to name each cell I query and include all unnamed cells in the results column for "Other". But whenever I try to name a cell the name doesn't get updated. I've tried the following:

ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange

and

foundRange.name = "QUERIED"

The function is here:
Function Single_word_occurrences(datatoFind As String, resultsCol As String) As Integer
    'Initializations
    Dim strFirstAddress As String
    Dim foundRange As Range
    Dim currentSheet As Integer, sheetCount As Integer, LastRow As Integer, loopedOnce As Integer, FoundCount As Integer

    FoundCount = 0
    currentSheet = ActiveSheet.Index
    sheetCount = ActiveWorkbook.Sheets.Count

    Sheets("Sheet1").Activate
    Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=Cells(2, 6), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Sheets("List Results").Cells(1, resultsCol).Value = datatoFind
    'if datatoFind is found in search range
    If Not foundRange Is Nothing Then
        'save the address of the first occurrence of datatoFind, in the strFirstAddress variable
        strFirstAddress = foundRange.Address
        Do
            'Find next occurrence of datatoFind
            Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=foundRange.Cells, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
            'Place the value of this occurrence in the next cell down in the column that holds found values (resultsCol column of List Results worksheet)
            LastRow = Sheets("List Results").Range(resultsCol & Rows.Count).End(xlUp).Row + 1
            Sheets("List Results").Range(resultsCol & LastRow).Value = foundRange.Address
            ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange
            If loopedOnce = 1 Then
                FoundCount = FoundCount + 1
            End If
            If loopedOnce = 0 Then
                loopedOnce = 1
            End If
            'The Loop ends on reaching the first occurrence of datatoFind
        Loop While foundRange.Address <> strFirstAddress And Not foundRange Is Nothing
        Msgbox(foundRange.Name)
    End If
    Single_word_occurrences = FoundCount
    Application.ScreenUpdating = True
    Sheets(currentSheet).Activate
End Function

A: You can't Define a Name in a UDF
you must use a sub
the following will fail:
Public Function qwerty(r As Range) As Variant
    qwerty = 1
    Range("B9").Name = "whatever"
End Function


Q: httplib post call error I am trying to automate few http requests where, I have following POST call data which i captured from the web :
Method: POST
Request Header :
POST /cgi-bin/auto_dispatch.cgi HTTP/1.1
Host: 10.226.45.6
Connection: keep-alive
Content-Length: 244
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhwDXAifvLs48E95A
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Referer: http://10.226.45.6/auto_dispatch.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,kn;q=0.6
Cookie: TWIKISID=dce9a6aa10e33b708f5bbc2912f781ab
payload :
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="taskid"
123
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="Submit"
Submit Form
------WebKitFormBoundaryhwDXAifvLs48E95A--
MY script is as follows :
  import httplib, urllib
     def printText(txt):
      lines = txt.split('\n')
         for line in lines:
           print line.strip()

     params = urllib.urlencode({'@taskid': 12524, '@Submit': 'Submit Form'})
     headers = {"Content-type": "multipart/form-data", "Accept":       "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
     conn = httplib.HTTPConnection("10.226.45.6", 80)
     conn.request("POST", "auto_dispatch.html", params, headers)
     response = conn.getresponse()
     print response.status, response.reason
     printText (response.read())
     conn.close()

I am getting the following error :
400 Bad Request

400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.
Please help me to form a proper request .

A: I Tried with the curl commands which worked for me :
curl --request POST 'http://10.226.45.6/cgi-bin/auto_dispatch.cgi HTTP/1.1' --data 'taskid=111&submit=submit'
curl --request POST 'http://10.226.45.6/cgi-bin/auto_free.cgi HTTP/1.1' --data 'submit=submit'


Q: Socket connection only when needed I have a web application that needs to refresh some values often because the changes have to be available almost in real time. To do this, I run via ajax a refresh.php routine every 15 seconds, which returns the updated information. Time that increases if there is no user activity.
I thought about the possibility of creating a service-worker in the browser (since I already use it for pwa too), and in it create a web-socket, and then only when there is an update on the server, create a socket for the ip's of the users that are logged in (and saved in a db), just to send to the user's browser that there is an update, then the web-socket triggers the javascript routine that connects to the server and does the update.
I do not know if it would be possible to create the socket just to inform that there is an update, because in this case, I do not want to leave the socket open, creating the connection only when there is an update of the information, which should happen to several users.
Has anyone ever needed or done anything like this, or would you have any other ideas?


Q: Sorting in Linux I have a string "abc" and I am greping it in 15 files in my directory in shell.
When I grep "abc" in my 15 files than it returns me the whole line of the files in which its present like this:
abc 0.2  9.0
abc 0.01 8.0
abc 0.06 9.4
abc 0.02 8.7

Now I want this output to be sorted in ascending order according to the second column.
So I wrote the command like this:
grep "abc" *.txt | sort -nr -t_ -k2

but the above command is not working and I don't know why.

A: Your command is not working because you don't have underscores separating the columns; further, you wanted the data ascending but you told it to sort in reverse (descending) order.  Use:
grep "abc" *.txt | sort -n -k 2

Or:
grep "abc" *.txt | sort -k 2n

Note that if there are multiple files, your grep output will be prefixed with a file name.  You will have to decide whether that matters.  It only screws things up if there are spaces in any of the file names.  The -h option to grep suppresses the file names.

A: I suggest to delete -t_ parameter, because as I see you use spaces as separator, not underscore. After that it works for me:
$ cat t | sort -n -k2
abc 0.01 8.0
abc 0.02 8.7
abc 0.06 9.4
abc 0.2  9.0

Updated: and yes, as @jonathan-leffler said you also should omit -r option for sorting in ascending order.

A: You can replace your entire script, including the call to grep, with one call to awk
awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt

Example
$ ls *.txt
four.txt  one.txt  three.txt  two.txt

$ cat *.txt
abc 0.02 8.3
foo
abc 0.06 9.4
bar
blah blah
abc 0.2  9.0
blah
abc 0.01 8.0
blah
abc 0.02 8.7
blah blah

$ awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt
abc 0.01 8.0
abc 0.02 8.3
abc 0.02 8.7
abc 0.06 9.4
abc 0.2  9.0

A: First problem: you've used -t_ to specify the field separator, but the output doesn't contain _ characters.
Next problem: the -k option has two arguments, start field and end field. By omitting the end field, you get end_of_line by default.
I'd suggest writing it like this:
grep "abc" *.txt | sort -nr -k2,2


Q: How to eliminate elements of a vector according to a pattern I have this vector:
a <- c("es1", "es2", "es3", "is1", "is2", "is3")

and i would like to eliminate all elements staring with "es", so it ends up looking like this:
b <- c("is1", "is2", "is3")

Thanks everyone!

A: If you want to remove all words that contain "es", try
b <- a[-grep("es", a)]

If you want to remove only the words that starts with "es", try
b <- a[-grep("\\bes\\w+", a)]


Q: Toast in not showing in asynctask I am trying to get message from the server to show in toast but it does not appear. The client receives the message from the server without any errors.I have tried opening UI thread in onpost but it didn't work
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    new test().execute();

}
public class test extends AsyncTask<String,String,String>{

    @Override
    protected String doInBackground(String... params) {

        try
        {
            socket = new Socket("ip", port);
            OutputStream outToServer = socket.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            Log.i(debugString, "Connected_reg!");
            out.writeUTF("3");

            InputStream inFromServer = socket.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            Log.i(debugString, in.readUTF());
            string= in.readUTF();

        }
        catch (Exception e) {
            Log.e(debugString, e.getMessage());
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {

       //super.onPostExecute(s);

                Context context = getApplicationContext();
                CharSequence text = string;
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
    }

}

A: It might be to do with the context.
I've had issues in the past with getApplicationContext not working for certain things, although can't remember what form the top of my head.
Instead of using getApplicationContext, in the activity where you call your async task put this in the constructor call. For example, assuming you are going from MainActivity change the line new test().execute(); to new test(MainActivity.this).execute();
Then in the async class create the constructor as
public test(Context context) and set a global class variable to be the value of context, and then use this in your toast.makeText instead of what is returned from getApplicationContext.
Also take a look in the logcat, see if there are any errors or exceptions being thrown, it might also be worth adding a log line in the onpostexecute method just to double check you're definetely going in there.

A: Create a constructor in the test class which receive a context and use that context in the Toast.makeText. Pass the host activity context to that constructor.
getApplicationContext() is a Context class method, AsyncTask does not inherent from that class. I suppose you are in a scope where you can invoke that method but that scope context is not valid in the scope that you are invoking the Toast.makeText method.


Q: best way to access a windows service via GUI I'm curious about the best way for a C# gui to access the functions of a Windows Service, be it WCF or ServiceController or some other option.
I'll explain what I'm doing: on a regulated time interval the service will be zipping one hours worth of datafiles from location A and sending the zipped file to location B, this will be done in the background 24/7 or until the service is stopped by the user and runs even when no one is logged in (hence the need for service) I would like the user to be able to pull up a GUI program that will allow them several options:
1) change the location to zip from
2) change the location to zip to
3) manually start the zipping process for a DateTime range specified
Now most of the functions for zipping and timers is all stored within the service. SO im wondering if a ServiceController in the GUI program would allow me to send variables to/from the service (ie folderpath names as strings, various other data) or if I'll need to spend the time making a WCF and treat the GUI as the Client and the Windows service as a source.
It should be noted the GUI will likely recieve data from the service, but only to signify if it is currently busy zipping.

A: One option is to tave a WCF service embedded on your windows service. With this WCF you can control the behaviour without restarting the service.
But the best option IMO is to have this in a config file. You can add some keys, but you would have to restart the service when you update the config.
In this case you can try a workaround, as in this thread.
The config is a good place for this kind of detail, because it can be easily modified and, unlike a database, it will be always avaiable.

A: I don't fully understand what you're trying to say, but you define what the interface to your service is when you make it.  If the operations you define take in variables, then you can pass data from your application to the service.
From what you described, just make opertaions in the service to do those 3 things you listed then call those from a button click in your UI code.
WCF would be fine for this here's a basic introduction to it http://msdn.microsoft.com/en-us/library/bb332338.aspx.


Q: Sticky Table two header using CSS for all OS i have two table headers and i want to sticky it using CSS only. Here is my html, and also posted image of my table, i have all the dynamic data and columns.

                    test11
                    test12
                    test13

                    test21
                    test22
                    test23

                    data1
                    data2
                    data3

                    data1
                    data2
                    data3

                    data1
                    data2
                    data3

How can I make the headers sticky using only CSS?

A: Try below css. You have to change top: 20px; with height of .first_head.
.fix-table-paren thead .first_head th{ position: sticky; top: 0; }
.fix-table-paren thead .second_head th{ position: sticky; top: 20px; }


Q: How can i Tlit the layout from Left to Right? I want to know about the Layout which can be Tlit from Left to Right. please give me any suggestion for help out me.

A: You can create .xml layouts for when the phone is placed horizontal or vertical. To create a horizontal layout, simply create a new .xml file and check that you would like the layout to be horizontal.


Q: URL gives 404 ..Angularjs I'm having issue with my url..i actually was trying to remove # tag from my url..which is done but the problem is now if i'm having url like this

http://localhost/xyz

it redirects me to

http://localhost/xyz/home

but the if i try and refersh the same page

http://localhost/xyz/home

it gives 404
any one knows how to solve it..
Thanks.

A: so actually now i'm able to open http://localhost/xyz/home directly with url rewrite which will point to my index.html.but now the bigger issue is whenever i'm trying to run my project it says unable to start debugging and none of my service is getting called it says 405(metod not allowed).i tried iisrest.but no luck.
so if you have any ideas,please share and thank you.


Q: What are the differences between OLEDB/ODBC drivers when connecting to SQL Server? I have an SQL Server database, and I need to push data into it through vbscript, as well as pull data into Excel. I have found multiple connection strings, but no repository for the benefits of performance and functionality comparing them. The driver options (Provider=) I have found so far are:

*

*{SQL Server} (ODBC)

*SQLOLEDB (newer than ODBC, but being deprecated?)

*SQLOLEDB.1 (what Excel 2016 uses when clicking 'Get External Data', but not even mentioned on connectionstrings.com... I assume a newer version of the above, but still the deprecated technology?)

*SQLNCLI11 (native client, OLE DB)

*{SQL Server Native Client 11.0} (native client, ODBC)

Different things I read say that ODBC is better because it has been around longer. And that OLE DB has been around long enough to have the same advantages. And OLE DB was made to work with a certain company's applications. And ODBC was made by the same company. And OLE DB can connect to and from different kinds of applications better. And ODBC works better with databases. And Native is...Native, so must be better... because of the name?
I find multiple questions here on SO floating around with no or partial answers, or having multiple comments claiming the answers are out of date. So, as of now, what the specific differences between these different drivers? Do they have different performance in different circumstances? Do they have different features? Do I need to do profiling to determine the best performance and reliability for my particular use case, or is there a standard "best practice" recommended by Microsoft or some recognized expert? Or are they all basically doing the same thing and as long as it's installed on the target system it doesn't really matter?

A: ODBC-it is designed for connecting to relational databases.
However, OLE DB can access relational databases as well as nonrelational databases.
There is data in your mail servers, directory services, spreadsheets, and text files. OLE DB allows SQL Server to link to these nonrelational database systems. For instance, if you want to query, through SQL Server, the Active Directory on the domain controller, you couldn't do this with ODBC, because it's not a relational database. However, you could use an OLE DB provider to accomplish that.
http://www.sqlservercentral.com/Forums/Topic537592-338-1.aspx


Q: How to initialize and set a 2D array in golang I am trying to simplay make a 2D array as a field on an object. I want a function that creates the object and returns it. But when trying to create the 2d array it returns a single array.
type Struct struct {
    X int
    Y int
    Grid [][]bool
}

func NewLifeSimulator(sizeX, sizeY int) *Struct{
    s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX,sizeY),  //Creates a regular array instead of 2D
    }
    return s
}

What do I need to change so that my function initializes a 2D array?

A: The expression:
make([][]bool, sizeX)

will create a slice of []bools of size sizeX. Then you have to go through each element and initialize those to slices of sizeY. If you want a fully initialized array:
s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX),
    }

// At this point, s.Grid[i] has sizeX elements, all nil

for i:=range s.Grid {
   s.Grid[i]=make([]bool, sizeY)
}

The expression make([][]bool, sizeX, sizeY) creates a [][]bool slice with initial size sizeX and capacity sizeY.


Q: yarn workspaces monorepo with vite, react, tailwind - VS Code fails to resolve packages I have created a monorepo using yarn@3 workspaces.
My root package.json:
{
  "name": "hello-yarn-workspaces",
  "packageManager": "yarn@3.1.1",
  "workspaces": [
    "apps/*",
    "packages/*"
  ],
  "devDependencies": {
    "@commitlint/cli": "^16.0.1",
    "@commitlint/config-conventional": "^16.0.0",
    "husky": "^7.0.4"
  },
  "scripts": {
    "postinstall": "husky install",
    "prepublishOnly": "pinst --disable",
    "postpublish": "pinst --enable"
  }
}

The package.json in apps/ui:
{
  "name": "ui",
  "packageManager": "yarn@3.1.1",
  "scripts": {
    "dev": "vite"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@tailwindcss/forms": "^0.4.0",
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "@vitejs/plugin-react": "^1.1.3",
    "autoprefixer": "latest",
    "postcss": "latest",
    "tailwindcss": "latest",
    "typescript": "^4.5.4",
    "vite": "^2.7.10"
  }
}

I have created a component inside my apps/ui/src folder and when I run yarn workspace ui run dev, the app can be started in the browser.
However, when opening my monorepo in VS Code, it fails to resolve npm packages in import statements:
// Cannot find module 'react' or its corresponding type declarations.ts(2307)
import React, { ReactElement, useState } from 'react'

The same happens for the vite.config.ts in apps/ui
// Cannot find module 'vite' or its corresponding type declarations.ts(2307)
import { defineConfig } from 'vite'
// Cannot find module '@vitejs/plugin-react' or its corresponding type declarations.ts(2307)
import react from '@vitejs/plugin-react'

When opening the monorepo in WebStorm, everything is ok.
The repro repository can be found here.
Update: It looks like it is related to the PnP mechanism. I came across this question and setting nodeLinker: node-modules in .yarnrc.yml followed by yarn install fixed it.
However, the ansers for this question didn't work for me.
I get this error in VS Code after running yarn dlx @yarnpkg/sdks vscode:
The path /Users/alexzeitler/src/hello-yarn-workspaces/.yarn/sdks/typescript/lib/tsserver.js doesn't point to a valid tsserver install. Falling back to bundled TypeScript version.

The files in .yarn/sdks/typescript/lib actually don't exist but I have a file integrations.yml in .yarn/sdks:
# This file is automatically generated by @yarnpkg/sdks.
# Manual changes might be lost!

integrations:
  - vscode

A: Looks like the missing pieces have been due to the PnP configuration:
yarn add --dev typescript ts-node prettier
yarn dlx @yarnpkg/sdks vscode

Add a minimal tsconfig.json:
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",
    "module": "commonjs",
    "lib": ["ESNext"],

    /* Strict Type-Checking Options */
    "strict": true,

    /* Module Resolution Options */
    "moduleResolution": "node",
    "esModuleInterop": true,

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  }
}

Then install this VS Code extension followed by these steps:

*

*Press ctrl+shift+p in a TypeScript file

*Choose "Select TypeScript Version"

*Pick "Use Workspace Version"

More details can be found in the docs.


Q: Firebase indexOn issue Edit: I want to filter all the post liked by someone using their phone number
My app was working since 3 years earlier i got warning in console about indexOn issue and i have added security rules as per instructed, now when i have updated firebase sdk and also now I'm using addOnCompleteListener instead of valueEventListener now some part of my app not working and now I'm getting exception about indexOn

I don't how to add index for this kind of key as it keeps changing as per user.
if I hardcode users phone number then it is working but I can't add keys for every user as there are few thousand user so please let me know what i can do.
here are few attachments about database, query and rules
database

query
FirebaseDatabase.getInstance()
                .getReference("2 line poetry").orderByChild(number).equalTo("heart");

Rules(currently used which works on previous version)

Rules(Hardcoded version which is working in new version)

I want to make this rule dynamic like using variable $phone or something, I have read almost all threads but didn't found any answer


Q: ZeroClipboard - Using multiple elements ZeroClipboard for single click copy. Both the links are giving the same output, rather than different. Demo link HERE
OBJ1
OBJ2

A: Give a common class to all these elements, and then make all of them available to ZeroClipBoard :

Then load them like this :

var clip = new ZeroClipboard($(".toBeCopied"));


Q: Flutter: LateError (LateInitializationError: Field 'user' has not been initialized.) I am nit sure about this error because user should be inithialized in Auth Provider and then I will be able to use it in User Provider but flutter continue giving this error.
Here is my code. Can someone help to solve or tell me a better form to organize it?
AuthProvider
class AuthProvider extends ChangeNotifier {
  late final FirebaseAuth _auth;
  late final NavigationService _navigationService;
  late final DatabaseService _databaseService;

  late UserData user;
  AuthProvider() {
    _auth = FirebaseAuth.instance;
    _navigationService = GetIt.instance.get<NavigationService>();
    _databaseService = GetIt.instance<DatabaseService>();
    _auth.authStateChanges().listen((_user) {
      if (_user != null) {
        //_databaseService.updateUserLastSeenTime(_user.uid);
        _databaseService.getUser(_user.uid).then(
          (_snapshot) {
            if (_snapshot.exists) {
              if (_snapshot.data() != null) {
                user =
                    UserData.fromJson(jsonDecode(jsonEncode(_snapshot.data())));
                notifyListeners();
              }
            }
            _navigationService.removeAndNavigateToRoute('/home');
          },
        );
      } else {
        _navigationService.removeAndNavigateToRoute('/login');
      }
    });
  }

User Provider
class UserProvider with ChangeNotifier {
  final DatabaseService _databaseService = DatabaseService();

  UserData _user = AuthProvider().user;
  UserData get getUser => _user;

  Future<void> refreshUser() async {
    UserData user = await _databaseService.getUserDetails();
    _user = user;
    notifyListeners();
  }

// update user name
  Future<void> editName(String name) async {
    try {
      await _databaseService.getUserDoc(_user.uid).update({'name': name});
    } catch (err) {
      print(err.toString());
    }
  }

// update user last name
  Future<void> editLastName(String lastName) async {
    try {
      await _databaseService
          .getUserDoc(_user.uid)
          .update({'lastName': lastName});
    } catch (err) {
      print(err.toString());
    }
  }
}


Q: MongoDB: Search Query to return an object inside the array I have a Journal Schema which contains an array of notes. I want to implement MongoDB search in my application so that it returns the note that matches the query. Right now it returns the entire Journal Object which contains the matched note.
Journal Schema:
{
  userid: {
    type: String,
    required: true,
  },
  notes: [
    {
      content: {
        type: String,
      },
    },
  ],
}

Right now my query syntax is:
[
  {
    $search: {
      index: 'Journal-search-index',
      text: {
        query: 'asdf',
        path: 'content'
      }
    }
  }
]

It returns the entire Journal object but I only want the note that matches the query. is there any way to implement that?

A: You are currently searching for documents that match current query, but not filtering the data inside of documents, particulary notes array.
You have to add filter on the next aggregation operation
const query = "asdf";

db.collection.aggregate([
  {
    $search: {
      index: "Journal-search-index",
      text: {
        query: query,
        path: "content",
      },
    },
  },
  {
    $project: {
      notes: {
        $filter: {
          input: "$notes",
          as: "note",
          cond: {
            $regexMatch: {
              input: "$$note",
              regex: query,
              options: "i",
            },
          },
        },
      },
    },
  },
]);

Playground Example


Q: How do I apply drop Shadow right and bottom of transparent view in Android? I want to apply drop shadow right and bottom on view (TextView/LinearLayout) with transparent background.
I have draw shadow using Layer-list as said in this link:
Add shadow on right and bottom side of the layout
but it is not giving me desired transparency.
can any one help me out?
Thanks


Q: Getting Value from Another Form: Apostrophes are not displaying Simply put, the apostrophes are not displaying inside my text field.
The result is here: www.unidrones.co.za/VRentals
In the search box, try typing something with an apostrophe like 1920's car or something. You will see a new form that appears. The "Model" field is supposed to accept the exact same string the user typed.
I viewed this nearly duplicate question: The apostrophes are not displayed when getting data from MySQL into bootstrap table but in my case I am not getting my value from the database, I'm getting the value directly from the previous form the user submitted.
I've tried escaping the string, I've tried utf8_encode() and utf8_decode(), I've tried prepared statements and I even tried changing all the "POST" methods to "GET" methods to see if that made any difference. Yet still, if I tried searching for something like 1920's Chrysler the apostrophe would turn into a backslash and the rest of the sentence would be gone.
My code:
<form action='inc/request.inc.php' method='POST' class='request-form' id='request-form'>
            Model
            <input type='text' name='searchvalue' class='searchvalue' value='".mysqli_real_escape_string($conn, $_POST['search'])."' required >
            Full Name
        ...
        </form>


Q: c++ templated container scanner here's today's dilemma:
suppose I've
class A{
  public:
   virtual void doit() = 0;
}

then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subclasses like say list<A*> or vector... The function should call all the doit methods while scanning the iterators... How to do this? I've thought of:
template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
    for (; begin != end; begin++) {
        A *elem = (serializable*) *begin;
        elem.doIt();
    }
}

but gives weird errors... do you have better ideas or specific information? Is it possible to use list<A> instead of list<A*>?

A: Why do you think you need the cast? If it is a collection of A * you should just be able to say:
(*begin)->doIt();

A: You can use the std::foreach for that:
std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );

The std::mem_fun will create an object that calls the given member function for it's operator() argument.  The for_each  will call this object for every element within v.begin() and v.end().

A: You should provide error messages to get better answers.
In your code, the first thing that comes to mind is to use
elem->doIt();

What is the "serializable" type ?


Q: Import Scala from Groovy Is there a way, preferred standard way to import Scala code (local jar, or local maven, or remote artifactory)?
We are using Groovy on Grails, and some library we want to use are written in Java or Scala. Considering they are all JVM languages, there must be a way to interplay.
I've search the net, but have not get a clear answer.

A: Both Scala and Java compiles into Java Bytecode (.class files) and packed as .jar files. It's same bytecode, and can be used from any other JVM language under same classpath.
So your app can mix java bytecode produces from any other JVM language, including Java, Groovy, Scala, Clojure, Kotlin, etc. You can put such jars into /lib dir (if your Grails version supports this; it's less preferred way) or as dependency from Maven repository (local or remote). Then you can use such classes from your code
See:

*

*https://en.wikipedia.org/wiki/Java_bytecode

*http://grails.github.io/grails-doc/2.4.x/guide/conf.html#dependencyResolution for grails 2.4.x

*http://grails.github.io/grails-doc/latest/guide/conf.html#dependencyResolution for latest grails

PS there could be some incompatibilities with some classes, because of different nature of sources languages. But in general it should work.

A: Did some simple tests. In hello-world example, just use

groovy -cp the-assembly-SNAPSHOT.jar main-file.groovy

And in the main-file.groovy, should have an import, like in Java/Scala


Q: Android base library module implementation We are currently updating the app code, and we are splitting the code into different library modules, which are used by one application module. The problem is that the app compiling time has increased exponentially and all of a sudden the 64k multidex limit has been exceeded. Here how we are building our app:

Is the base module recompiling each time for each library module? What could be changed to improve the compile time?


Q: Renaming Row Count Column in SQL I can’t find how to rename the row counting column in a table in an SQL Server RDMS. When you create a table and you have user created columns, A and B for example, to the farthest right of those columns, you have the Row Number column.
It does not have a title. It just sequentially counts all the rows in your table. It's default. Is it possible to manipulate this column denoting the row numbers? Meaning, can I rename it, put its contents in descending order, etc. If so, how?
And if not, what are the alternatives to have a sequentially counting column counting all the rows in my table?

A: No.  You can create your own column with sequential values using an identity column.  This is usually a primary key.
Alternatively, when you query the table, you can assign a sequential number (with no gaps) using row_number().  In general, you want a column that specifies the ordering:
select t.*, row_number() over (order by <ordering column>) as my_sequential_column
from t;


Q: Travis CI simple bash broken with latest update any "n" character seen as "\n" line break Travis CI seems to be misbehaving very oddly since yesterday. I know they pushed out an update on the 21st June 2017 to Travis but this issue only started happening yesterday to me causing a total mess of one of my repo's but luckily I reverted back to the last commit where everything was still OK and have done no more commits since then just been running tests on a different test repo all day today and it's still broken.
During my Travis build process I run a number of bash scripts that do various things like create files based on templates. But since yesterday the output of any echo or printf see's any "n" character as a line break \n
For example:
This simple printf in my bash script:
for line in $(cat $INPUT1); do
printf "\t\"~${line}\"\t\t$ACTION1\n" >> whateverfile.txt

My inputs are defined earlier as:
ACTION1="0;"
INPUT1=$TRAVIS_BUILD_DIR/myfile.txt

Travis breaks the output of any ${line} which contains an "n" in the output.
So for example a ${line} from the cat statement that contains the word bingbot for instance should output as follows:
"~bingbot" 0;

but Travis is doing this because it see's any n character as a line break, this below is the output of running the script with sh -x ./scriptname
bi"\t\t0;\n

+ printf \t"~gbot

and in the actual output file this is what travis prints with printf
bi"     0;
"~gbot

Anyone else seeing this behavior? I have tweeted and emailed them but no response yet. Tried various things to fix it and in some cases capitalising all my variables, inputs, filenames and directories fixes it but that is not a solution. What has Travis done to simple bash? or am I missing something. This has worked perfectly for over a year.
Note: my default scripts all run using #!/bin/bash I have changed them to use #!/bin/sh but it is still happening.

A: I solved this thanks to the help of a number of people in this question - Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
It wasn't a Travis CI issue after all. It's all explained in the link above.


Q: github webhook with flask - Github not trigger or not send requset I tried to write a flask app that when every time you do a push event to the Github repo it sends a webhook to the flask server. My code for flask app is:
from flask import Flask, request
app = Flask(__name__)

@app.route("/")
def getGitUpdate():
   #some of code
   return 'hello world'

if __name__ == '__main__':
    app.run("0.0.0.0",8000)

The way I set up the webhook on Github is like this:
enter image description here
It is important to note that the firewall is turned off, and in addition I am using the ubuntu 21.04 operating system.


Q: Purge cache in Cloudflare using API What would be best practice to refresh content that is already cached by CF?
We have few API that generate JSON and we cache them.
Once a while JSON should be updated and what we do right now is - purge them via API.

https://api.cloudflare.com/client/v4/zones/dcbcd3e49376566e2a194827c689802d/purge_cache

later on, when user hits the page with required JSON it will be cached.
But in our case we have 100+ JSON files that we purge at once and we want to send new cache to CF instead of waiting for users (to avoid bad experience for them).
Right now I consider to PING (via HTTP request) needed JSON endpoints just after we have purged cache.
My question if that is the right way and if CF already has some API to do what we need.
Thanks.

A: Currently, the purge API is the recommended way to invalidate cached content on-demand.
Another approach for your scenario could be to look at Workers and Workers KV, and combine it with the Cloudflare API. You could have:

*

*A Worker reading the JSON from the KV and returning it to the user.

*When you have a new version of the JSON, you could use the API to create/update the JSON stored in the KV.

This setup could be significantly performant, since the Worker code in (1) runs on each Cloudflare datacenter and returns quickly to the users. It is also important to note that KV is "eventually consistent" storage, so feasibility depends on your specific application.


Q: Sort Dictionary swift 3.0 At some point of coding, I require to sort dictionary to get ordered data based on the Dictionary's Key.
I tried to get the result by:
let sortedDict = dict.sorted { $0.key < $1.key }

It results into:
let dict = ["a0":1, "a3":2 , "a10":2, "a20":3]

Though, desired result:
let dict = ["a0":1, "a10":2, "a20":3, "a3":2]

Any suggestions would be most appreciated.
Thanks In advance.

A: Dictionary is an unordered collection of data, so you can't create an ordered dictionary.

A: Try This:
    for i in 0..<parameters!.count {
        let key = "q\(i)"
        if httpBody.contains(key){
            let regex = try! NSRegularExpression(pattern: "\\b\(key)\\b", options: .caseInsensitive)
            httpBody = regex.stringByReplacingMatches(in: httpBody, options: [], range: NSRange(0..<httpBody.utf16.count), withTemplate: "q")
        }
    }

Simple sort function will not work here.


Q: How do I use a date function in Access? I'm trying to put items into a table which have been deemed over due. I have the date of when items were completed last in a list, and I know the frequency of how often the items need to be completed.

Ex. I have a cleaning that happened on 4/7/17 and it needs to be cleaned 30 days after it was last cleaned, and I have a cleaning that occurred 1/13/17 and it needs to be cleaned 90 days after it was last cleaned.

How can I get Access to show me overdue items in a separate list? If it helps, I will click a button before going to this table. The thing is, not every item needs to be cleaned at the same frequency. To my knowledge, Access doesn't have the date functions like Excel and you cannot type functions into a cell. Thanks!

A:  dim datedue as date, lastdate as date
 datedue = Dateadd("d", 30, lastdate)

 If datedue < Date() then
      'do stuff
 End if

This is basic syntax for checking dates. Since you didnt try anythin on your own, this is all you get.
Have fun   :)

A: You don't "type functions into a cell", you set the ControlSource of a textbox. And Access has dozens of date functions.
However, you could start with a query:
Select
    *,
    DateAdd("d", [CleaningFrequency], [LastCleaned]) As NextCleaning,
    IIf(DateDiff("d", [LastCleaned], Date()) > [CleaningFrequency], "Overdue", Null) As [Status],
    IIf(DateDiff("d", [LastCleaned], Date()) = [CleaningFrequency], "Yes", Null) As [Clean Today]
From
    YourTable

Of course, replace field and table names with those of yours.


Q: Conversion from type 'DBNull' to type 'Date' is not valid on tryparse I am attempting to do a DateTime.TryParse from a date-formatted string, to a new column that I created as part of a DataView table.  I am getting this error when the code runs Conversion from type 'DBNull' to type 'Date' is not valid.
This is the line of code:
DateTime.TryParse(dr("IX_ArticleStartDate"), dr("nStartDate"))

And these are the values in my watch when it errors out.
+       dr("IX_ArticleStartDate")   "2015/3/11" {String}    Object
+       dr("nStartDate")    {}  Object

I was under the impression that a TryParse would return a NULL value if it fails to convert datatypes.  Is there something that I should be doing different to convert this string to a DateTime datatype?
dr is instantiated as a DataRow
Dim dr As DataRow = dv0.Table.Rows(i)

A: VB implicitly try's to cast the DBNull Value to DateTime, since the method signature of DateTime.TryParse is
Public Shared Function TryParse(s As String, ByRef result As Date) As Boolean

which fails. You can use a variable instead:
dim startDate as DateTime
If DateTime.TryParse(dr("IX_ArticleStartDate").ToString(), startDate) Then
    dr("startDate") = startDate
End If

A: A DateTime is a value type and cannot have a null value.  You can do something like this:
Dim result As DateTime

Dim myDate As DateTime? = If(Not dr.IsNull("IX_ArticleStartDate") AndAlso _
    DateTime.TryParse(dr.IsNull("IX_ArticleStartDate").ToString(), result), _
    result, New DateTime?)

In this example, the variable myDate is not actually a DateTime, it's a Nullable(Of DateTime) as indicated by the question mark ? after DateTime in the declaration (see MSDN).  The TryParse method actually takes a string value as the first argument and an output parameter which is a DateTime value as the second argument.  If the parse is successful, it returns True and sets the output parameter to the parsed DateTime value; on the other hand, if the parse is not successful, it returns False and sets the output parameter to DateTime.MinDate which is not very useful because it's difficult to distinguish between a valid use of DateTime.MinDate and null.
The example makes use of a ternary operator which either parses and returns the date value, if it's not null, or else returns a nullable date instead (New DateTime?).
You would then use myDate.HasValue() accordingly to determine if the value is null, and if it's not null, you can use its value: myDate.Value.


Q: Generating multiple data with SQL query I have 2 tables as below
Product_Asset:
PAId      Tracks
1          2
2          3

Product_Asset_Resource:
Id        PAId        TrackNumber
1          1              1
2          1              2
3          2              1
4          2              2
5          2              3

I would like to know if I can generate the data in product_asset_resource table based on product_asset table using TSQL query (without complex cursor etc.)
For example, if the number of tracks in product_asset  is 3 then I need to populate 3 rows in product_asset_resource with track numbers as 1,2,3

A: You can do this with the help of a Tally Table.
WITH E1(N) AS( -- 10 ^ 1 = 10 rows
    SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
CteTally(N) AS(
    SELECT TOP(SELECT MAX(Tracks) FROM Product_Asset)
        ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
    FROM E4
)
SELECT
    Id  = ROW_NUMBER() OVER(ORDER BY pa.PAId, t.N),
    pa.PAId,
    TrackNumber = t.N
FROM Product_Asset pa
INNER JOIN CteTally t
    ON t.N <= pa.Tracks

ONLINE DEMO

A: Try this,I am not using any Tally Table
declare @Product_Asset table(PAId int,Tracks int)
insert into @Product_Asset values (1 ,2),(2, 3)

;with CTE as
(
select PAId,1 TrackNumber from @Product_Asset
union all

select  pa.PAId,TrackNumber+1 from @Product_Asset pa
inner join cte c on pa.PAId=c.PAId
where c.TrackNumber<pa.Tracks
)

select ROW_NUMBER()over(order by paid)id, * from cte

IMHO,Recursive CTE or sub query or using temp table performance depend upon example to example.
I find Recursive CTE more  readable and won't use them unless they exhibit performance problem.
I am not convince that Recursive CTE is hidden RBAR.
CTE is just syntax so in theory it is just a subquery
We can take any example to prove that using #Temp table will improve the performance ,that doesn't mean we always use temp table.
Similarly in this example using Tally Table may not improve the performance this do not imply that we should take help of Tally Table at all.


Q: sending email with Indy to a gmail address message goes to spam Hello I'm trying to send a message from delphi (indy) to a gmail address. When I go to Gmail I found my message in spam folder. If I try to send the same message with PHPMailer from web it works correctly. This is the code.
Thanks
//setup SMTP
SMTP.Port := 25;
SMTP.ConnectTimeout := 1000;
SMTP.Host := 'smtp.xxxxxx.it';
SMTP.Username := 'info@xxxxxx.it';
SMTP.Password := 'xxxxxx';
SMTP.Connect();

if SMTP.Authenticate then
begin
    //setup mail message
    MailMessage.From.Name := 'xxxxxx';
    MailMessage.From.Address := 'info@xxxxxx.it';
    MailMessage.Recipients.EMailAddresses := 'xxxxxx@gmail.com';

    MailMessage.Subject := ledSubject.Text;
    MailMessage.ContentType := 'multipart/mixed';
    htmpart := TIdText.Create(MailMessage.MessageParts, nil);
    htmpart.Body := Body.Lines;
    htmpart.ContentType := 'text/html';

    //send mail
    try
        try
            SMTP.Send(MailMessage);
        except on E:Exception do
            StatusMemo.Lines.Insert(0, 'ERROR: ' + E.Message);
        end;
    finally
        if SMTP.Connected then SMTP.Disconnect;
    end;
end;

A: Probably I've found the problem. I look the message in 'original mode' I found in the header that google says 'MISSING ID' and I try to add this code:
    MailMessage.MsgId := '1234567890@drinkmessage.it';
    MailMessage.ExtraHeaders.Values['Message-Id'] := MailMessage.MsgId;

Now it seems to work fine.
thanks

A: Have you tried changing HeloName and MailAgent of IdSMTP? If you use the same domain with PHPMailer, my guess is GMail considers emails coming from your application as spam because it doesn't detect/like the application which is sending them.


Q: Problem with random variable elements for Web Scrapping I'd like to create a relative function to access every game report available in this table: https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1
I started making a relative URL, but there is an element in the URL that I believe to be random.
Here is what I refer to:

*

*cbdc95fe for: https://fbref.com/fr/matchs/cbdc95fe/Lille-Auxerre-7-Aout-2022-Ligue-1

*

*00173ae0 for: https://fbref.com/fr/matchs/00173ae0/Nantes-Lille-12-Aout-2022-Ligue-1
To overcome this limit, do you know efficient ways to open all links within the table?
Thanks for your help !

A: using the requests and lxml libraries (lxml for xpath) this becomes a fairly straightforward task:
  1 import requests
  2 from lxml import etree
  3
  4 s = requests.session()
  5 r = s.get("https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1")
  6 tree = etree.HTML(r.content)
  7 matchreporturls = tree.xpath('//td[@data-stat="match_report"]/a[text()="Rapport de match "]/@href')
  8
  9 for matchreport in matchreporturls:
 10     r = s.get("https://fbref.com" + matchreport)
 11     # do something with the response data
 12     print('scraped {0}'.format(r.url))


Q: Which one is better for (mysql) performance? Which one is better for (mysql) performance ?
"1500 (300x5) Tables with 365 rows per table" OR "(300x5)1500x365 rows in 1 table" ?
(I will get the data(s) with php.)
365 -> days number of the year

*

*if second: I will use "date" and "x_id" to get the 1 row from (300x5)1500x365 rows.

*if first: I will use "date" and "table_name" to get 1 row from 365 rows.**

A: Second one.
http://datacharmer.blogspot.com/2009/03/normalization-and-smoking.html
[edited after updates to question]
In second case you can create an index on columns (x_id,date) which will improve performance of WHERE x_id = ? AND date = ? searches. Some ~550000 rows is not much for well indexed table.

A: Assuming that all the relationships in the data are one-to-one, then the second option of using a single table is the better (normalized) approach.
But there's no detail to the multi-table option, or the data that is being stored.  Bad design, like a table per user, is responsible for performance - not the fact of numerous tables.
Update
Things are still quite vague, but the data you want to store is daily and over the course of years.  What makes it different that you would consider separate tables with identical formats?  The identical tables prompts me to suggest single main table, with some supporting tables involved for things like status and/or type codes to differentiate between records in a single table that were obvious in a separate table approach.

A: That depend on the engine you are using and also if you are going to have more read or more write.
For that look at the way each engine lock the table regarding read and write.
But 1500 table is a lot. I would expect something like 10 table.
1 table is not a bad choice either but if one day you want to have multiple server it gonna be more easy to spread them with 10 table.
Also if you change the structure of the table is going to be long with 1 table. (I know that it shouldn't append but the fact it does)


Q: Lambda Expression using Foreach Clause
Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?

EDIT
For reference, here's the blog post which eric referred to in the comments
https://ericlippert.com/2009/05/18/foreach-vs-foreach/
ORIG
More of a curiosity I suppose but one for the C# Specification Savants...
Why is it that the ForEach() clause doesn't work (or isn't available) for use on IQueryable/IEnumerable result sets...
You have to first convert your results ToList() or ToArray()
Presumably theres a technical limitation to the way C# iterates IEnumerables Vs. Lists...
Is it something to do with the Deferred Execution's of IEnumerables/IQuerable Collections.
e.g.
var userAgentStrings = uasdc.UserAgentStrings
    .Where<UserAgentString>(p => p.DeviceID == 0 &&
                            !p.UserAgentString1.Contains("msie"));
//WORKS
userAgentStrings.ToList().ForEach(uas => ProcessUserAgentString(uas));

//WORKS
Array.ForEach(userAgentStrings.ToArray(), uas => ProcessUserAgentString(uas));

//Doesn't WORK
userAgentStrings.ForEach(uas => ProcessUserAgentString(uas));

A: It's perfectly possible to write a ForEach extension method for IEnumerable<T>.
I'm not really sure why it isn't included as a built-in extension method:

*

*Maybe because ForEach already existed on List<T> and Array prior to LINQ.

*Maybe because it's easy enough to use a foreach loop to iterate the sequence.

*Maybe because it wasn't felt to be functional/LINQy enough.

*Maybe because it isn't chainable. (It's easy enough to make a chainable version that yields each item after performing an action, but that behaviour isn't particularly intuitive.)

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}


Q: Sort an NSMutableArray / Dictionary with several objects I am having a problem that I think I am overcomplicating.
I need to make either an NSMutableArray or NSMutableDictionary. I am going to be adding at least two objects like below:
NSMutableArray *results = [[NSMutableArray alloc] init];

[results addObject: [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInteger:myValue01], @"valueLabel01", nil]];

This gives me the array I need but after all the objects are added I need to be able to sort the array by the first column (the integers - myValues). I know how to sort when there is a key, but I am not sure how to add a key or if there is another way to sort the array.
I may be adding more objects to the array later on.

A: Quick reference to another great answer for this question:
How to sort NSMutableArray using sortedArrayUsingDescriptors?
NSSortDescriptors can be your best friend in these situations :)

A: What you have done here is create a list with two elements: [NSNumber numberWithInteger:myValue01] and @"valueLabel01". It seems to me that you wanted to keep records, each with a number and a string? You should first make a class that will contain the number and the string, and then think about sorting.

A: Doesn't the sortedArrayUsingComparator: method work for you? Something like:
- (NSArray *)sortedArray {
    return [results sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
    {
        NSNumber *number1 = [obj1 objectAtIndex:0];
        NSNumber *number2 = [obj2 objectAtIndex:0];
        return [number1 compare:number2]; }];
    }


Q: Cant find the file i created on android tablet /data directory in android is empty. I have installed a few applications and i also wrote code to create a file in /data/Myapp directory ,
I have these lines in OnCreate method , but i dont see any files in /data directory after running the program.
    File fileDir = getFilesDir();
    String filedir=fileDir.toString();
    Log.v("TEST","FILEDIR--->"+filedir);

       //output i got is FILEDIR--->/data/data/com.android.Test/files

    String strNewFileName = "test1.txt";
    String strFileContents = " MY FIRST FILE CREATION PRGM";

    File newFile = new File(fileDir, strNewFileName);
    try{

            boolean filestat = newFile.createNewFile();
            Log.v("TEST"," CREATE FILE =>"+ filestat);

                //output is CREATE FILE =>true indicating success

            FileOutputStream fo =
            new FileOutputStream(newFile.getAbsolutePath());
            fo.write(strFileContents.getBytes());
            fo.close();
    }
    catch(IOException e)
    {Log.v("TEST","Exception on create ");}

A: On real device, you can't see these folders if it's not rooted. see this question.
If you want to write files in your app directory, then your code is OK. You can check that it is there in the same way you created it - from your application:
File myFile = new File(getFilesDir() + "/test1.txt");
if (myFile.exists())
{
  //Good!
}


Q: how to sort parameters with Jenkins parametrized job? Problem:
A Jenkins job is starting to have a lot of parameter (over 20).
Is there a way to group them, have title, etc...?
I looked up and found none.

A: There is no way of sorting parameters automatically that I'm aware of. You can arrange them via Drag&Drop in your project's config manually, of course.
You can group them using the Parameter Separator Plugin:
Meta Data → [✔] This build is parameterized → Add Parameter → Parameter Separator


Q: How can I copy dependencies from a library project to the main project? I have an Asp.Net project (Vb.Net) that references a managed dll (library written in C#). That library project has several unmanaged dependencies dlls in a lib folder (copied into bin/Release/lib folder during build). The library is not a part of the main solution.
My library uses [DllImport] that references an unmanaged dll. But to let the unmanaged dll be found, I call SetDllDirectory():
        string path = // don't know how to generate the path
        SetDllDirectory(path);

I am struggling with generating the path to the unmanaged dll and its dependencies. I can start with my main project bin folder or something. But what should I do next? E.g. is there a way to copy the unmanaged dlls from the library's bin/Release/lib folder to my main project's bin folder? Or some other solution?

A: There are two ways you can go about this:

*

*Add the Dlls to the VS project as a file, then set Build Action to None and Copy to output directory as Copy. This should ensure that any external dependencies of the referenced library are copied.

*Add a command like xcopy "$(ProjectDir)lib\*.*" "$(OutDir)\" /y /e or xcopy "$(ProjectDir)lib\*.*" "$(TargetDir)" /y to the Build Events section in Project properties. This should copy the \lib directory from the project root to the output.


Q: How to get iframe images to print as part of full document in IE I have two IFRAMEs.  Each IFRAME is loaded dynamically as the result of submitting a FORM.  The result of each FORM submit is a dynamically generated jpeg image (Content-type: image/jpeg).  The following page displays correctly (you can see both images).  If you try to print this page in IE however, you just get an outline of the images, but not the actual images.  It prints correctly in Safari and Chrome.  How can you get the IFRAME images to print along with the rest of the document in IE?
I am using IE 9.0.8112.16421.
<HTML>
<HEAD>
<TITLE>View Image</TITLE>
</HEAD>
<BODY onLoad="top.document.Form1.submit();top.docment.Form2.submit();">
<FORM NAME=Form1 ACTION="URL" METHOD=POST Target=Img1>
<INPUT TYPE=HIDDEN NAME=ID VALUE=123>
<INPUT TYPE=HIDDEN NAME=Cmd VALUE=DispImage1>
</FORM>
<FORM NAME=Form2 ACTION="URL" METHOD=POST Target=Img2>
<INPUT TYPE=HIDDEN NAME=ID VALUE=345>
<INPUT TYPE=HIDDEN NAME=Cmd VALUE=DispImage2>
</FORM>
<IFRAME NAME=Img1 SRC=Javascript:'' WIDTH=500 HEIGHT=250 FRAMEBORDER=0 SCROLLING=no>
</IFRAME><BR>
<IFRAME NAME=Img2 SRC=Javascript:'' WIDTH=500 HEIGHT=250 FRAMEBORDER=0 SCROLLING=no>
</IFRAME>
</BODY>
</HTML>


Q: Building Framework as "Generic iOS Device" Causes Use of Undeclared Type in Project Using Framework Basically, as stated in the title, when I build my Cocoa Touch Framework for "Generic iOS Device," it causes "Use of Undeclared Type" compilation errors in my XCode project using the framework. However, when I build the XCode Project for "Generic iOS Device" too, the errors go away.
My question is: How can I build the framework in such a way that it can be used for simulators as well as a generic iOS device?
I was under the impression that building a Cocoa Touch Framework for "Generic iOS Device" would allow it to be used in any build configuration. Is this incorrect?
Is there something that has to be changed in the build settings or schemes?
Thanks!

A: Update: I was mistaken, and due to simulators and iPhones having different architectures, you have to compile the framework for each one respectively. However, I was able to create a "fat framework" by following this Medium article: https://medium.com/@hassanahmedkhan/a-noobs-guide-to-creating-a-fat-library-for-ios-bafe8452b84b
This fat framework can be used for both "Generic iOS Device" and the simulator.