问:
How to delete dynamic allocated array in c++?
I got stuck with deleting an dynamically allocated array of int.
I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it.
I have code on http://rextester.com/OTPPRQ8349
Thanks!</p>

```<code>class MyClass
{
   public:
   int _a;
   int* c;
   int fRozmiar;
   static int fIlosc;
   MyClass() //default constructor
   {
       _a=0;
       c = new int [9];
       for(int i = 0; i<=9; i++)
       {
           c[i] = 1;
       }
       fIlosc++;
   }
   MyClass(int a1, int c1) // parametrized constructor
   {
       _a=a1;
       c = new int [c1];
       for(int i = 0; i<=c1; i++)
       {
           c[i] = rand();
       }
       fIlosc++;
   }
   MyClass(const MyClass &p2) // copy constructor
   {
    _a =p2._a;
    c = p2.c;
    fRozmiar = p2.fRozmiar;
    fIlosc = fIlosc;
    fIlosc++;
   }
    ~MyClass(); // destructor

    static int getCount() {
         return fIlosc;
      }
};

//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
        for(int i = 0; i<sizeof(c); ++i)
        {
            delete[] c[i];
        }
        delete[] c;
       fIlosc--;
}
int main()
{
}
</code>```

答:
Remove the for-loop, but keep the delete[] c after it.

Each int doesn't need to be deleted because they're not dynamically allocated. If you needed to delete them, then the for-loop wouldn't work becuase: sizeof(c) is not the size of the array, and delete[] should have been delete instead.

Body:
I got stuck with deleting an dynamically allocated array of int.
I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it.
I have code on http://rextester.com/OTPPRQ8349
Thanks!

class MyClass
{
   public:
   int _a;
   int* c;
   int fRozmiar;
   static int fIlosc;
   MyClass() //default constructor
   {
       _a=0;
       c = new int [9];
       for(int i = 0; i<=9; i++)
       {
           c[i] = 1;
       }
       fIlosc++;
   }
   MyClass(int a1, int c1) // parametrized constructor
   {
       _a=a1;
       c = new int [c1];
       for(int i = 0; i<=c1; i++)
       {
           c[i] = rand();
       }
       fIlosc++;
   }
   MyClass(const MyClass &p2) // copy constructor
   {
    _a =p2._a;
    c = p2.c;
    fRozmiar = p2.fRozmiar;
    fIlosc = fIlosc;
    fIlosc++;
   }
    ~MyClass(); // destructor

    static int getCount() {
         return fIlosc;
      }
};

//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
        for(int i = 0; i<sizeof(c); ++i)
        {
            delete[] c[i];
        }
        delete[] c;
       fIlosc--;
}
int main()
{
}


来源: stackexchange

问:
How to get previous and next words for current selection in FabricJS?
I'm wondering how to find a previous and next words in Textbox element of FabricJS.
Assume I have the next text:

Hello beautiful world.

Currently, my cursor stands on "beautiful", so I want to get "Hello" as a text before and "world" as a text after.

Any ideas?
Tnx

http://jsfiddle.net/redlive/gdyvfj1h/1/

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

function getBeforeAndAfter(text){
 const start = text.selectionStart;
 const end = text.selectionEnd;
 const textBefore = '';
 const textAfter = '';
 ///////////// THIS LOGIC NEEDS TO BE DEVELOPED HERE /////
 $('#before').val( textBefore );
 $('#after').val( textAfter );
}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);

var text = new fabric.Textbox('Hello beautiful world', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});
text.selectionStart = 6;
text.selectionEnd = 15;
canvas.add(text);
canvas.renderAll();

$("#btn").on("click", function(t){
 getBeforeAndAfter(text);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
Text before:
<input type="text" id="before" disabled/>
<br>
Text after:
<input type="text" id="after" disabled/>
<br>
<button id="btn">Get Before and After</button></code>```

答:
Inside your getBeforeAndAfter function, do this:

Logic

First, set the currently selected word to currentWord from the string by calling .slice on  the Textbox's .text property. Provide start and end as your arguments. You now have the selected word ('beautiful').

Second, split the string by a single space.

Third, find the indexOf your selected word (1).

Finally, your previous word's content is words[currentWordIndex - 1] and your next word's content is words[currentWordIndex + 1].

Example:

```<code>function getBeforeAndAfter(text){
    const string = text.text;
    const start = text.selectionStart;
    const end = text.selectionEnd;
    const currentWord = string.slice(start, end);

    const words = string.split(" ");
    const index = words.indexOf(currentWord);

    const textBefore = words[index-1];
    const textAfter = words[index+1];

    $('#before').val( textBefore );
    $('#after').val( textAfter );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering how to find a previous and next words in Textbox element of FabricJS.
Assume I have the next text:

Hello beautiful world.

Currently, my cursor stands on "beautiful", so I want to get "Hello" as a text before and "world" as a text after.

Any ideas?
Tnx

http://jsfiddle.net/redlive/gdyvfj1h/1/

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

function getBeforeAndAfter(text){
 const start = text.selectionStart;
 const end = text.selectionEnd;
 const textBefore = '';
 const textAfter = '';
 ///////////// THIS LOGIC NEEDS TO BE DEVELOPED HERE /////
 $('#before').val( textBefore );
 $('#after').val( textAfter );
}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);

var text = new fabric.Textbox('Hello beautiful world', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});
text.selectionStart = 6;
text.selectionEnd = 15;
canvas.add(text);
canvas.renderAll();

$("#btn").on("click", function(t){
 getBeforeAndAfter(text);
});

<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
Text before:
<input type="text" id="before" disabled/>

Text after:
<input type="text" id="after" disabled/>

<button id="btn">Get Before and After</button>

Body:
Inside your getBeforeAndAfter function, do this:

Logic

First, set the currently selected word to currentWord from the string by calling .slice on  the Textbox's .text property. Provide start and end as your arguments. You now have the selected word ('beautiful').

Second, split the string by a single space.

Third, find the indexOf your selected word (1).

Finally, your previous word's content is words[currentWordIndex - 1] and your next word's content is words[currentWordIndex + 1].

Example:

function getBeforeAndAfter(text){
    const string = text.text;
    const start = text.selectionStart;
    const end = text.selectionEnd;
    const currentWord = string.slice(start, end);

    const words = string.split(" ");
    const index = words.indexOf(currentWord);

    const textBefore = words[index-1];
    const textAfter = words[index+1];

    $('#before').val( textBefore );
    $('#after').val( textAfter );
}


问:
Xcode not reflecting changes in the code to the simulator and device
This never happened to me before. I have my code which was working fine and yesterday morning after updating my code from GitHub, the Xcode did not accept changes and installed the previous build. I removed my project, deleted Git client and cloned a new project, which didn't work while running on simulator. I tried installing app on device and it was running fine!

Later in the evening I created an AdHoc and I had the same issue (AdHoc was same as simulator build!).

Today morning I removed the Xcode and installed the new Xcode Version 4.3. However the problem still exists. I can not see my new changes on Simulator and on device. The same code is working fine for my friend. (I have cleaned the project many times, removed the project from Organizer-? project). Nothing seems to work.

EDIT:

I formatted my computer.

Now there should be no reason for it to show me old code. I even got the fresh copy from Repo... The worst thing is, it's still showing me something different!

Why is it like this?

答:
Still happening in 11/2017

xCode (that day, never seen it before) is not saving changes in code in Assistant editor mode. Even linking IBOutlet doesn't work.

If you go back to Standard Editor you loose all your new code, nice...

Better stay in Standard Editor

ContentLicense: CC BY-SA 4.0


问:
MS SQL Not Like Query
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.</p>

```<code>SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName
</code>```

答:
```<code>SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay <> 'Monday'
</code>```

Try using <>

Title: MS SQL Not Like Query

Body:
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.

SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName

Body:
SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay <> 'Monday'

Try using <>


问:
View with editable textviews (onClick)
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

```<code>    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);
</code>```

.......

```<code>    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}
</code>```

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.

答:
You should better implement a unified onClickListener()

Activity

```<code>public class Activity extends AppCompatActivity implements View.OnClickListener
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        TextView textView1 = findViewById(R.id.text_view_1);
        textView1.setOnClickListener(this);

        TextView textView2 = findViewById(R.id.text_view_2);
        textView2.setOnClickListener(this);

        TextView textView3 = findViewById(R.id.text_view_3);
        textView3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
        final TextView textView = (TextView) v;

        final EditText editText = new EditText(this);
        editText.setText(textView.getText());

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("Edit");
        dialog.setView(editText);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(editText.getText());
            }
        });
        dialog.show();
    }
}
</code>```

ButterKnife

With ButterKnife it is simpler, and you dont need to exclusively implement View.OnClickListener

```<code>public class Activity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        // ButterKnife Binder
        ButterKnife.bind(this);
    }

    // ButterKnife OnClick
    @OnClick({R.id.text_view_1, R.id.text_view_2, R.id.text_view_3})
    void onClickTextView(final TextView textView)
    {
        final EditText editText = new EditText(this);
        editText.setText(textView.getText());

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("Edit");
        dialog.setView(editText);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(editText.getText());
            }
        });
        dialog.show();
    }
}
</code>```

Title: View with editable textviews (onClick)

Body:
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);

.......

    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.

Body:
You should better implement a unified onClickListener()

Activity

public class Activity extends AppCompatActivity implements View.OnClickListener
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        TextView textView1 = findViewById(R.id.text_view_1);
        textView1.setOnClickListener(this);

        TextView textView2 = findViewById(R.id.text_view_2);
        textView2.setOnClickListener(this);

        TextView textView3 = findViewById(R.id.text_view_3);
        textView3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
        final TextView textView = (TextView) v;

        final EditText editText = new EditText(this);
        editText.setText(textView.getText());

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("Edit");
        dialog.setView(editText);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(editText.getText());
            }
        });
        dialog.show();
    }
}

ButterKnife

With ButterKnife it is simpler, and you dont need to exclusively implement View.OnClickListener

public class Activity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        // ButterKnife Binder
        ButterKnife.bind(this);
    }

    // ButterKnife OnClick
    @OnClick({R.id.text_view_1, R.id.text_view_2, R.id.text_view_3})
    void onClickTextView(final TextView textView)
    {
        final EditText editText = new EditText(this);
        editText.setText(textView.getText());

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("Edit");
        dialog.setView(editText);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(editText.getText());
            }
        });
        dialog.show();
    }
}


问:
CLion won't print in console after scanf
Console in CLion won't print line after scaning input, but in iTerm after compiling it all works perfectly.
Code:

```<code>#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName;
    printf("Hello, what is your name?\n");
    scanf("%s", personName);
    printf("Hello, %s\n", personName);
    return 0;
}
</code>```

I just got this in CLion console:

```<code>Hello, what is your name?
Mike

Process finished with exit code 11
</code>```

答:
You need to use an array for personName. The code will be,

```<code>#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName[32];
    printf("Hello, what is your name?\n");
    if(scanf("%s", personName))
        printf("Hello, %s\n", personName);
    return 0;
}
</code>```

Body:
Console in CLion won't print line after scaning input, but in iTerm after compiling it all works perfectly.
Code:

#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName;
    printf("Hello, what is your name?\n");
    scanf("%s", personName);
    printf("Hello, %s\n", personName);
    return 0;
}

I just got this in CLion console:

Hello, what is your name?
Mike

Process finished with exit code 11

Body:
You need to use an array for personName. The code will be,

#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName[32];
    printf("Hello, what is your name?\n");
    if(scanf("%s", personName))
        printf("Hello, %s\n", personName);
    return 0;
}


问:
By group, create new column by summing part of row
I'm sure this has been answered somewhere, but I've been trying different methods all day without success. Below is a part of my large dataframe. By group ('legal'), I want to sum 3 columns and create a new column of each groups' total.

My dataframe:

```<code> legal y2015 y2016 y2017
  NE2    0     1      1
  NE2    0     1      1
  SW4    1     0      0
  SW4    1     0      0
</code>```

Desired result:

```<code> legal y2015 y2016 y2017  total
  NE2    0     1      1     2
  NE2    0     1      1     2
  SW4    1     0      0     1
  SW4    1     0      0     1
</code>```

I've tried by, ColSums, ddply, etc. and get various errors, often that my replacement has fewer rows than my data. The examples I'm working off of are all a bit different than what I'm trying to achieve.

答:
df$total = rowSums(df[,2:4])

I'm subsetting df to avoid summing strings. Better to use dplyr::select or subset to specify columns, so you can avoid numeric indexing.

EDIT: noticed you said "by group", which confuses me since your example has multiple rows for each group. If you actually wanted

```<code> legal y2015 y2016 y2017  total
  NE2    0     2      2     4
  SW4    2     0      0     2
</code>```

you can first use dplyr.

```<code>df = df %>% group_by(legal) %>%
summarise(y2015 = sum(y2015),
          y2016 = sum(y2016),
          y2017 = sum(y2017))
</code>```

Then use rowSums on the result

Body:
I'm sure this has been answered somewhere, but I've been trying different methods all day without success. Below is a part of my large dataframe. By group ('legal'), I want to sum 3 columns and create a new column of each groups' total.

My dataframe:

 legal y2015 y2016 y2017
  NE2    0     1      1
  NE2    0     1      1
  SW4    1     0      0
  SW4    1     0      0

Desired result:

 legal y2015 y2016 y2017  total
  NE2    0     1      1     2
  NE2    0     1      1     2
  SW4    1     0      0     1
  SW4    1     0      0     1

I've tried by, ColSums, ddply, etc. and get various errors, often that my replacement has fewer rows than my data. The examples I'm working off of are all a bit different than what I'm trying to achieve.

Body:
df$total = rowSums(df[,2:4])

I'm subsetting df to avoid summing strings. Better to use dplyr::select or subset to specify columns, so you can avoid numeric indexing.

EDIT: noticed you said "by group", which confuses me since your example has multiple rows for each group. If you actually wanted

 legal y2015 y2016 y2017  total
  NE2    0     2      2     4
  SW4    2     0      0     2

you can first use dplyr.

df = df %>% group_by(legal) %>%
summarise(y2015 = sum(y2015),
          y2016 = sum(y2016),
          y2017 = sum(y2017))

Then use rowSums on the result


问:
Serve files from Apache to Javascript
I am writing my first web application with Javascript and WebGL. For now I am running the app on localhost from Apache. The app needs to work with data that is provided instantly. Until now I worked with AJAX calls that happen during runtime which doesn't work out for my purposes anymore. So instead of serving individual files from Server to Client when asked, I want the application to load all files from the Server to Client side at initialization time (I want this to happen automatically at the start so I don't have to add every new file as a url in the html index). I understand I should do this with Server Side scripting; probably with PHP since I have a Apache localhost? I have different folders which hold my necessary resources in a uniform dataformat (.txt, .png and .json). So what I want to do is, before the Javascript app starts, look through the folder and send one object per folder that holds filenames as keys bound to filedata. Is my intuition right that I need to do that with PHP? If yes, where do I start to tell my application what to do when (first start serving files with php, then start the javascript app)? How do I do this on localhost? Should I already think about extending my toolset (e.g. using nodeJS on ServerSide(locally for now))? If so what lightweight tools do you propose for this kind of work? I feel I am missing some design principles here.

EDIT:
Keep in mind that I don't want to specifically call a single file... I am already doing that. What I need is a script that automatically serves all the files of a certain folder on the server to the client side at init time of the app before the program logic of the actual application starts.

答:
Your question is kind of broad so I'll try my best.  Why does AJAX not work for real-time data but loading all the files once does?  If you're working with real time data, why not look into a websocket or at the bare minimum, AJAX queries?

If you want to pass data from the server to the client, you will need to use a HTTP request no matter what.  A GET request or POST request is necessary for the client to request data from the server and receive it as a response.

You could theoretically just pass the data from PHP straight to the view of the application (which is technically done through a GET request whenever a user requests data such as .php files from the server) but this isn't as flexible as if Javascript had access to the data.  You can do some hacks and 'transfer' the data from the view to Javascript with some .value methods, but this isn't ideal and can be prone to some security holes.  This also means data is only being passed once.

So what would need to happen is that the data would need to be processed upon initialization and then immediately transferred to the client by use of Javascript and HTTP requests.

So if you want Javascript to have access to the data and use it in variables or manipulate it further, then you'd need to use an HTTP request such as GET or POST which is called by Javascript.  Otherwise, you need to immediately pass the data to the view upon initialization (through PHP), but this means you can't work with real-time data because the data is only being passed once when there is a page refresh.

Example of scandir():

```<code><?php
//scandir() returns filenames, not data from files
$fileArray = scandir('datafolder/') //this is a relative path reference to the folder 'datafolder'
$finalArray = [];

foreach($fileArray as $filename){
    tempArray = [];
    $file = fopen('datafolder/' . $filename, 'r'); //im pretty sure scandir only retrieves the filenames and not the path, so you might need to append the filepath so your script knows where to look
    $tempArray = fgetcsv($file, 1024); //temp array to hold contents of each iteration of foreach loop
    array_push($finalArray, $tempArray); //this will store the data for later use
}
</code>```

Or the data can be used however, depending on what it is.  Say, if you need to combine the data from multiple .csv files, you can read each file and append it to a single array.  If you want to read multiple distinct files and preserve the independence of each file, you can create multiple arrays and then pass back a single JSON encoded object that contains each file's data as a separate attribute of the object such as:

```<code>{
    'dataOne': [0,1,2,3,4,5,6...],
    'dataTwo': ['new', 'burger', 'milkshake'],
    'dataThree': ['Mary', 'Joe', 'Pam', 'Eric']
}
</code>```

Which can be created with a PHP associative array using one of the following methods:

```<code>//assuming $arrayOne is already assigned from reading a file and storing its contents within $arrayOne
$data['dataOne'] = $arrayOne;
// or
array_push($data['dataTwo'], $arrayTwo);
// or
array_push($data, [
   'dataThree'  => ['Mary', 'Joe', 'Pam', 'Eric']
]);
</code>```

Then $data can simply be passed back which is a single array containing all the different sets of data, if each set needs to be distinct.

Title: Serve files from Apache to Javascript

Body:
Your question is kind of broad so I'll try my best.  Why does AJAX not work for real-time data but loading all the files once does?  If you're working with real time data, why not look into a websocket or at the bare minimum, AJAX queries?

If you want to pass data from the server to the client, you will need to use a HTTP request no matter what.  A GET request or POST request is necessary for the client to request data from the server and receive it as a response.

You could theoretically just pass the data from PHP straight to the view of the application (which is technically done through a GET request whenever a user requests data such as .php files from the server) but this isn't as flexible as if Javascript had access to the data.  You can do some hacks and 'transfer' the data from the view to Javascript with some .value methods, but this isn't ideal and can be prone to some security holes.  This also means data is only being passed once.

So what would need to happen is that the data would need to be processed upon initialization and then immediately transferred to the client by use of Javascript and HTTP requests.

So if you want Javascript to have access to the data and use it in variables or manipulate it further, then you'd need to use an HTTP request such as GET or POST which is called by Javascript.  Otherwise, you need to immediately pass the data to the view upon initialization (through PHP), but this means you can't work with real-time data because the data is only being passed once when there is a page refresh.

Example of scandir():

<?php
//scandir() returns filenames, not data from files
$fileArray = scandir('datafolder/') //this is a relative path reference to the folder 'datafolder'
$finalArray = [];

foreach($fileArray as $filename){
    tempArray = [];
    $file = fopen('datafolder/' . $filename, 'r'); //im pretty sure scandir only retrieves the filenames and not the path, so you might need to append the filepath so your script knows where to look
    $tempArray = fgetcsv($file, 1024); //temp array to hold contents of each iteration of foreach loop
    array_push($finalArray, $tempArray); //this will store the data for later use
}

Or the data can be used however, depending on what it is.  Say, if you need to combine the data from multiple .csv files, you can read each file and append it to a single array.  If you want to read multiple distinct files and preserve the independence of each file, you can create multiple arrays and then pass back a single JSON encoded object that contains each file's data as a separate attribute of the object such as:

{
    'dataOne': [0,1,2,3,4,5,6...],
    'dataTwo': ['new', 'burger', 'milkshake'],
    'dataThree': ['Mary', 'Joe', 'Pam', 'Eric']
}

Which can be created with a PHP associative array using one of the following methods:

//assuming $arrayOne is already assigned from reading a file and storing its contents within $arrayOne
$data['dataOne'] = $arrayOne;
// or
array_push($data['dataTwo'], $arrayTwo);
// or
array_push($data, [
   'dataThree'  => ['Mary', 'Joe', 'Pam', 'Eric']
]);

Then $data can simply be passed back which is a single array containing all the different sets of data, if each set needs to be distinct.


问:
Disable Highlight Matched Parentheses in ViM : "let loaded_matchparen = 1" not working
How to disable auto highlighting of Matched Parentheses (cursor briefly jumping to the matched bracket, when a new bracket is inserted) in ViM?

When I faced this issue in my earlier company, then I was able to resolve it by adding below line to my .vimrc

```<code>let loaded_matchparen = 1
</code>```

Now in my new company I am facing the same problem. But now the issue doesn't go even with above line in my .vimrc.

I tried adding, NoMatchParen to my .vimrc, I am getting following error when opening ViM:

```<code>Error detected while processing <...>/.vimrc:
E492: Not an editor command: NoMatchParen
</code>```

Pl. let me know a work around for this annoying issue.

FYR, Output of my $ vim --version:

```<code>VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Feb 11 2012 21:05:37)
Compiled by rvictor@depbldrh61
Huge version with GTK2 GUI.  Features included (+) or not (-):
+arabic +autocmd +balloon_eval +browse ++builtin_terms +byte_offset +cindent
+clientserver +clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
+conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con_gui +diff
+digraphs +dnd -ebcdic +emacs_tags +eval +ex_extra +extra_search +farsi
+file_in_path +find_in_path +float +folding -footer +fork() +gettext
-hangul_input +iconv +insert_expand +jumplist +keymap +langmap +libcall
+linebreak +lispindent +listcmds +localmap -lua +menu +mksession +modify_fname
+mouse +mouseshape +mouse_dec -mouse_gpm -mouse_jsbterm +mouse_netterm
-mouse_sysmouse +mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg
-osfiletype +path_extra -perl +persistent_undo +postscript +printer +profile
-python -python3 +quickfix +reltime +rightleft -ruby +scrollbind +signs
+smartindent -sniff +startuptime +statusline -sun_workshop +syntax +tag_binary
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
 +toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo
+vreplace +wildignore +wildmenu +windows +writebackup +X11 -xfontset +xim
+xsmp_interact +xterm_clipboard -xterm_save
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
      user exrc file: "$HOME/.exrc"
  system gvimrc file: "$VIM/gvimrc"
    user gvimrc file: "$HOME/.gvimrc"
    system menu file: "$VIMRUNTIME/menu.vim"
  fall-back for $VIM: "/depot/vim-7.3/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -I/usr/include/gtk-2.0 -I/usr/lib64/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12     -g -O2 -D_FORTIFY_SOURCE=1
Linking: gcc   -L/usr/local/lib -o vim   -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lgdk_pixbuf-2.0 -lpangocairo-1.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lglib-2.0   -lXt -lm -lncurses -lselinux -lacl
</code>```

答:
As none of the above answers worked for me (OSX Sierra), I will provide what I think should work in any (of the usual?) configuration of vim.

As the OP, in OSX vim relies on the plugin MatchParen for highlighting the matching parentheses. Thus, :set noshowmatch will not work. However, :NoMatchParen works.

The question is now to configure our ~/.vimrc so that this plugin is disabled by default when opening a file.

As it's common to import our ~/.vimrc from old system to any new accounts, and in the new system highlighting might be toggled by show match, the following will address the issue automatically in both instances:

In your ~/.vimrc add the following lines:

```<code>" Disable parentheses matching depends on system. This way we should address all cases (?)
set noshowmatch
" NoMatchParen " This doesnt work as it belongs to a plugin, which is only loaded _after_ all files are.
" Trying disable MatchParen after loading all plugins
"
function! g:FckThatMatchParen ()
    if exists(":NoMatchParen")
        :NoMatchParen
    endif
endfunction

augroup plugin_initialize
    autocmd!
    autocmd VimEnter * call FckThatMatchParen()
augroup END
</code>```

Note: the END in the last augroup line is important. Without it you get a pesky notification when calling vim before your file gets open:

```<code>$ vi my file.txt
plugin_initialize
Press ENTER or type command to continue
</code>```

Body:
How to disable auto highlighting of Matched Parentheses (cursor briefly jumping to the matched bracket, when a new bracket is inserted) in ViM?

When I faced this issue in my earlier company, then I was able to resolve it by adding below line to my .vimrc

let loaded_matchparen = 1

Now in my new company I am facing the same problem. But now the issue doesn't go even with above line in my .vimrc.

I tried adding, NoMatchParen to my .vimrc, I am getting following error when opening ViM:

Error detected while processing <...>/.vimrc:
E492: Not an editor command: NoMatchParen

Pl. let me know a work around for this annoying issue.

FYR, Output of my $ vim --version:

VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Feb 11 2012 21:05:37)
Compiled by rvictor@depbldrh61
Huge version with GTK2 GUI.  Features included (+) or not (-):
+arabic +autocmd +balloon_eval +browse ++builtin_terms +byte_offset +cindent
+clientserver +clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
+conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con_gui +diff
+digraphs +dnd -ebcdic +emacs_tags +eval +ex_extra +extra_search +farsi
+file_in_path +find_in_path +float +folding -footer +fork() +gettext
-hangul_input +iconv +insert_expand +jumplist +keymap +langmap +libcall
+linebreak +lispindent +listcmds +localmap -lua +menu +mksession +modify_fname
+mouse +mouseshape +mouse_dec -mouse_gpm -mouse_jsbterm +mouse_netterm
-mouse_sysmouse +mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg
-osfiletype +path_extra -perl +persistent_undo +postscript +printer +profile
-python -python3 +quickfix +reltime +rightleft -ruby +scrollbind +signs
+smartindent -sniff +startuptime +statusline -sun_workshop +syntax +tag_binary
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
 +toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo
+vreplace +wildignore +wildmenu +windows +writebackup +X11 -xfontset +xim
+xsmp_interact +xterm_clipboard -xterm_save
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
      user exrc file: "$HOME/.exrc"
  system gvimrc file: "$VIM/gvimrc"
    user gvimrc file: "$HOME/.gvimrc"
    system menu file: "$VIMRUNTIME/menu.vim"
  fall-back for $VIM: "/depot/vim-7.3/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -I/usr/include/gtk-2.0 -I/usr/lib64/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12     -g -O2 -D_FORTIFY_SOURCE=1
Linking: gcc   -L/usr/local/lib -o vim   -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lgdk_pixbuf-2.0 -lpangocairo-1.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lglib-2.0   -lXt -lm -lncurses -lselinux -lacl

Body:
As none of the above answers worked for me (OSX Sierra), I will provide what I think should work in any (of the usual?) configuration of vim.

As the OP, in OSX vim relies on the plugin MatchParen for highlighting the matching parentheses. Thus, :set noshowmatch will not work. However, :NoMatchParen works.

The question is now to configure our ~/.vimrc so that this plugin is disabled by default when opening a file.

As it's common to import our ~/.vimrc from old system to any new accounts, and in the new system highlighting might be toggled by show match, the following will address the issue automatically in both instances:

In your ~/.vimrc add the following lines:

" Disable parentheses matching depends on system. This way we should address all cases (?)
set noshowmatch
" NoMatchParen " This doesnt work as it belongs to a plugin, which is only loaded _after_ all files are.
" Trying disable MatchParen after loading all plugins
"
function! g:FckThatMatchParen ()
    if exists(":NoMatchParen")
        :NoMatchParen
    endif
endfunction

augroup plugin_initialize
    autocmd!
    autocmd VimEnter * call FckThatMatchParen()
augroup END

Note: the END in the last augroup line is important. Without it you get a pesky notification when calling vim before your file gets open:

$ vi my file.txt
plugin_initialize
Press ENTER or type command to continue


问:
Function in button
So I'm working on a wordpress theme and it's really twisted. The problem is I'm comfortable just with html and css, as I'm a code noob, so I would really appreciate your help here.

The problem here is that I want to put a tracking script and a redirect on a specific button. I'd now how to do this if I'd find the button's html form.

But when I go to the code in the page where the button is, this is the only thing showing regarding the button

```<code>    <?php BookYourTravel_Theme_Utils::render_submit_button("primary-btn",
    "submit-accommodation-booking", esc_html__('TRIMITE REZERVAREA',
    'bookyourtravel')); ?>
</code>```

BookYourTravel is the theme

I know you should maybe see all the files to know what to do, as this doesn't seem as enough info.
But I also have a functions.php file. Should I look there? Do you have any idea where should I go?

Thank you a lot. Really stuck here.

答: You didn't really give enough information for us to do anything. So if you are really pulling your hair on this one just replace the old button with a new button that you wrote. I can help you out on that end if you don't know javascript. </p>

Title: Function in button

Body:
So I'm working on a wordpress theme and it's really twisted. The problem is I'm comfortable just with html and css, as I'm a code noob, so I would really appreciate your help here.

The problem here is that I want to put a tracking script and a redirect on a specific button. I'd now how to do this if I'd find the button's html form.

But when I go to the code in the page where the button is, this is the only thing showing regarding the button

    <?php BookYourTravel_Theme_Utils::render_submit_button("primary-btn",
    "submit-accommodation-booking", esc_html__('TRIMITE REZERVAREA',
    'bookyourtravel')); ?>

BookYourTravel is the theme

I know you should maybe see all the files to know what to do, as this doesn't seem as enough info.
But I also have a functions.php file. Should I look there? Do you have any idea where should I go?

Thank you a lot. Really stuck here.


问:
Using registration free com in a .NET app
I'm trying to use a 3rd party COM DLL (I don't believe its a .NET component) from a .NET service without registering the COM DLL but I'm having no luck so far.

I've copied the manifest files from here (http://stackoverflow.com/questions/465882/generate-manifest-files-for-registration-free-com) to use as a starting point (I generated the COM DLL manifest using the referenced mt.exe/regsvr42.exe). However all I get is the following error:

Exception: System.InvalidCastException
Message: Unable to cast COM object of type 'LOGICLib.LogicClass' to interface type 'LOGICLib.ILogic'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAA3E8FB4}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Source: Interop.LOGICLib
   at LOGICLib.LogicSecuredClass.Connect(String IP, UInt16 Value, Int32& Result)
   at My.Server.MyAssembly.Loader.Connect() in D:\MyProject\Source\Server\MyAssembly\Loader.cs:line 461

The application manifest is named after the exe that starts the service - I've also tried naming it after the assembly that calls the COM DLL. I've tried starting on the command line and via Visual Studio's debugger. I've also tried using the Interop file supplied by the third party and generating my own.

(Note - I've only tested under Windows XP so far.)

I've spent two days on this now and have not progressed at all. Any ideas what I may have missed?

答:
Well, from the exception, you're getting a cast error when trying to cast an object of type LogicClass to an interface type of ILogic.  Looks like LogicClass doesn't implement ILogic.

You didn't supply what the DLL is or where you got it, so you're best bet is to look at the documentation for the library you're trying to use.  Just a wild guess, but it looks like you're implementing it incorrectly.

ContentLicense: CC BY-SA 2.5


问:
SQL how can I have sql return one row instead of multiple per distinct ID?
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

```<code>ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50
</code>```

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

```<code>SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID
</code>```

that worked fine.  I would get

```<code>01 2016-08-21
02 2016-10-01
</code>```

I soon realized that I also need PERCENT column.

```<code>SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT
</code>```

but now, I'm getting the multiple rows for ID 01 which is wrong...

```<code>01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50
</code>```

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

```<code>01  2016-08-21  1111  52
02  2016-10-01  1111  50
</code>```

答:
IF you database supports row_number() over() then using that function is an excellent way of determining which rows are "the earliest" like this:

```<code>select *
from (
       select *
          , row_number() over(partition by ID, CODE order by DATE ASC) as is_oldest
       from YOURTABLE
       where DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
       and CODE = 1111
     ) d
where is_oldest = 1
</code>```

The significant advantage of this is it provides access to the whole row associated with "the oldest" without needing a join.

Note the flexibility of this approach too, it can easily be extended e.g.

```<code>select *
from (
       select *
          , row_number() over(partition by ID, CODE order by date ASC) as is_oldest
          , row_number() over(partition by ID, CODE order by date DESC) as is_recent
       from your_table
       WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
       AND   CODE = 1111
     ) d
where is_oldest = 1
or is_recent = 1
</code>```

All one has to do to get "the most recent" is change the order from ASCending to DESCending.

NB: MySQL prior to v8 does not support "window functions such as row_number, but it is planned at v8 onward. Many other databases do support this function.

Body:
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID

that worked fine.  I would get

01 2016-08-21
02 2016-10-01

I soon realized that I also need PERCENT column.

SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT

but now, I'm getting the multiple rows for ID 01 which is wrong...

01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

01  2016-08-21  1111  52
02  2016-10-01  1111  50

Body:
IF you database supports row_number() over() then using that function is an excellent way of determining which rows are "the earliest" like this:

select *
from (
       select *
          , row_number() over(partition by ID, CODE order by DATE ASC) as is_oldest
       from YOURTABLE
       where DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
       and CODE = 1111
     ) d
where is_oldest = 1

The significant advantage of this is it provides access to the whole row associated with "the oldest" without needing a join.

Note the flexibility of this approach too, it can easily be extended e.g.

select *
from (
       select *
          , row_number() over(partition by ID, CODE order by date ASC) as is_oldest
          , row_number() over(partition by ID, CODE order by date DESC) as is_recent
       from your_table
       WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
       AND   CODE = 1111
     ) d
where is_oldest = 1
or is_recent = 1

All one has to do to get "the most recent" is change the order from ASCending to DESCending.

NB: MySQL prior to v8 does not support "window functions such as row_number, but it is planned at v8 onward. Many other databases do support this function.


问:
SQL Query to JSON
Hi I am new to JSON and would like to ask this question:

So my goal is trying to make the result look like this:

```<code>{
    "userid": "10293304" ,     "segments": ["Online_Flag"]
}

{
    "userid": "10292298" , "segments": ["schedule_Appointment", "Enrolled_Order","Complete_Order"]

}
</code>```

I was able to use T SQL to query the result to look like this:

```<code>[{"userid":"10293159","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10293056","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10292838","segments":[{"segment":"Schedule_Appointment"}]},
</code>```

The issue is that I only need to show the JSON value (Schedule_Appointment), not the key(segment)

is there any way (using TSQL) to hide the keys and only show the values in JSON Array?

I have tried to look for ways to create JSON array using SQL but no luck, if anyone can explain I would really appreciate.

SQL SERVER 2016

Data

```<code>CREATE TABLE [dbo].[Lotame_JSON](
[lead_id] [varchar](100) NULL,
[dist_date_key] [date] NULL,
[online_flag] [int] NULL,
[sched_appt_qty] [int] NULL,
[enroll_order_qty] [int] NULL,
[compl_order_qty] [int] NULL)

insert into [dbo].[Lotame_JSON]
values('105646','2016-12-1',1,0,0,1)

insert into [dbo].[Lotame_JSON]
values('125646','2016-12-1',0,0,1,0)

insert into [dbo].[Lotame_JSON]
values('112646','2016-12-1',0,1,1,0)

insert into [dbo].[Lotame_JSON]
values('106446','2016-12-1',0,0,1,0)
</code>```

Query I have:

```<code>select
[lead_id] AS 'userid',
(
SELECT segment
    from
    (
        SELECT
            CASE WHEN [online_flag] > 0 THEN '1' else null end as 'online_flag',
            CASE WHEN sched_appt_qty > 0 THEN '2' else null end as 'Schedule_Appointment',
            CASE WHEN enroll_order_qty > 0 THEN '3'  else null end as 'Enrolled_Order',
            CASE WHEN compl_order_qty > 0 THEN '4'  else null end as 'Complete_Order'
        FROM [dbo].[Lotame_JSON] as sub
        WHERE sub.lead_id = main.lead_id
    ) t
    UNPIVOT
    (
        segment1
        for segment in (online_flag,Schedule_Appointment,Enrolled_Order,Complete_Order)
    ) as UnPvot
    for JSON PATH
) AS 'segments'
from [dbo].[Lotame_JSON] as main
where online_flag = 0 and (sched_appt_qty > 0 or enroll_order_qty > 0   or    compl_order_qty > 0)
and dist_date_key >= '2016-9-1'
FOR JSON PATH
</code>```

Thanks

答:
You're very close. There's a trick to getting JSON arrays formatted correctly in SQL. You use a combination of JSON_QUERY, STUFF, and FOR XML PATH on the data you want in the array. And to get results without the outer-most square brackets, use FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Put it all together and you get a query that looks like this:

```<code>SELECT
userid = [lead_id]
,segments = JSON_QUERY(
                        '[' + STUFF(
                                    (
                                        SELECT ',' + '"' +  segment + '"'
                                        FROM
                                        (
                                            SELECT
                                                CASE WHEN [online_flag] > 0 THEN '1' ELSE NULL END AS 'online_flag',
                                                CASE WHEN sched_appt_qty > 0 THEN '2' ELSE NULL END AS 'Schedule_Appointment',
                                                CASE WHEN enroll_order_qty > 0 THEN '3' ELSE NULL END AS 'Enrolled_Order',
                                                CASE WHEN compl_order_qty > 0 THEN '4' ELSE NULL END AS 'Complete_Order'
                                            FROM [dbo].[Lotame_JSON] AS sub
                                            WHERE sub.lead_id = main.lead_id
                                        ) t
                                        UNPIVOT
                                        (
                                            segment1 FOR segment IN (online_flag, Schedule_Appointment, Enrolled_Order, Complete_Order)
                                        ) AS UnPvot
                                        FOR XML PATH ('')
                                    )
                        , 1, 1, '') + ']'
                    )
FROM [dbo].[Lotame_JSON] AS main
WHERE online_flag = 0
    AND dist_date_key >= '2016-9-1'
    AND (
            sched_appt_qty > 0
            OR enroll_order_qty > 0
            OR compl_order_qty > 0
        )
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
</code>```

Title: SQL Query to JSON

Body:
Hi I am new to JSON and would like to ask this question:

So my goal is trying to make the result look like this:

{
    "userid": "10293304" ,     "segments": ["Online_Flag"]
}

{
    "userid": "10292298" , "segments": ["schedule_Appointment", "Enrolled_Order","Complete_Order"]

}

I was able to use T SQL to query the result to look like this:

[{"userid":"10293159","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10293056","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10292838","segments":[{"segment":"Schedule_Appointment"}]},

The issue is that I only need to show the JSON value (Schedule_Appointment), not the key(segment)

is there any way (using TSQL) to hide the keys and only show the values in JSON Array?

I have tried to look for ways to create JSON array using SQL but no luck, if anyone can explain I would really appreciate.

SQL SERVER 2016

Data

CREATE TABLE [dbo].[Lotame_JSON](
[lead_id] [varchar](100) NULL,
[dist_date_key] [date] NULL,
[online_flag] [int] NULL,
[sched_appt_qty] [int] NULL,
[enroll_order_qty] [int] NULL,
[compl_order_qty] [int] NULL)

insert into [dbo].[Lotame_JSON]
values('105646','2016-12-1',1,0,0,1)

insert into [dbo].[Lotame_JSON]
values('125646','2016-12-1',0,0,1,0)

insert into [dbo].[Lotame_JSON]
values('112646','2016-12-1',0,1,1,0)

insert into [dbo].[Lotame_JSON]
values('106446','2016-12-1',0,0,1,0)

Query I have:

select
[lead_id] AS 'userid',
(
SELECT segment
    from
    (
        SELECT
            CASE WHEN [online_flag] > 0 THEN '1' else null end as 'online_flag',
            CASE WHEN sched_appt_qty > 0 THEN '2' else null end as 'Schedule_Appointment',
            CASE WHEN enroll_order_qty > 0 THEN '3'  else null end as 'Enrolled_Order',
            CASE WHEN compl_order_qty > 0 THEN '4'  else null end as 'Complete_Order'
        FROM [dbo].[Lotame_JSON] as sub
        WHERE sub.lead_id = main.lead_id
    ) t
    UNPIVOT
    (
        segment1
        for segment in (online_flag,Schedule_Appointment,Enrolled_Order,Complete_Order)
    ) as UnPvot
    for JSON PATH
) AS 'segments'
from [dbo].[Lotame_JSON] as main
where online_flag = 0 and (sched_appt_qty > 0 or enroll_order_qty > 0   or    compl_order_qty > 0)
and dist_date_key >= '2016-9-1'
FOR JSON PATH

Thanks

Body:
You're very close. There's a trick to getting JSON arrays formatted correctly in SQL. You use a combination of JSON_QUERY, STUFF, and FOR XML PATH on the data you want in the array. And to get results without the outer-most square brackets, use FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Put it all together and you get a query that looks like this:

SELECT
userid = [lead_id]
,segments = JSON_QUERY(
                        '[' + STUFF(
                                    (
                                        SELECT ',' + '"' +  segment + '"'
                                        FROM
                                        (
                                            SELECT
                                                CASE WHEN [online_flag] > 0 THEN '1' ELSE NULL END AS 'online_flag',
                                                CASE WHEN sched_appt_qty > 0 THEN '2' ELSE NULL END AS 'Schedule_Appointment',
                                                CASE WHEN enroll_order_qty > 0 THEN '3' ELSE NULL END AS 'Enrolled_Order',
                                                CASE WHEN compl_order_qty > 0 THEN '4' ELSE NULL END AS 'Complete_Order'
                                            FROM [dbo].[Lotame_JSON] AS sub
                                            WHERE sub.lead_id = main.lead_id
                                        ) t
                                        UNPIVOT
                                        (
                                            segment1 FOR segment IN (online_flag, Schedule_Appointment, Enrolled_Order, Complete_Order)
                                        ) AS UnPvot
                                        FOR XML PATH ('')
                                    )
                        , 1, 1, '') + ']'
                    )
FROM [dbo].[Lotame_JSON] AS main
WHERE online_flag = 0
    AND dist_date_key >= '2016-9-1'
    AND (
            sched_appt_qty > 0
            OR enroll_order_qty > 0
            OR compl_order_qty > 0
        )
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER


问:
how to extract BIC from several regression results by apply function in r
I already have several regression results, e.g. fit1, fit2, fit3.
And I want to extract BIC from the regression result by using apply function.

Question is, when I code as follow:

```<code>fitresult = cbind(fit1, fit2, fit3)
BIC = apply(fitresult, 2, BIC)
</code>```

It shows error:

```<code>Error in UseMethod("logLik") : no applicable method for 'logLik'
applied to an object of class "list"
</code>```

I checked and find class(fitresult[1]) = 'list' and loglik cannot apply on 'list' class. I think this error means I cannot use BIC(fitresult[1]) because fitresult[1] is not a fit result object.

So how can I use apply function to make each component in fitresult applied by apply function? By changing the class of each component?

答:
TL;DR: The cbind operation strips the model class (for example, class is lm if the model object was created with the lm function) from the model objects, but BIC expects an object with a model class (like lm or glm). Instead, do lapply(list(fit1, fit2, fit3), BIC) and BIC will work.

Assuming fit1, fit2, and fit3 are objects that resulted from running a modeling function (like lm or glm), then these are objects are lists containing the model output (for example, run str(fit1).

BIC is expecting a model object (for example, if the model was created with lm, the output object would be a list of class lm). However, the output of cbind(fit1, fit2, fit3) has class matrix, and each column contains all the sub-list elements from a given model object (for example, type fitresult, class(fitresult), fitresult[1, ], and fitresult[2, ] in the console and see what happens). However, these columns of fitresult no longer have the model class lm attached to them, so BIC doesn't know how to operate on them. For example, if you used lm to create the model then class(fit1) would return lm. But after the cbind operation. note that class(fitresult[ ,1]) returns list.

Instead, put these model objects into a list and use lapply to run BIC on each model object:

```<code>lapply(list(fit1, fit2, fit3), BIC)
</code>```

The output should be a list where each element is the BIC from a given model. If you want the output as a vector, you can do:

```<code>sapply(list(fit1, fit2, fit3), BIC)
</code>```

Body:
I already have several regression results, e.g. fit1, fit2, fit3.
And I want to extract BIC from the regression result by using apply function.

Question is, when I code as follow:

fitresult = cbind(fit1, fit2, fit3)
BIC = apply(fitresult, 2, BIC)

It shows error:

Error in UseMethod("logLik") : no applicable method for 'logLik'
applied to an object of class "list"

I checked and find class(fitresult[1]) = 'list' and loglik cannot apply on 'list' class. I think this error means I cannot use BIC(fitresult[1]) because fitresult[1] is not a fit result object.

So how can I use apply function to make each component in fitresult applied by apply function? By changing the class of each component?

Body:
TL;DR: The cbind operation strips the model class (for example, class is lm if the model object was created with the lm function) from the model objects, but BIC expects an object with a model class (like lm or glm). Instead, do lapply(list(fit1, fit2, fit3), BIC) and BIC will work.

Assuming fit1, fit2, and fit3 are objects that resulted from running a modeling function (like lm or glm), then these are objects are lists containing the model output (for example, run str(fit1).

BIC is expecting a model object (for example, if the model was created with lm, the output object would be a list of class lm). However, the output of cbind(fit1, fit2, fit3) has class matrix, and each column contains all the sub-list elements from a given model object (for example, type fitresult, class(fitresult), fitresult[1, ], and fitresult[2, ] in the console and see what happens). However, these columns of fitresult no longer have the model class lm attached to them, so BIC doesn't know how to operate on them. For example, if you used lm to create the model then class(fit1) would return lm. But after the cbind operation. note that class(fitresult[ ,1]) returns list.

Instead, put these model objects into a list and use lapply to run BIC on each model object:

lapply(list(fit1, fit2, fit3), BIC)

The output should be a list where each element is the BIC from a given model. If you want the output as a vector, you can do:

sapply(list(fit1, fit2, fit3), BIC)


答:
You can use student table and a subquery. The subquery is the distinct list of all students that dine on Monday, then run a left outerjoin of student and subquery b where b.SID is null;

```<code>select S.SName from Student as S
Left Outer Join
(select Distinct S2.SID from Student as S2 Inner Join Dinner as D on S2.SID=D.SID where D.DinnerDay='Monday') as tbMonStd
on S.SID=tbMonStd.SID
where tbMonStd.SID IS NULL
</code>```

The Subquery gives you the list of all students attached to Monday. The left outerjoin and the last where clause gives you the students not found in Monday list

Title: MS SQL Not Like Query

Body:
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.

SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName

Body:
You can use student table and a subquery. The subquery is the distinct list of all students that dine on Monday, then run a left outerjoin of student and subquery b where b.SID is null;

select S.SName from Student as S
Left Outer Join
(select Distinct S2.SID from Student as S2 Inner Join Dinner as D on S2.SID=D.SID where D.DinnerDay='Monday') as tbMonStd
on S.SID=tbMonStd.SID
where tbMonStd.SID IS NULL

The Subquery gives you the list of all students attached to Monday. The left outerjoin and the last where clause gives you the students not found in Monday list


问:
Nodejs process hang, how could I debug it or collect dump?
my nodejs process which was running at Linux, now it is hang and the CPU is 100%. Is there anyway I can do to debug it and find the reason? Do I need to collect dump and how? Thanks.</p>

答:
There's an npm module called why-is-node-running that can give you info like:</p>

```<code>There are 4 known handle(s) keeping the process running and 0 unknown
Known handles:

# Timer
/Users/maf/dev/node_modules/why-is-node-running/example.js:6  - setInterval(function () {}, 1000)
/Users/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()

# TCP
/Users/maf/dev/node_modules/why-is-node-running/example.js:7  - server.listen(0)
/Users/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()

# TCP
/Users/maf/dev/node_modules/why-is-node-running/example.js:7  - server.listen(0)
/Users/maf/dev/node_modules/why-is-node-running/example.js:11 - createServer()

# Timer
/Users/maf/dev/node_modules/why-is-node-running/example.js:13 - setTimeout(function () {
</code>```

Body:
There's an npm module called why-is-node-running that can give you info like:

There are 4 known handle(s) keeping the process running and 0 unknown
Known handles:

# Timer
/Users/maf/dev/node_modules/why-is-node-running/example.js:6  - setInterval(function () {}, 1000)
/Users/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()

# TCP
/Users/maf/dev/node_modules/why-is-node-running/example.js:7  - server.listen(0)
/Users/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()

# TCP
/Users/maf/dev/node_modules/why-is-node-running/example.js:7  - server.listen(0)
/Users/maf/dev/node_modules/why-is-node-running/example.js:11 - createServer()

# Timer
/Users/maf/dev/node_modules/why-is-node-running/example.js:13 - setTimeout(function () {


问:
In jena: How can i load an ontology once?
I need to load an ontology once only in Jena. My method which contains the SPARQL query also contains the

Model model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
model =  FileManager.get().loadModel("c:/jena/ICD.owl");
```

<p>It all works well except every time a conduct a query the method reloads the ontology.
I need the ontology to be loaded once only and the 'model' variable to be 'seen' in the method. If I move the two model statements into the main class the method can't see 'model'. There are no global variables in Java. </p>

<p>Here is the code:</p>

``` class store {
        Model model = ModelFactory.createOntologyModel(     OntModelSpec.OWL_MEM );
         public void myQuery() {
                String pattern = "\\#(.*)$";
                model =  FileManager.get().loadModel("c:/jena/ICD.owl");
                String singleQueryWord1="VEnTRICULAR FIBRILLATION";
                String firstQueryWord2="pedestrian";
                String secondQueryWord2="car";
                String queryPattern1="("+singleQueryWord1+"(.*))";
                String queryPattern2="("+firstQueryWord2+"(.|\\n)*"+secondQueryWord2+")|("+secondQueryWord2+"(.|\\n)*"+firstQueryWord2+")";

                Pattern r = Pattern.compile(pattern);

                String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\r\n" +
                        "PREFIX afn:<http://jena.apache.org/ARQ/function#>\r\n"+
                        "PREFIX owl: <http://www.w3.org/2002/07/owl#>\r\n" +
                        "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\r\n" +
                        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" +
                        "PREFIX dc: <http://purl.org/dc/elements/1.1/>\r\n" +
                        "SELECT DISTINCT ?subject ?object\r\n" +

                        "   WHERE {\r\n"+

                         "?subject dc:title ?object \r\n" +

                        "FILTER regex(?object,\""+ queryPattern1 +"\",\"i\")\r\n" +
                        //"FILTER regex( ?object,\"( pedestrian (.|\\n)* car )|( car (.|\\n)* pedestrian )\",\"i\")\r\n"+
                        "}"
                         ;

                  Query query = QueryFactory.create(queryString) ;
                  try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
                        ResultSet results = qexec.execSelect() ;
                        if(!results.hasNext()) {
                            System.out.println("No results");
                        }else
                        for ( ; results.hasNext() ; )
                        {

                            QuerySolution soln = results.nextSolution();
                            Resource subj = (Resource) soln.get("?subject");

                            String subStr = subj.toString();
                            Matcher m = r.matcher(subStr);

                                if(m.find()) {
                            Literal obj = (Literal) soln.get("?object");
                            System.out.println(m.group()+" ........ "+obj);
                            }

                            m.reset();

                        }

                  } catch(Exception e) {
                        System.out.println(e.getMessage());
                         }
                }
    }
```

Many thanks for any suggestions.
Phil

答:
I think I figured it out. I can load the ontology in the main method once only. Then I pass the model into the myQuery method. I sould be able to access the myQuery with getter and setters and not have to load the ontology every time I do a query.

```<code>public class SPARQLVeriations {
static private String singleQueryWord1="ventricular fibrillation";
static private String firstQueryWord2;
static private String secondQueryWord2;
static private Model model;
SPARQLVeriations sv = new SPARQLVeriations();

public static void main(String[] args) {

     model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
    model = FileManager.get().loadModel("c:/jena/ICD.owl");

     myQuery(model,singleQueryWord1,firstQueryWord2,secondQueryWord2);

}

private static void myQuery(Model model,String singleQueryWord1,String firstQueryWord2,String secondQueryWord2) {
    String pattern = "\\#(.*)$";

   // String singleQueryWord1="VEnTRICULAR FIBRILLATION";
    //String firstQueryWord2="pedestrian";
    //String secondQueryWord2="car";
    String queryPattern1="("+singleQueryWord1+"(.*))";
    Pattern r = Pattern.compile(pattern);

    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\r\n" +
            "PREFIX afn:<http://jena.apache.org/ARQ/function#>\r\n"+
            "PREFIX owl: <http://www.w3.org/2002/07/owl#>\r\n" +
            "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\r\n" +
            "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" +
            "PREFIX dc: <http://purl.org/dc/elements/1.1/>\r\n" +
            "SELECT DISTINCT ?subject ?object\r\n" +

            "   WHERE {\r\n"+

             "?subject dc:title ?object \r\n" +

            "FILTER regex(?object,\""+ queryPattern1 +"\",\"i\")\r\n" +
            //"FILTER regex( ?object,\"( pedestrian (.|\\n)* car )|( car (.|\\n)* pedestrian )\",\"i\")\r\n"+
            "}"
             ;

      Query query = QueryFactory.create(queryString) ;
      try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
            ResultSet results = qexec.execSelect() ;
            if(!results.hasNext()) {
                System.out.println("No results");
            }else
            for ( ; results.hasNext() ; )
            {

                QuerySolution soln = results.nextSolution();
                Resource subj = (Resource) soln.get("?subject");

                String subStr = subj.toString();
                Matcher m = r.matcher(subStr);

                    if(m.find()) {
                Literal obj = (Literal) soln.get("?object");
                System.out.println(m.group()+" ........ "+obj);
                }

                m.reset();

            }

      } catch(Exception e) {
            System.out.println(e.getMessage());
             }

}
public void setQuery1() { }
</code>```

}

Body:
I need to load an ontology once only in Jena. My method which contains the SPARQL query also contains the

Model model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
model =  FileManager.get().loadModel("c:/jena/ICD.owl");

It all works well except every time a conduct a query the method reloads the ontology.
I need the ontology to be loaded once only and the 'model' variable to be 'seen' in the method. If I move the two model statements into the main class the method can't see 'model'. There are no global variables in Java.

Here is the code:

 class store {
        Model model = ModelFactory.createOntologyModel(     OntModelSpec.OWL_MEM );
         public void myQuery() {
                String pattern = "\\#(.*)$";
                model =  FileManager.get().loadModel("c:/jena/ICD.owl");
                String singleQueryWord1="VEnTRICULAR FIBRILLATION";
                String firstQueryWord2="pedestrian";
                String secondQueryWord2="car";
                String queryPattern1="("+singleQueryWord1+"(.*))";
                String queryPattern2="("+firstQueryWord2+"(.|\\n)*"+secondQueryWord2+")|("+secondQueryWord2+"(.|\\n)*"+firstQueryWord2+")";

                Pattern r = Pattern.compile(pattern);

                String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\r\n" +
                        "PREFIX afn:<http://jena.apache.org/ARQ/function#>\r\n"+
                        "PREFIX owl: <http://www.w3.org/2002/07/owl#>\r\n" +
                        "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\r\n" +
                        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" +
                        "PREFIX dc: <http://purl.org/dc/elements/1.1/>\r\n" +
                        "SELECT DISTINCT ?subject ?object\r\n" +

                        "   WHERE {\r\n"+

                         "?subject dc:title ?object \r\n" +

                        "FILTER regex(?object,\""+ queryPattern1 +"\",\"i\")\r\n" +
                        //"FILTER regex( ?object,\"( pedestrian (.|\\n)* car )|( car (.|\\n)* pedestrian )\",\"i\")\r\n"+
                        "}"
                         ;

                  Query query = QueryFactory.create(queryString) ;
                  try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
                        ResultSet results = qexec.execSelect() ;
                        if(!results.hasNext()) {
                            System.out.println("No results");
                        }else
                        for ( ; results.hasNext() ; )
                        {

                            QuerySolution soln = results.nextSolution();
                            Resource subj = (Resource) soln.get("?subject");

                            String subStr = subj.toString();
                            Matcher m = r.matcher(subStr);

                                if(m.find()) {
                            Literal obj = (Literal) soln.get("?object");
                            System.out.println(m.group()+" ........ "+obj);
                            }

                            m.reset();

                        }

                  } catch(Exception e) {
                        System.out.println(e.getMessage());
                         }
                }
    }

Many thanks for any suggestions.
Phil

Body:
I think I figured it out. I can load the ontology in the main method once only. Then I pass the model into the myQuery method. I sould be able to access the myQuery with getter and setters and not have to load the ontology every time I do a query.

public class SPARQLVeriations {
static private String singleQueryWord1="ventricular fibrillation";
static private String firstQueryWord2;
static private String secondQueryWord2;
static private Model model;
SPARQLVeriations sv = new SPARQLVeriations();

public static void main(String[] args) {

     model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
    model = FileManager.get().loadModel("c:/jena/ICD.owl");

     myQuery(model,singleQueryWord1,firstQueryWord2,secondQueryWord2);

}

private static void myQuery(Model model,String singleQueryWord1,String firstQueryWord2,String secondQueryWord2) {
    String pattern = "\\#(.*)$";

   // String singleQueryWord1="VEnTRICULAR FIBRILLATION";
    //String firstQueryWord2="pedestrian";
    //String secondQueryWord2="car";
    String queryPattern1="("+singleQueryWord1+"(.*))";
    Pattern r = Pattern.compile(pattern);

    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\r\n" +
            "PREFIX afn:<http://jena.apache.org/ARQ/function#>\r\n"+
            "PREFIX owl: <http://www.w3.org/2002/07/owl#>\r\n" +
            "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\r\n" +
            "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" +
            "PREFIX dc: <http://purl.org/dc/elements/1.1/>\r\n" +
            "SELECT DISTINCT ?subject ?object\r\n" +

            "   WHERE {\r\n"+

             "?subject dc:title ?object \r\n" +

            "FILTER regex(?object,\""+ queryPattern1 +"\",\"i\")\r\n" +
            //"FILTER regex( ?object,\"( pedestrian (.|\\n)* car )|( car (.|\\n)* pedestrian )\",\"i\")\r\n"+
            "}"
             ;

      Query query = QueryFactory.create(queryString) ;
      try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
            ResultSet results = qexec.execSelect() ;
            if(!results.hasNext()) {
                System.out.println("No results");
            }else
            for ( ; results.hasNext() ; )
            {

                QuerySolution soln = results.nextSolution();
                Resource subj = (Resource) soln.get("?subject");

                String subStr = subj.toString();
                Matcher m = r.matcher(subStr);

                    if(m.find()) {
                Literal obj = (Literal) soln.get("?object");
                System.out.println(m.group()+" ........ "+obj);
                }

                m.reset();

            }

      } catch(Exception e) {
            System.out.println(e.getMessage());
             }

}
public void setQuery1() { }

}


问:
completionHandler of AVAudioPlayerNode.scheduleFile() is called too early
I am trying to use the new AVAudioEngine in iOS 8.

It looks like the completionHandler of player.scheduleFile() is called before the sound file has finished playing.

I am using a sound file with a length of 5s -- and the println()-Message appears round about 1 second before the end of the sound.

Am I doing something wrong or do I misunderstand the idea of a completionHandler?

Thanks!

Here is some code:

```<code>class SoundHandler {
    let engine:AVAudioEngine
    let player:AVAudioPlayerNode
    let mainMixer:AVAudioMixerNode

    init() {
        engine = AVAudioEngine()
        player = AVAudioPlayerNode()
        engine.attachNode(player)
        mainMixer = engine.mainMixerNode

        var error:NSError?
        if !engine.startAndReturnError(&error) {
            if let e = error {
                println("error \(e.localizedDescription)")
            }
        }

        engine.connect(player, to: mainMixer, format: mainMixer.outputFormatForBus(0))
    }

    func playSound() {
        var soundUrl = NSBundle.mainBundle().URLForResource("Test", withExtension: "m4a")
        var soundFile = AVAudioFile(forReading: soundUrl, error: nil)

        player.scheduleFile(soundFile, atTime: nil, completionHandler: { println("Finished!") })

        player.play()
    }
}
</code>```

答:
My bug report for this was closed as "works as intended," but Apple pointed me to new variations of the scheduleFile, scheduleSegment and scheduleBuffer methods in iOS 11. These add a completionCallbackType argument that you can use to specify that you want the completion callback when the playback is completed:

```<code>[self.audioUnitPlayer
            scheduleSegment:self.audioUnitFile
            startingFrame:sampleTime
            frameCount:(int)sampleLength
            atTime:0
            completionCallbackType:AVAudioPlayerNodeCompletionDataPlayedBack
            completionHandler:^(AVAudioPlayerNodeCompletionCallbackType callbackType) {
    // do something here
}];
</code>```

The documentation doesn't say anything about how this works, but I tested it and it works for me.

I've been using this workaround for iOS 8-10:

```<code>- (void)playRecording {
    [self.audioUnitPlayer scheduleSegment:self.audioUnitFile startingFrame:sampleTime frameCount:(int)sampleLength atTime:0 completionHandler:^() {
        float totalTime = [self recordingDuration];
        float elapsedTime = [self recordingCurrentTime];
        float remainingTime = totalTime - elapsedTime;
        [self performSelector:@selector(doSomethingHere) withObject:nil afterDelay:remainingTime];
    }];
}

- (float)recordingDuration {
    float duration = duration = self.audioUnitFile.length / self.audioUnitFile.processingFormat.sampleRate;
    if (isnan(duration)) {
        duration = 0;
    }
    return duration;
}

- (float)recordingCurrentTime {
    AVAudioTime *nodeTime = self.audioUnitPlayer.lastRenderTime;
    AVAudioTime *playerTime = [self.audioUnitPlayer playerTimeForNodeTime:nodeTime];
    AVAudioFramePosition sampleTime = playerTime.sampleTime;
    if (sampleTime == 0) { return self.audioUnitLastKnownTime; } // this happens when the player isn't playing
    sampleTime += self.audioUnitStartingFrame; // if we trimmed from the start, or changed the location with the location slider, the time before that point won't be included in the player time, so we have to track it ourselves and add it here
    float time = sampleTime / self.audioUnitFile.processingFormat.sampleRate;
    self.audioUnitLastKnownTime = time;
    return time;
}
</code>```

Body:
I am trying to use the new AVAudioEngine in iOS 8.

It looks like the completionHandler of player.scheduleFile() is called before the sound file has finished playing.

I am using a sound file with a length of 5s -- and the println()-Message appears round about 1 second before the end of the sound.

Am I doing something wrong or do I misunderstand the idea of a completionHandler?

Thanks!

Here is some code:

class SoundHandler {
    let engine:AVAudioEngine
    let player:AVAudioPlayerNode
    let mainMixer:AVAudioMixerNode

    init() {
        engine = AVAudioEngine()
        player = AVAudioPlayerNode()
        engine.attachNode(player)
        mainMixer = engine.mainMixerNode

        var error:NSError?
        if !engine.startAndReturnError(&error) {
            if let e = error {
                println("error \(e.localizedDescription)")
            }
        }

        engine.connect(player, to: mainMixer, format: mainMixer.outputFormatForBus(0))
    }

    func playSound() {
        var soundUrl = NSBundle.mainBundle().URLForResource("Test", withExtension: "m4a")
        var soundFile = AVAudioFile(forReading: soundUrl, error: nil)

        player.scheduleFile(soundFile, atTime: nil, completionHandler: { println("Finished!") })

        player.play()
    }
}

Body:
My bug report for this was closed as "works as intended," but Apple pointed me to new variations of the scheduleFile, scheduleSegment and scheduleBuffer methods in iOS 11. These add a completionCallbackType argument that you can use to specify that you want the completion callback when the playback is completed:

[self.audioUnitPlayer
            scheduleSegment:self.audioUnitFile
            startingFrame:sampleTime
            frameCount:(int)sampleLength
            atTime:0
            completionCallbackType:AVAudioPlayerNodeCompletionDataPlayedBack
            completionHandler:^(AVAudioPlayerNodeCompletionCallbackType callbackType) {
    // do something here
}];

The documentation doesn't say anything about how this works, but I tested it and it works for me.

I've been using this workaround for iOS 8-10:

- (void)playRecording {
    [self.audioUnitPlayer scheduleSegment:self.audioUnitFile startingFrame:sampleTime frameCount:(int)sampleLength atTime:0 completionHandler:^() {
        float totalTime = [self recordingDuration];
        float elapsedTime = [self recordingCurrentTime];
        float remainingTime = totalTime - elapsedTime;
        [self performSelector:@selector(doSomethingHere) withObject:nil afterDelay:remainingTime];
    }];
}

- (float)recordingDuration {
    float duration = duration = self.audioUnitFile.length / self.audioUnitFile.processingFormat.sampleRate;
    if (isnan(duration)) {
        duration = 0;
    }
    return duration;
}

- (float)recordingCurrentTime {
    AVAudioTime *nodeTime = self.audioUnitPlayer.lastRenderTime;
    AVAudioTime *playerTime = [self.audioUnitPlayer playerTimeForNodeTime:nodeTime];
    AVAudioFramePosition sampleTime = playerTime.sampleTime;
    if (sampleTime == 0) { return self.audioUnitLastKnownTime; } // this happens when the player isn't playing
    sampleTime += self.audioUnitStartingFrame; // if we trimmed from the start, or changed the location with the location slider, the time before that point won't be included in the player time, so we have to track it ourselves and add it here
    float time = sampleTime / self.audioUnitFile.processingFormat.sampleRate;
    self.audioUnitLastKnownTime = time;
    return time;
}


问:
How to auto-indent code in the Atom editor?
How do you auto-indent your code in the Atom editor? In other editors you can usually select some code and auto-indent it.

Is there a keyboard shortcut as well?

答:
This is the best help that I found:

https://atom.io/packages/atom-beautify

This package can be installed in Atom and then CTRL+ALT+B solve the problem.


问:
Reference to elements adds (unwanted) namespace to target xml
my overall goal is to break down a big xsd in several small xsd's, one especially holding elements and complex types I want to reuse in the other xsds. Say the type xsd is called "types.xsd" and the one of the other xsds is called "request.xsd"

That being said, I declared one central ID "evalancheId" as an element and try to reference (using ref) to them. However, the resulting XML comes with an unwanted namespace prefix "ns:evalancheId" for the referenced elemeent.

types.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://hansgrohe.com/pi/PA/C4C/Contact/10"
xmlns="http://hansgrohe.com/pi/PA/C4C/Contact/10">

<xsd:element name="evalancheId" type="xsd:int"/>

<xsd:complexType name="contactComplexType">
    <xsd:sequence>
        <xsd:element minOccurs="0" maxOccurs="1" name="givenName">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:minLength value="1"/>
                    <xsd:maxLength value="40"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
        <!-- ... -->
    </xsd:sequence>
</xsd:complexType>
</code>```

request.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://hansgrohe.com/pi/PA/C4C/Contact/10"
xmlns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
<xsd:include schemaLocation="types.xsd"/>
<xsd:element name="updateContactReq" type="contactUpgradeComplexType"/>
<xsd:complexType name="contactUpgradeComplexType">
    <xsd:complexContent>
        <xsd:extension base="contactComplexType">
            <xsd:sequence>
                <xsd:element ref="evalancheId" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>
</code>```

result.xml

```<code><ns:updateContactReq xmlns:ns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
    <givenName>Jay</givenName>
    <ns:evalancheId>0815</ns:evalancheId>
</ns:updateContactReq>
</code>```

actually_wanted.xml

```<code><ns:updateContactReq xmlns:ns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
    <givenName>Jay</givenName>
    <evalancheId>0815</evalancheId>
</ns:updateContactReq>
</code>```

Question

How can I get rid of the namespace in "ns:evalancheId" and yet reuse the evalancheId element

Many thanks and kind regards
Tschenser

答:
I don't believe you can. Only global elements are visible for reuse by the including/importing XSD. But global elements are always in the target namespace of their own XSD.
You could set elementFormDefault to 'unqualified' and declare the element as a local (i.e. non-global) element definition. But that would defeat your objective of having the element contained in a separate XSD.
I think the best solution for you would be to define the types in a separate XSD but the element declarations locally in your main XSD. That way, the element declaration can be local, while the complex type is defined in a separate XSD.

Body:
my overall goal is to break down a big xsd in several small xsd's, one especially holding elements and complex types I want to reuse in the other xsds. Say the type xsd is called "types.xsd" and the one of the other xsds is called "request.xsd"

That being said, I declared one central ID "evalancheId" as an element and try to reference (using ref) to them. However, the resulting XML comes with an unwanted namespace prefix "ns:evalancheId" for the referenced elemeent.

types.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://hansgrohe.com/pi/PA/C4C/Contact/10"
xmlns="http://hansgrohe.com/pi/PA/C4C/Contact/10">

<xsd:element name="evalancheId" type="xsd:int"/>

<xsd:complexType name="contactComplexType">
    <xsd:sequence>
        <xsd:element minOccurs="0" maxOccurs="1" name="givenName">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:minLength value="1"/>
                    <xsd:maxLength value="40"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>

    </xsd:sequence>
</xsd:complexType>

request.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://hansgrohe.com/pi/PA/C4C/Contact/10"
xmlns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
<xsd:include schemaLocation="types.xsd"/>
<xsd:element name="updateContactReq" type="contactUpgradeComplexType"/>
<xsd:complexType name="contactUpgradeComplexType">
    <xsd:complexContent>
        <xsd:extension base="contactComplexType">
            <xsd:sequence>
                <xsd:element ref="evalancheId" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

result.xml

<ns:updateContactReq xmlns:ns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
    <givenName>Jay</givenName>
    <ns:evalancheId>0815</ns:evalancheId>
</ns:updateContactReq>

actually_wanted.xml

<ns:updateContactReq xmlns:ns="http://hansgrohe.com/pi/PA/C4C/Contact/10">
    <givenName>Jay</givenName>
    <evalancheId>0815</evalancheId>
</ns:updateContactReq>

Question

How can I get rid of the namespace in "ns:evalancheId" and yet reuse the evalancheId element

Many thanks and kind regards
Tschenser


问:
Oracle left outer join return 0 rows with data in left dataset
I’m trying to get a list of hard-coded events and join in a table with actual events, so I can actually see if they were performed.

Here are my query:

```<code>SELECT a.Verification FROM (SELECT 'Verify ID changed' as Verification  FROM DUAL
UNION ALL
SELECT 'Verify manual Valve closed' as Verification FROM DUAL
UNION ALL
SELECT 'Verify manual Valve open' as Verification FROM DUAL
UNION ALL
SELECT 'Visually verify Things' as Verification FROM DUAL
) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
WHERE c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'
</code>```

When I read the documentation for LEFT Outer join, then queues should always return the data from the left table, so why is my query returning 0 rows (there is nothing in the JOBEVENTS events table but left hard-coded values are always there).

Am i misunderstanding how LEFT OUTER JOIN works?

答:
Make the filter on the left joined table part of the join, not the where clause.

```<code>SELECT a.Verification, c.*
FROM (
      SELECT 'Verify ID changed' as Verification  FROM DUAL UNION ALL
      SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL
      SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL
      SELECT 'Visually verify Things' as Verification FROM DUAL
      ) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
       AND c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'
;
</code>```

Alternatively, you can to add to your where clause so that NULLS may be returned from the left joined table. e.g.:

```<code>SELECT a.Verification, c.*
FROM (
      SELECT 'Verify ID changed' as Verification  FROM DUAL UNION ALL
      SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL
      SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL
      SELECT 'Visually verify Things' as Verification FROM DUAL
      ) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
WHERE ( c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'
      OR c.EVENTDESC IS NULL
      )
;
</code>```

Always take care with outer joined tables when referenced in the where clause that you permit NULLS from that table, otherwise you create the equivalent conditions of an inner join (& sometimes called "implied inner join").

Body:
I’m trying to get a list of hard-coded events and join in a table with actual events, so I can actually see if they were performed.

Here are my query:

SELECT a.Verification FROM (SELECT 'Verify ID changed' as Verification  FROM DUAL
UNION ALL
SELECT 'Verify manual Valve closed' as Verification FROM DUAL
UNION ALL
SELECT 'Verify manual Valve open' as Verification FROM DUAL
UNION ALL
SELECT 'Visually verify Things' as Verification FROM DUAL
) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
WHERE c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'

When I read the documentation for LEFT Outer join, then queues should always return the data from the left table, so why is my query returning 0 rows (there is nothing in the JOBEVENTS events table but left hard-coded values are always there).

Am i misunderstanding how LEFT OUTER JOIN works?

Body:
Make the filter on the left joined table part of the join, not the where clause.

SELECT a.Verification, c.*
FROM (
      SELECT 'Verify ID changed' as Verification  FROM DUAL UNION ALL
      SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL
      SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL
      SELECT 'Visually verify Things' as Verification FROM DUAL
      ) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
       AND c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'
;

Alternatively, you can to add to your where clause so that NULLS may be returned from the left joined table. e.g.:

SELECT a.Verification, c.*
FROM (
      SELECT 'Verify ID changed' as Verification  FROM DUAL UNION ALL
      SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL
      SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL
      SELECT 'Visually verify Things' as Verification FROM DUAL
      ) a
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC
WHERE ( c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017'
      OR c.EVENTDESC IS NULL
      )
;

Always take care with outer joined tables when referenced in the where clause that you permit NULLS from that table, otherwise you create the equivalent conditions of an inner join (& sometimes called "implied inner join").