问:
Why does my loop use 100% CPU and never end?
I have this method:

```<code>    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }
</code>```

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

```<code>    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }
</code>```

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

答:
This seems like an interesting issue here.  At first glance, it would appear that ReadLine has an issue with the handle being closed from under it while it's trying to read data, and thus would seem to be a bug in the Framework.  However, I'm not convinced that easily that it's a bug in the .Net framework...

However, there are a couple low level issues here.

The other answers you have got so far all suggest you modify the while loop.  I would do this as well, but I don't think this is the root of your problem.  You do not need a sleep in there, because you will get your waitstate from the ReadLine(), unless there is no data to read, and it just returns a failue, THEN you will 'tight-loop'.  So, make sure you are checking any and all error states during this loop.

If you do not, I can see issues.

If everything else is working as it should, then if I were you, I would start by trying to identify if you can duplicate it outside of your program with a small demo program.  I'm sure there is plenty of error checking in the Framework's Stream handling.  However, it looks like you are running some stuff from Cygwin, and that's the output you are reading from the cmd shell.

Try making a simple app that just spits out data to stdout, and stderr, and then make sure the app closes while you are still reading..

Also use the debugger to see what line== after the failure occurs.

Larry

OwnerDisplayName: Malfist

Body:
I have this method:

    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

LastEditorDisplayName: Rich B

OwnerDisplayName: LarryF


来源: stackexchange

问:
Parser/split const char* in c++
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";
</code>```

Example 2 of fildedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";
</code>```

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

```<code>1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
</code>```

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.

答:
Here is a solution using std::find() that should be pretty fast and efficient. The idea is you have an outer loop that finds each successive line ending '\n' and an inner loop that finds (within that range) each successive field ending ';'

In the heart of the two loops you get the opportunity to do whatever you like with the columns:

```<code>char const* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";

auto filesize = std::strlen(filedata);

auto line_beg = filedata;
auto line_end = filedata + filesize;

for(; auto line_pos = std::find(line_beg, line_end, '\n'); line_beg = line_pos + 1)
{
    auto field_beg = line_beg;
    auto field_end = line_pos;

    auto field_number = 0U;
    for(; auto field_pos = std::find(field_beg, field_end, ';'); field_beg = field_pos + 1)
    {
        ++field_number;

        // select the field number you want here
        if(field_number == 1 || field_number == 2)
        {
            // do something with the field that starts at field_beg
            // and ends at field_pos
            std::cout << ' ' << std::string(field_beg, field_pos);
        }

        if(field_pos == field_end)
            break;
    }

    std::cout << '\n';

    if(line_pos == line_end)
        break;
}
</code>```

Output:

```<code> 1496843100 2017-06-07 13:45:00
 1496843100 2017-06-07 13:45:00
 1496843100 2017-06-07 13:45:00
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parser/split const char* in c++

Body:
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";

Example 2 of fildedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.

Body:
Here is a solution using std::find() that should be pretty fast and efficient. The idea is you have an outer loop that finds each successive line ending '\n' and an inner loop that finds (within that range) each successive field ending ';'

In the heart of the two loops you get the opportunity to do whatever you like with the columns:

char const* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";

auto filesize = std::strlen(filedata);

auto line_beg = filedata;
auto line_end = filedata + filesize;

for(; auto line_pos = std::find(line_beg, line_end, '\n'); line_beg = line_pos + 1)
{
    auto field_beg = line_beg;
    auto field_end = line_pos;

    auto field_number = 0U;
    for(; auto field_pos = std::find(field_beg, field_end, ';'); field_beg = field_pos + 1)
    {
        ++field_number;

        // select the field number you want here
        if(field_number == 1 || field_number == 2)
        {
            // do something with the field that starts at field_beg
            // and ends at field_pos
            std::cout << ' ' << std::string(field_beg, field_pos);
        }

        if(field_pos == field_end)
            break;
    }

    std::cout << '\n';

    if(line_pos == line_end)
        break;
}

Output:

 1496843100 2017-06-07 13:45:00
 1496843100 2017-06-07 13:45:00
 1496843100 2017-06-07 13:45:00


问:
Loading '*.mat' correctly but form another unknown location
I got 2 functions in my matlab script. These functions exchange the data via a *.mat file.
In one of the functions, I read the number of specific files and a data from them. Later I process and store the variable ggd in proj1.mat file. As shown below :

```<code>    function browse_pushBtn_Callback(hObject, eventdata, handles)
% hObject    handle to browse_pushBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.directory = uigetdir('C:\temp\');
guidata(hObject,handles);
ggd.directory = handles.directory;
if (ggd.directory)
    set(handles.browse_textEdit,'String',handles.directory);
    disp2listbox(handles.mainLog_listBox, '1. Searching for GGD Datafile:');
    ggd = MyRead(ggd);
    disp2listbox(handles.mainLog_listBox, sprintf('     -%d Bilder
    gefunden',length(ggd.bilds)));
    save proj1 ggd;
else
    set(handles.browse_textEdit,'String','Select a directory');
end
</code>```

The Second function is :

```<code>function start_pushBtn_Callback(hObject, eventdata, handles)
% hObject    handle to start_pushBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

option = get(handles.mainMenu,'Value');
if (option == 1)
    disp2listbox(handles.mainLog_listBox, '2. Calculating the quadratic size..');
    fprintf('path is : %s\n', pwd); % did just to check the path (for debugging purpose)
    load proj1 ggd;
    ggd = MyProcess(ggd);
    save proj1 ggd;
    disp2listbox(handles.mainLog_listBox, sprintf('     -MySize: %d X %d',ggd.X(1), ggd.Y(2)));
    disp2listbox(handles.mainLog_listBox, '3. opening another function...');
    % call to another function
elseif (option == 2)
    disp2listbox(handles.mainLog_listBox, '2. opening third function...');
    % call to third different function
end
</code>```

The funny thing is that these two functions work perfectly fine when I run them in Matlab tool.
Later, I compile the standalone executable for my application. This standalone application works fine until the first function; but, when I call the second function, it loads the proj1.mat file from another unknown location that contains totally different data.

Have no idea what is the problem that causing such weird behaviour.

I checked the current paths (pwd) in second function while executing standalone
 and found it to be the same as the one in first function.

Any ideas ??

答:
If you need to keep writing and reading from a file in a deployed application, I would recommend creating a local directory in user's machine's App Data and storing all the files there. You can do this by using the following function from matlab central. E.g. something like

```<code>file_root = getapplicationdatadir('your.application.name',1,1);
</code>```

should create a directory (if it does not exist) on the user's computer where it will store all the files, and variable root will give you the absolute path to that directory. You can then use it to save and load the files. E.g.

```<code>save([file_root '/proj1.mat'],'ggd');
</code>```

in the first function, and

```<code>load([file_root '/proj1.mat'],'ggd');
</code>```

in the second function. This way you know exactly where the file is stored. Also, read the link I mentioned earlier in the comment.

Body:
I got 2 functions in my matlab script. These functions exchange the data via a *.mat file.
In one of the functions, I read the number of specific files and a data from them. Later I process and store the variable ggd in proj1.mat file. As shown below :

    function browse_pushBtn_Callback(hObject, eventdata, handles)
% hObject    handle to browse_pushBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.directory = uigetdir('C:\temp\');
guidata(hObject,handles);
ggd.directory = handles.directory;
if (ggd.directory)
    set(handles.browse_textEdit,'String',handles.directory);
    disp2listbox(handles.mainLog_listBox, '1. Searching for GGD Datafile:');
    ggd = MyRead(ggd);
    disp2listbox(handles.mainLog_listBox, sprintf('     -%d Bilder
    gefunden',length(ggd.bilds)));
    save proj1 ggd;
else
    set(handles.browse_textEdit,'String','Select a directory');
end

The Second function is :

function start_pushBtn_Callback(hObject, eventdata, handles)
% hObject    handle to start_pushBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

option = get(handles.mainMenu,'Value');
if (option == 1)
    disp2listbox(handles.mainLog_listBox, '2. Calculating the quadratic size..');
    fprintf('path is : %s\n', pwd); % did just to check the path (for debugging purpose)
    load proj1 ggd;
    ggd = MyProcess(ggd);
    save proj1 ggd;
    disp2listbox(handles.mainLog_listBox, sprintf('     -MySize: %d X %d',ggd.X(1), ggd.Y(2)));
    disp2listbox(handles.mainLog_listBox, '3. opening another function...');
    % call to another function
elseif (option == 2)
    disp2listbox(handles.mainLog_listBox, '2. opening third function...');
    % call to third different function
end

The funny thing is that these two functions work perfectly fine when I run them in Matlab tool.
Later, I compile the standalone executable for my application. This standalone application works fine until the first function; but, when I call the second function, it loads the proj1.mat file from another unknown location that contains totally different data.

Have no idea what is the problem that causing such weird behaviour.

I checked the current paths (pwd) in second function while executing standalone
 and found it to be the same as the one in first function.

Any ideas ??

Body:
If you need to keep writing and reading from a file in a deployed application, I would recommend creating a local directory in user's machine's App Data and storing all the files there. You can do this by using the following function from matlab central. E.g. something like

file_root = getapplicationdatadir('your.application.name',1,1);

should create a directory (if it does not exist) on the user's computer where it will store all the files, and variable root will give you the absolute path to that directory. You can then use it to save and load the files. E.g.

save([file_root '/proj1.mat'],'ggd');

in the first function, and

load([file_root '/proj1.mat'],'ggd');

in the second function. This way you know exactly where the file is stored. Also, read the link I mentioned earlier in the comment.


问:
MalformedURLException although I have already replaced spaces with %20
```<code>String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+origin+"&destinations="+destination+"&mode=driving&sensor=false&language=en-EN&units=imperial";
url = url.replaceAll(" ", "%20");
</code>```

Output :

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=150%20Sutter%20St%20San%20Francisco,%20CA,%20United%20States&destinations=1%20Palmer%20Sq%20E
Princeton,%20NJ%2008542&mode=driving&sensor=false&language=en-EN&units=imperial
```

<p>But I am getting an error saying : </p>

```java.net.MalformedURLException: Illegal character in URL
```

Can some one help me out ..

答: java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));have a nice day =).

ContentLicense: CC BY-SA 4.0

Body:
String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+origin+"&destinations="+destination+"&mode=driving&sensor=false&language=en-EN&units=imperial";
url = url.replaceAll(" ", "%20");

Output :

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=150%20Sutter%20St%20San%20Francisco,%20CA,%20United%20States&destinations=1%20Palmer%20Sq%20E
Princeton,%20NJ%2008542&mode=driving&sensor=false&language=en-EN&units=imperial

But I am getting an error saying :

java.net.MalformedURLException: Illegal character in URL

Can some one help me out ..


问:
R Building a function with a condition as variable
I have a data.frame consisting of two columns, time and value. Let's say:

```<code>> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
>6  -0.14219086  0.3387807
>7  -0.05981503  1.3872106
>8   0.37187516  2.0057095
>9   0.42432858  2.6805815
>10  1.19915563  1.9988563
</code>```

I want to build a function which will filter this data, according to the specific condition. Here is my code:

```<code>> select<-function(object,cond)
 {
     subset(object,eval(deparse(substitute(cond))))
 }
</code>```

If I use now my new function as follows:

```<code>>select(s,value<0)
</code>```

I would like to see only rows, where value is < 0. E.g.

```<code>> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
</code>```

However, after running this code, I have an error, that subset must be logical. I tried everything I know about to make the "value<0" visible as expression for R. Does anyone know how to fix it?

```<code>Error in subset.data.frame(object, eval(deparse(substitute(cond)))) :
'subset' must be logical
</code>```

Regards
Michal

答:
Try any of these:

```<code>select <- subset

select <- function(...) subset(...)

select <- function(data, cond) eval.parent(substitute(subset(data, cond)))

select <- function(data, cond) {
  mc <- match.call()
  mc[[1L]] <- quote(subset)
  m <- match(c("data", "cond"), names(mc), 0L)
  names(mc)[m] <- c("x", "subset")
  eval.parent(mc)
}
</code>```

and then using the builtin BOD data.frame

```<code>select(BOD, Time > 3)
</code>```

Body:
I have a data.frame consisting of two columns, time and value. Let's say:

> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
>6  -0.14219086  0.3387807
>7  -0.05981503  1.3872106
>8   0.37187516  2.0057095
>9   0.42432858  2.6805815
>10  1.19915563  1.9988563

I want to build a function which will filter this data, according to the specific condition. Here is my code:

> select<-function(object,cond)
 {
     subset(object,eval(deparse(substitute(cond))))
 }

If I use now my new function as follows:

>select(s,value<0)

I would like to see only rows, where value is < 0. E.g.

> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195

However, after running this code, I have an error, that subset must be logical. I tried everything I know about to make the "value<0" visible as expression for R. Does anyone know how to fix it?

Error in subset.data.frame(object, eval(deparse(substitute(cond)))) :
'subset' must be logical

Regards
Michal

Body:
Try any of these:

select <- subset

select <- function(...) subset(...)

select <- function(data, cond) eval.parent(substitute(subset(data, cond)))

select <- function(data, cond) {
  mc <- match.call()
  mc[[1L]] <- quote(subset)
  m <- match(c("data", "cond"), names(mc), 0L)
  names(mc)[m] <- c("x", "subset")
  eval.parent(mc)
}

and then using the builtin BOD data.frame

select(BOD, Time > 3)


问:
SEO URL # vs. #!

Possible Duplicate:

  What's the shebang (#!) in Facebook and new Twitter URLs for?

Hello!

What is the difference between this URL: mysite.com/images.php#img-1 and this URL: mysite.com/images.php#!img-1, please?

I have a simple photo gallery, nothing fancy, that changes images from a JavaScript array of files and instead of refreshing the page for every image it does it "on the spot" using jQuery.

Thank you.

答: The #! style is used by Google for indexing ajax content.

ContentLicense: CC BY-SA 2.5

Title: SEO URL # vs. #!


问:
401 When passing the token using graphic onenote api
I am new to Microsoft graph so this might be a dumb question.
So I am writing a command line application trying to update a page in our team onenote. (enterprise onenote)
Here is the code I got work getting the token.
https://login.microsoftonline.com/common/oauth2/authorize?client_id=my_client_Id&response_type=code&redirect_uri=Some_uri&resource=https://graph.microsoft.com&scope=Notes.ReadWrite.All

I got the token as strCode and trying to retrieve all the notes under this account by these codes:

```<code>    var baseAddress = new Uri("https://graph.microsoft.com/v1.0/me/onenote");

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        var request = new HttpRequestMessage(HttpMethod.Get, @"/pages");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", strCode);

        using (var response = httpClient.SendAsync(request).Result)
        {
            string responseData = response.Content.ReadAsStringAsync().Result;
        }
    }
</code>```

And in the response data I got
"{   \"error\": {     \"code\": \"InvalidAuthenticationToken\",     \"message\": \"CompactToken parsing failed with error code: -2147184105\",     \"innerError\": {       \"request-id\": \"*********************",       \"date\": \"2017-06-08T18:25:06\"     }   } }"

Any idea how to fix this..?

答:
Problem resolved .
I need to convert the authentication code into a "real" access token..
The one that I got is not an access token. </p>

Body:
I am new to Microsoft graph so this might be a dumb question.
So I am writing a command line application trying to update a page in our team onenote. (enterprise onenote)
Here is the code I got work getting the token.
https://login.microsoftonline.com/common/oauth2/authorize?client_id=my_client_Id&response_type=code&redirect_uri=Some_uri&resource=https://graph.microsoft.com&scope=Notes.ReadWrite.All

I got the token as strCode and trying to retrieve all the notes under this account by these codes:

    var baseAddress = new Uri("https://graph.microsoft.com/v1.0/me/onenote");

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        var request = new HttpRequestMessage(HttpMethod.Get, @"/pages");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", strCode);

        using (var response = httpClient.SendAsync(request).Result)
        {
            string responseData = response.Content.ReadAsStringAsync().Result;
        }
    }

And in the response data I got
"{   \"error\": {     \"code\": \"InvalidAuthenticationToken\",     \"message\": \"CompactToken parsing failed with error code: -2147184105\",     \"innerError\": {       \"request-id\": \"*********************",       \"date\": \"2017-06-08T18:25:06\"     }   } }"

Any idea how to fix this..?


问:
Editable ComboBox binding and update source trigger

Requirement

I want to have ComboBox where user may enter some text or choose text from drop-down list. Binding source should be updated when user press Enter after typing or when item is simply selected from drop-down list (best View behavior in my case).

Problem

when UpdateSourceTrigger=PropertyChange (default) is set, then source update will trigger after every character, which is not good, because property setter call is expensive;

when UpdateSourceTrigger=LostFocus is set, then selecting item from drop-down list will require one more action to actually lose focus, which is not very user-friendly (required additional click after click to select item).

I tried to use UpdateSourceTrigger=Explicit, but it doesn't go well:

```<code><ComboBox IsEditable="True" VerticalAlignment="Top" ItemsSource="{Binding List}"
          Text="{Binding Text, UpdateSourceTrigger=LostFocus}"
          SelectionChanged="ComboBox_SelectionChanged"
          PreviewKeyDown="ComboBox_PreviewKeyDown" LostFocus="ComboBox_LostFocus"/>

public partial class MainWindow : Window
{
    private string _text = "Test";
    public string Text
    {
        get { return _text; }
        set
        {
            if (_text != value)
            {
                _text = value;
                MessageBox.Show(value);
            }
        }
    }

    public string[] List
    {
        get { return new[] { "Test", "AnotherTest" }; }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count > 0)
            ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

    private void ComboBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
            ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

    private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

}
</code>```

This code has 2 issues:

when item is selected from drop-down menu, then source is updated with previously selected value, why?

when user start typing something and then click drop-down button to choose something from the list - source is updated again (due to focus lost?), how to avoid that?

I am a bit afraid to fall under XY problem that's why I posted original requirement (perhaps I went wrong direction?) instead of asking to help me to fix one of above problems.

答:
I had a similar issue, I handled it in the .cs code.  It isn't the XAML way, but it gets it done.  First I broke the binding, then manually propagated the value both ways.</p>

```<code><ComboBox x:Name="Combo_MyValue"
                      ItemsSource="{Binding Source={StaticResource ListData}, XPath=MyContextType/MyValueType}"
                      DisplayMemberPath="@Description"
                      SelectedValuePath="@Value"
                      IsEditable="True"
                      Loaded="Combo_MyValue_Loaded"
                      SelectionChanged = "Combo_MyValue_SelectionChanged"
                      LostFocus="Combo_MyValue_LostFocus"
                      />

    private void Combo_MyValue_Loaded(object sender, RoutedEventArgs e)
    {
        if (DataContext != null)
        {
            Combo_MyValue.SelectedValue = ((MyContextType)DataContext).MyValue;
        }
    }

    private void Combo_MyValue_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if( e.AddedItems.Count == 0)
        {
            // this is a custom value, we'll set it in the lost focus event
            return;
        }
        // this is a picklist value, get the value from itemsource
        XmlElement selectedItem = (XmlElement)e.AddedItems[0];
        string selectedValue = selectedItem.GetAttribute("Value");
        ((PumpParameters)DataContext).MyValue = selectedValue;
    }

    private void Combo_MyValue_LostFocus(object sender, RoutedEventArgs e)
    {
        if( Combo_MyValue.IsDropDownOpen || Combo_MyValue.SelectedIndex != -1)
        {
            // not a custom value
            return;
        }
        // custom value
        ((MyContextType)DataContext).MyValue = Combo_MyValue.Text;
    }
</code>```

Body:
Requirement

I want to have ComboBox where user may enter some text or choose text from drop-down list. Binding source should be updated when user press Enter after typing or when item is simply selected from drop-down list (best View behavior in my case).

Problem

when UpdateSourceTrigger=PropertyChange (default) is set, then source update will trigger after every character, which is not good, because property setter call is expensive;

when UpdateSourceTrigger=LostFocus is set, then selecting item from drop-down list will require one more action to actually lose focus, which is not very user-friendly (required additional click after click to select item).

I tried to use UpdateSourceTrigger=Explicit, but it doesn't go well:

<ComboBox IsEditable="True" VerticalAlignment="Top" ItemsSource="{Binding List}"
          Text="{Binding Text, UpdateSourceTrigger=LostFocus}"
          SelectionChanged="ComboBox_SelectionChanged"
          PreviewKeyDown="ComboBox_PreviewKeyDown" LostFocus="ComboBox_LostFocus"/>

public partial class MainWindow : Window
{
    private string _text = "Test";
    public string Text
    {
        get { return _text; }
        set
        {
            if (_text != value)
            {
                _text = value;
                MessageBox.Show(value);
            }
        }
    }

    public string[] List
    {
        get { return new[] { "Test", "AnotherTest" }; }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count > 0)
            ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

    private void ComboBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
            ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

    private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
    }

}

This code has 2 issues:

when item is selected from drop-down menu, then source is updated with previously selected value, why?

when user start typing something and then click drop-down button to choose something from the list - source is updated again (due to focus lost?), how to avoid that?

I am a bit afraid to fall under XY problem that's why I posted original requirement (perhaps I went wrong direction?) instead of asking to help me to fix one of above problems.

Body:
I had a similar issue, I handled it in the .cs code.  It isn't the XAML way, but it gets it done.  First I broke the binding, then manually propagated the value both ways.

<ComboBox x:Name="Combo_MyValue"
                      ItemsSource="{Binding Source={StaticResource ListData}, XPath=MyContextType/MyValueType}"
                      DisplayMemberPath="@Description"
                      SelectedValuePath="@Value"
                      IsEditable="True"
                      Loaded="Combo_MyValue_Loaded"
                      SelectionChanged = "Combo_MyValue_SelectionChanged"
                      LostFocus="Combo_MyValue_LostFocus"
                      />

    private void Combo_MyValue_Loaded(object sender, RoutedEventArgs e)
    {
        if (DataContext != null)
        {
            Combo_MyValue.SelectedValue = ((MyContextType)DataContext).MyValue;
        }
    }

    private void Combo_MyValue_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if( e.AddedItems.Count == 0)
        {
            // this is a custom value, we'll set it in the lost focus event
            return;
        }
        // this is a picklist value, get the value from itemsource
        XmlElement selectedItem = (XmlElement)e.AddedItems[0];
        string selectedValue = selectedItem.GetAttribute("Value");
        ((PumpParameters)DataContext).MyValue = selectedValue;
    }

    private void Combo_MyValue_LostFocus(object sender, RoutedEventArgs e)
    {
        if( Combo_MyValue.IsDropDownOpen || Combo_MyValue.SelectedIndex != -1)
        {
            // not a custom value
            return;
        }
        // custom value
        ((MyContextType)DataContext).MyValue = Combo_MyValue.Text;
    }


问:
how to use oracle instr function in java
```<code>if instr(lv_my_name, '  ', -2) != length(lv_my_name) - 2 or length(lv_my_name) = 2 then
    lv_my_name:= lv_my_name;
else
    lv_my_name:= trim(substr(lv_my_name, 0, length(lv_my_name)-1));
end if;
</code>```

if I were to write the same logic in Java, how do I do it?

答:
INSTR(string, substring [, position [, occurrence] ] )

The INSTR functions search string for substring. [...] If a substring that is equal to substring is found, then the function returns an integer indicating the position of the first character of this substring. If no such substring is found, then the function returns zero.

position is an nonzero integer indicating the character of string where Oracle Database begins the search—that is, the position of the first character of the first substring to compare with substring. If position is negative, then Oracle counts backward from the end of string and then searches backward from the resulting position.

occurrence is an integer indicating which occurrence of substring in string Oracle should search for. The value of occurrence must be positive. If occurrence is greater than 1, then the database does not return on the first match but continues comparing consecutive substrings of string, as described above, until match number occurrence has been found.

Compare that to:

String.indexOf(String str, int fromIndex)

Returns the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.

String.lastIndexOf(String str, int fromIndex)

Returns the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.

So, since your code doesn't use 4th parameter, and the 3rd parameter is negative, INSTR and lastIndexOf are mostly equivalent

Remember that Java indexes are 0-based, and Oracle positions are 1-based.

Body:
if instr(lv_my_name, '  ', -2) != length(lv_my_name) - 2 or length(lv_my_name) = 2 then
    lv_my_name:= lv_my_name;
else
    lv_my_name:= trim(substr(lv_my_name, 0, length(lv_my_name)-1));
end if;

if I were to write the same logic in Java, how do I do it?


问:
Replace a range of numbers with different range of numbers in SQL
For example replace

```<code>TransactionID
--------
 1
 2
 3
</code>```

with

```<code>TransactionID
--------
 95
 96
 97
</code>```

respectively. Basically, I want to replace numbers with numbers but for multiple items without writing update statement for each item.

Example:

```<code>Update BatchItem
    set TransactionID = '95'
    where BatchItemID = 12345**6**

Update BatchItem
    set TransactionID = '96'
    where BatchItemID = 12345**7**

Update BatchItem
    set TransactionID = '97'
    where BatchItemID = 12345**8**
</code>```

How do I write above statement to update multiple transactionID in sequence?

答:
Try this:

```<code>UPDATE BatchItem SET TransactionId = TransactionId + 94
</code>```

UPDATE

This appears to be the "quick and dirty" version of @Joe's answer.  I'll leave it up in case you find it less confusing than his answer...

Body:
For example replace

TransactionID
--------
 1
 2
 3

with

TransactionID
--------
 95
 96
 97

respectively. Basically, I want to replace numbers with numbers but for multiple items without writing update statement for each item.

Example:

Update BatchItem
    set TransactionID = '95'
    where BatchItemID = 12345**6**

Update BatchItem
    set TransactionID = '96'
    where BatchItemID = 12345**7**

Update BatchItem
    set TransactionID = '97'
    where BatchItemID = 12345**8**

How do I write above statement to update multiple transactionID in sequence?

Body:
Try this:

UPDATE BatchItem SET TransactionId = TransactionId + 94

UPDATE

This appears to be the "quick and dirty" version of @Joe's answer.  I'll leave it up in case you find it less confusing than his answer...


问:
Fulltext search on relational DB with multiple schemas
Warning: Solr newbie here

I have a PostgreSQL database with multiple schemas. Each schema contains several tables. The schemas generally differ in table count and the tables don't have necessarily much in common either.

Regarding the sizing:

In total I'll have dozens up to few hundreds of schemas

Each schema may contain ~10 tables

Each table contains tens of thousands of rows X several hundreds columns

I want to make a full-text search in the data across the DB schemas. As a result I want to be able to identify the schema, table and column matching the search term.

To what I'm thinking about on my own so far are few SOLR options (I would be glad for recommendations on ES solution as well):

1. Create a multi-core where each core represents table within DB schema

This will nicely reuse the DB schema but I'll end up having several thousands of Cores which I believe is misuse.

2. Flattern the index so it covers all possible values

I was thinking about super-generic Solr schema which basically navigates down to individual cell in the table. Something similar to:

```<code><fields>
  <field name="schema" ... />
  <field name="table" ... />
  <field name="column"  ... />
  <field name="row" ... />
  <field name="value"  ... />
</fields>
</code>```

In this case I feel I may be misusing the whole concept a bit as the value would have to be of some generic type (String?) which smells already :)

Also the ID would need to be composed but this I understand should be possible.

Any insight to the problem or recommendation to which part of the documentation to focus on will be much appreciated.

答:
With the response :

@jeorfevre: the idea is I'll search for a word (like "Jerusalem") and the response needs to navigate me to the schema -> table -> column where this term exists. Being able to identify even row is a plus but not strictly required.

I will suggest you to go for a word indexing instead of rows / line full text.

```<code><fields>
  <field name="schema" ... />
  <field name="table" ... />
  <field name="column"  ... />
  <field name="row" ... />
  <field name="myword"  ... />
</fields>
</code>```

This will be a far better approch than the full text search upon X rows in solr. The fulltext is the slowest option in solr. This kind of search is the best option.

You type "Jerusalem", and it will return all the results matching it.
What do you think of that. Better than fulltextsearch, this will hit directly 1 one word only.

Body:
Warning: Solr newbie here

I have a PostgreSQL database with multiple schemas. Each schema contains several tables. The schemas generally differ in table count and the tables don't have necessarily much in common either.

Regarding the sizing:

In total I'll have dozens up to few hundreds of schemas

Each schema may contain ~10 tables

Each table contains tens of thousands of rows X several hundreds columns

I want to make a full-text search in the data across the DB schemas. As a result I want to be able to identify the schema, table and column matching the search term.

To what I'm thinking about on my own so far are few SOLR options (I would be glad for recommendations on ES solution as well):

1. Create a multi-core where each core represents table within DB schema

This will nicely reuse the DB schema but I'll end up having several thousands of Cores which I believe is misuse.

2. Flattern the index so it covers all possible values

I was thinking about super-generic Solr schema which basically navigates down to individual cell in the table. Something similar to:

<fields>
  <field name="schema" ... />
  <field name="table" ... />
  <field name="column"  ... />
  <field name="row" ... />
  <field name="value"  ... />
</fields>

In this case I feel I may be misusing the whole concept a bit as the value would have to be of some generic type (String?) which smells already :)

Also the ID would need to be composed but this I understand should be possible.

Any insight to the problem or recommendation to which part of the documentation to focus on will be much appreciated.

Body:
With the response :

@jeorfevre: the idea is I'll search for a word (like "Jerusalem") and the response needs to navigate me to the schema -> table -> column where this term exists. Being able to identify even row is a plus but not strictly required.

I will suggest you to go for a word indexing instead of rows / line full text.

<fields>
  <field name="schema" ... />
  <field name="table" ... />
  <field name="column"  ... />
  <field name="row" ... />
  <field name="myword"  ... />
</fields>

This will be a far better approch than the full text search upon X rows in solr. The fulltext is the slowest option in solr. This kind of search is the best option.

You type "Jerusalem", and it will return all the results matching it.
What do you think of that. Better than fulltextsearch, this will hit directly 1 one word only.


问:
How to apply style to a paragraph while editing a word document file through c# code using OpenXML?
I tried following code block to apply style to paragraph which is hierarchically correct but its not working in intended way.

```<code>Paragraph paragraph = new Paragraph();
ParagraphProperties paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new ParagraphStyleId() { Val = "Title" });
paragraph.Append(paragraphProperties);
</code>```

So help me out to apply styles to paragraphs programmatically.
And still I am in learning phase, So need good documentation as well.

答:
Recommended documentation for you Open XML - The markup explained by Wouter van Vugt.  It can be found as an attachment to this blog post.

The ebook is a free PDF and is broken up into 4 Chapters:  WordprocessingML, SpreadsheetML, PresentationML and DrawingML.

In the WordprocessingML Chapter, Wouter explains how Styles are added to the document in the section called "Styling the document".  There are 10 pages of explanations and examples to help you during your learning phase to become a master of OpenXML styling.

In your specific case, you will need to make sure the Title style is defined correctly in the Styles part of the document.  And the necessary style relationships are added.  These details are mentioned in the ebook above.

Body:
I tried following code block to apply style to paragraph which is hierarchically correct but its not working in intended way.

Paragraph paragraph = new Paragraph();
ParagraphProperties paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new ParagraphStyleId() { Val = "Title" });
paragraph.Append(paragraphProperties);

So help me out to apply styles to paragraphs programmatically.
And still I am in learning phase, So need good documentation as well.


问:
Fullscreen map with Semantic UI
I'm trying to display a semantic-ui sidebar AND full-screen map.

The deal is I will construct map events to toggle the sidebar(s). My problem is with the CSS.

I'm able to show everything as expected, but I'm having the first item on the menu always shown, pushing a lot of stuff down.

This is the relevant html structure:

```<code><body>
<div class="ui sidebar vertical menu">
    <a class="item">
        Item 1
    </a>
    <a class="item">
        Item 2
    </a>
    <a class="item">
        Item 3
    </a>
</div>

<div class="pusher">
    <div id="map"></div>
</div>

<script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="bower_components/semantic/dist/semantic.min.js"></script>
<script type="text/javascript" src="bower_components/leaflet/dist/leaflet.js"></script>
<script>
    var map = L.map('map').setView([51.505, -0.09], 13);
    $('.ui.sidebar').sidebar('toggle');
</script>
</body>
</code>```

Here are the changes I did to CSS:

```<code>body {
background-color: #FFFFFF;
display: flex;
height: 100vh;
flex-direction: column;
}

#map {
    height: 100vh;
    width: 100%;
}
</code>```

An example of how this is behaving, as the page loads, and after the toggle:

答:
try this

  <button id="btn"> toggle</button>
  <button style="float: right"> toggle</button>

```

Title: Fullscreen map with Semantic UI

Body:
I'm trying to display a semantic-ui sidebar AND full-screen map.

The deal is I will construct map events to toggle the sidebar(s). My problem is with the CSS.

I'm able to show everything as expected, but I'm having the first item on the menu always shown, pushing a lot of stuff down.

This is the relevant html structure:

        Item 1

        Item 2

        Item 3

Here are the changes I did to CSS:

body {
background-color: #FFFFFF;
display: flex;
height: 100vh;
flex-direction: column;
}

#map {
    height: 100vh;
    width: 100%;
}

An example of how this is behaving, as the page loads, and after the toggle:

Body:
try this

<body>

<style>
  .unstyle{
  background: rgba(0,0,0,.0)!important;
}
</style>

<div id="topbar" style="width: 100%; height: 37px;" class="">
  <button id="btn"> toggle</button>
  <button style="float: right"> toggle</button>
</div>
<div id="app" class="" style="height: 94%; width: 100%">
  <div class="ui left vertical menu sidebar unstyle"></div>
  <div class="pusher" style="height: 100%; width: 100%;">
    <div id="mapid"  style="height: 100%; width: 100%; position: relative;"> </div>
  </div>
  <script>
  $('#app .ui.sidebar')
   .sidebar({context: $('#app')})
   .sidebar('setting','transition', 'overlay')
   .sidebar('setting','dimPage', false)
   .sidebar('setting','closable', false)
   .sidebar('attach events', '#btn')
   .sidebar('toggle');
  </script>
</div>

</body>


问:
Minecraft modding Java exception in mod item class
This is my code, I have errors on line 16 and 17, i don't know where im going wrong, this is in the main ModItems class and i have been using this video as a guide If you need the rest of my class files i have uploaded the current copy of my classes here

The error on both lines is The constructor Item(Item, Item) is undefined

```<code> package TheStraying11.QuarkyPower.init;

import TheStraying11.QuarkyPower.Reference;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemSoup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import TheStraying11.QuarkyPower.items.QuarkUp;
import TheStraying11.QuarkyPower.items.QuarkDown;

public class ModItems {

    public static Item QuarkUp;
    public static Item QuarkDown;

    public static void init() {
        QuarkUp = new Item(QuarkUp, QuarkUp);
        QuarkDown = new Item(QuarkDown, QuarkDown);
    }
    public static void register() {
        registerItem(QuarkUp);
        registerItem(QuarkDown);
    }
    public static void registerRenders() {

    }
    public static void registerItem(Item item) {
        GameRegistry.register(item);
    }

    public static void registerRender(Item item) {
        ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(new ResourceLocation(Reference.MODID, item.getUnlocalizedName().substring(5)), "inventory"));

    }
}
</code>```

答:
friend helped, changed

```<code>QuarkUp = new Item(QuarkUp, QuarkUp);
QuarkDown = new Item(QuarkDown, QuarkDown);
</code>```

to

```<code>quark_Up = new itemQuarkUp();
quark_Down = new itemQuarkDown();
</code>```

EDIT:

Completely started again as that video just made a mess imo, that i didn't understand, I guess ill get better soon haha, i just wish i could use Python instead

Body:
This is my code, I have errors on line 16 and 17, i don't know where im going wrong, this is in the main ModItems class and i have been using this video as a guide If you need the rest of my class files i have uploaded the current copy of my classes here

The error on both lines is The constructor Item(Item, Item) is undefined

 package TheStraying11.QuarkyPower.init;

import TheStraying11.QuarkyPower.Reference;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemSoup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import TheStraying11.QuarkyPower.items.QuarkUp;
import TheStraying11.QuarkyPower.items.QuarkDown;

public class ModItems {

    public static Item QuarkUp;
    public static Item QuarkDown;

    public static void init() {
        QuarkUp = new Item(QuarkUp, QuarkUp);
        QuarkDown = new Item(QuarkDown, QuarkDown);
    }
    public static void register() {
        registerItem(QuarkUp);
        registerItem(QuarkDown);
    }
    public static void registerRenders() {

    }
    public static void registerItem(Item item) {
        GameRegistry.register(item);
    }

    public static void registerRender(Item item) {
        ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(new ResourceLocation(Reference.MODID, item.getUnlocalizedName().substring(5)), "inventory"));

    }
}

Body:
friend helped, changed

QuarkUp = new Item(QuarkUp, QuarkUp);
QuarkDown = new Item(QuarkDown, QuarkDown);

to

quark_Up = new itemQuarkUp();
quark_Down = new itemQuarkDown();

EDIT:

Completely started again as that video just made a mess imo, that i didn't understand, I guess ill get better soon haha, i just wish i could use Python instead


问:
how to access string indexer on a collection in Powershell
Slowly learning Powershell ... I'm working on a script to query a third party AD/AM database (ldap). The specific LDAP property name that I want has a hyphen in the name.

I can do this in c# without thinking about it, but I don't want to fire up Visual Studio just to do some simple scripting stuff that changes frequently.

```<code>$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
.....
$results = $objSearcher.FindAll()
foreach($result in $results) {
   $item = $result.Properties
   $item.some-property         # this fails because of '-'
   $result['some-property']    # 'Unable to index into an object of type System.DirectoryServices.SearchResult.'
}
</code>```

答:
You can also specify the property name via a variable:</p>

```<code>$prop = 'some-property'
$result.$prop
</code>```

Body:
Slowly learning Powershell ... I'm working on a script to query a third party AD/AM database (ldap). The specific LDAP property name that I want has a hyphen in the name.

I can do this in c# without thinking about it, but I don't want to fire up Visual Studio just to do some simple scripting stuff that changes frequently.

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
.....
$results = $objSearcher.FindAll()
foreach($result in $results) {
   $item = $result.Properties
   $item.some-property         # this fails because of '-'
   $result['some-property']    # 'Unable to index into an object of type System.DirectoryServices.SearchResult.'
}

Body:
You can also specify the property name via a variable:

$prop = 'some-property'
$result.$prop


问:
summarize weekly average using daily data in R
How to add one column price.wk.average to the data such that price.wk.average is equal to the average price of last week, and also add one column price.mo.average to the data such that it equals to the average price of last month? The price.wk.average will be the same for the entire week. </p>

```<code> Dates    Price   Demand  Price.wk.average   Price.mo.average
 2010-1-1   x        x
 2010-1-2   x        x
 ......
  2015-1-1  x         x
</code>```

答:
jkl,

try to post reproducible examples.  It will make it easier to help you.  you can use dplyr:

```<code>library(dplyr)
df <- data.frame(date = seq(as.Date("2017-1-1"),by="day",length.out = 100), price = round(runif(100)*100+50,0))
df <- df %>%
  group_by(week = week(date)) %>%
  mutate(Price.wk.average = mean(price)) %>%
  ungroup() %>%
  group_by(month = month(date)) %>%
  mutate(Price.mo.average = mean(price))
</code>```

Body:
How to add one column price.wk.average to the data such that price.wk.average is equal to the average price of last week, and also add one column price.mo.average to the data such that it equals to the average price of last month? The price.wk.average will be the same for the entire week.

 Dates    Price   Demand  Price.wk.average   Price.mo.average
 2010-1-1   x        x
 2010-1-2   x        x
 ......
  2015-1-1  x         x

Body:
jkl,

try to post reproducible examples.  It will make it easier to help you.  you can use dplyr:

library(dplyr)
df <- data.frame(date = seq(as.Date("2017-1-1"),by="day",length.out = 100), price = round(runif(100)*100+50,0))
df <- df %>%
  group_by(week = week(date)) %>%
  mutate(Price.wk.average = mean(price)) %>%
  ungroup() %>%
  group_by(month = month(date)) %>%
  mutate(Price.mo.average = mean(price))


问:
Is it good idea to write multi level inline functions in C++?
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

```<code>inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}
</code>```

答:
If both implemented in same scope, than compile can even do some algebraic optimization without inline. Some time ago I was very surprised when see that compiler sometime replace big and complex structures with simple calls of destination functions (kinda arguments carrying for d3d api). So, if you worry about performance, than just don't... at least yours app benchmarks are really bad.

On the other hand, it's all about relations: if func1 not really logically related to func2, only code\math kinda same, than better to copy func2 into func1. Why? Because func2 may be changed, but you forget about func1 and broke it, because they was related not by internal domain logic.

UPD after UPD

If all about speed and their is only math, than wrote in func1 fully optimized expression and don't rely to compiler. But it's if you really know that performance are on first place.

Body:
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}


问:
Local logging vs. using remote service
I have a web app, with node backend. I'm finishing the backend now and I was wondering what should I use for logging. Particularly, whether should I log locally or to some remote location, something like Loggly for example. The reason why I want to go for remote is the ease of use - I can view all logs from the browser, instead of a terminal. I have too much stuff on my mind to implement a web interface myself. I just have one doubt, if each time I log something, I have to send a request to their server, won't this put much more load on my server than local logging? Or is it completely negligible? Also what if network failed? Should I also set up local logging, in case connection fails?</p>

答:
While your question is somewhat at risk of closing as being opinion based, I will answer in hopes that it helps.

At this point, my go-to architecture is based on the 12-factor app (12factor.net).

If you follow those principles, you'll find that logging locations and such should not be a concern of the application itself.  Log to stdout and stderr and then let the application forget about it.

With that done, your environment can then think about what to do with the logs out of band.  In most cases, I'll then have a host based log shipper send logs to an ELK stack or Splunk or Loggly or whatever.  Doesn't matter, the point is that your app doesn't (and shouldn't) care because logging ain't its business.

Title: Local logging vs. using remote service


问:
Getting a request timeout on Heroku with passportJS
I've been struggling with this all night but I haven't found an answer. I created an application which uses Passport JS for authentication. The users are saved in a MongoDB database, works perfectly on my local machine.

For that reason, I attempted to upload the app on Heroku. I added the mlab add-on and imported the data from my local database. When I visit the mlab dashboard the data is there.

The problem is that when I fill the form and hit enter, the app doesn't do anything and the in the console of the web browser the following error appears: "Failed to load resource: the server responded with a status of 503 (Service Unavailable)". I don't know what it's wrong and I need to fix it.

Among all the things I've read I think that a possible error could be that I'm not using things like connect-redis or connect-mongo (don't know which is best) with express-session. This is my code (middlewares):

```<code>app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(session({
    name: 'session',
    secret: '53kre7',
    resave: false,
    saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())
</code>```

So I really hope you can help me because I want to learn how to do it right. Thank you so much

答: My mistake. Heroku named the variable as MONGODB_URI while in my code I had MONGOLAB_URI. So I wasn't pointing to a real database. Problem solved.</p>

Body:
I've been struggling with this all night but I haven't found an answer. I created an application which uses Passport JS for authentication. The users are saved in a MongoDB database, works perfectly on my local machine.

For that reason, I attempted to upload the app on Heroku. I added the mlab add-on and imported the data from my local database. When I visit the mlab dashboard the data is there.

The problem is that when I fill the form and hit enter, the app doesn't do anything and the in the console of the web browser the following error appears: "Failed to load resource: the server responded with a status of 503 (Service Unavailable)". I don't know what it's wrong and I need to fix it.

Among all the things I've read I think that a possible error could be that I'm not using things like connect-redis or connect-mongo (don't know which is best) with express-session. This is my code (middlewares):

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(session({
    name: 'session',
    secret: '53kre7',
    resave: false,
    saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())

So I really hope you can help me because I want to learn how to do it right. Thank you so much


问:
Perform insertion of data into multiple tables using JDBC in one function
I need to perfom data base insertion in my spring boot webapp. What I have so far is a list of sport competitions and there respective informations.

one competition can hold at different time the same day.
Fist thing annoying me is how do I store this times is DB. Does a new table needed here ? (I created a date table)

I searched around and I still don't figure out how to combine the insertion of
competition info and its dates in my insert function at same time.

My insert function need some works, I need somme help.

this answer  is good, but it's did not fill my requirements

My data base schema:

```<code>CREATE TABLE competition (
  competition_id integer PRIMARY KEY,
  nom varchar(128) NOT NULL,
);

CREATE TABLE date (
  id integer PRIMARY KEY,
  date_time timestamptz,
  competition_id integer REFERENCES competition (competition_id)
);
</code>```

Json data:

```<code>{
    "id": "420",
    "name": "SOCCER",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
        "2016-05-12T05:00:00.000Z"
    ]
},
{
    "id": "220",
    "name": "BASKETBALL",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
    ]
}
</code>```

My competition Class:

```<code>public class Competition{
    private int id;
    private String name;
    private String[] dates;
    // setters ... getters
}
</code>```

Function to insert data :

```<code>private static final String INSERT_STMT =
      " insert into competition (id, name)"
    + " values (?, ?)"
    ;

public int insert(Competition competition) {
    return jdbcTemplate.update(conn -> {
      PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
      ps.setInt(1, competition.getId());
      ps.setString(2, competition.getName());
      return ps;
    });

    // insert also in date table ???
  }
</code>```

答: At first if you need data consistency then you should wrap your insert statements with transaction. For insert data into multiple tables you should execute multiple insert statements, the same as you doing with sql. If you need return updated rows count you can create wrapper class where you can store it and return it.</p>

Body:
I need to perfom data base insertion in my spring boot webapp. What I have so far is a list of sport competitions and there respective informations.

one competition can hold at different time the same day.
Fist thing annoying me is how do I store this times is DB. Does a new table needed here ? (I created a date table)

I searched around and I still don't figure out how to combine the insertion of
competition info and its dates in my insert function at same time.

My insert function need some works, I need somme help.

this answer  is good, but it's did not fill my requirements

My data base schema:

CREATE TABLE competition (
  competition_id integer PRIMARY KEY,
  nom varchar(128) NOT NULL,
);

CREATE TABLE date (
  id integer PRIMARY KEY,
  date_time timestamptz,
  competition_id integer REFERENCES competition (competition_id)
);

Json data:

{
    "id": "420",
    "name": "SOCCER",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
        "2016-05-12T05:00:00.000Z"
    ]
},
{
    "id": "220",
    "name": "BASKETBALL",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
    ]
}

My competition Class:

public class Competition{
    private int id;
    private String name;
    private String[] dates;
    // setters ... getters
}

Function to insert data :

private static final String INSERT_STMT =
      " insert into competition (id, name)"
    + " values (?, ?)"
    ;

public int insert(Competition competition) {
    return jdbcTemplate.update(conn -> {
      PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
      ps.setInt(1, competition.getId());
      ps.setString(2, competition.getName());
      return ps;
    });

    // insert also in date table ???
  }


问:
Unable to activate virtualenv via bash script
I'm running a project inside a virtualenv in python. Here's the path to the virtualenv.

```<code>~/iss/issp/bin
</code>```

The problem is when I try to run the activate script with:

```<code>source activate
</code>```

it throws the following error.

```<code>:~/iss/issp/bin$ source activate
: command not found
bash: activate: line 4: syntax error near unexpected token `$'{\r''
'ash: activate: line 4: `deactivate () {
</code>```

Here's the code inside the script:

```<code># This file must be used with "source bin/activate" *from bash*
# you cannot run it directly

deactivate () {
    unset pydoc

    # reset old environment variables
    if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
        PATH="$_OLD_VIRTUAL_PATH"
        export PATH
        unset _OLD_VIRTUAL_PATH
    fi
    if [ -n "$_OLD_VIRTUAL_PYTHONHOME" ] ; then
        PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
        export PYTHONHOME
        unset _OLD_VIRTUAL_PYTHONHOME
    fi

    # This should detect bash and zsh, which have a hash command that must
    # be called to get it to forget past commands.  Without forgetting
    # past commands the $PATH changes we made may not be respected
    if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
        hash -r 2>/dev/null
    fi

    if [ -n "$_OLD_VIRTUAL_PS1" ] ; then
        PS1="$_OLD_VIRTUAL_PS1"
        export PS1
        unset _OLD_VIRTUAL_PS1
    fi

    unset VIRTUAL_ENV
    if [ ! "$1" = "nondestructive" ] ; then
    # Self destruct!
        unset -f deactivate
    fi
}

# unset irrelevant variables
deactivate nondestructive

VIRTUAL_ENV="/home/pablo/issp"
export VIRTUAL_ENV

_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH

# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "$PYTHONHOME" ] ; then
    _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
    unset PYTHONHOME
fi

if [ -z "$VIRTUAL_ENV_DISABLE_PROMPT" ] ; then
    _OLD_VIRTUAL_PS1="$PS1"
    if [ "x" != x ] ; then
        PS1="$PS1"
    else
    if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
        # special case for Aspen magic directories
        # see http://www.zetadev.com/software/aspen/
        PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
    fi
    fi
    export PS1
fi

alias pydoc="python -m pydoc"

# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.  Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
    hash -r 2>/dev/null
fi
</code>```

答: Just had the same problem, and decided to do hexdump -C bin/activate to figure out. Turns out my bin/activate file had CR/LF line endings instead of just CR, changing them with (tr -d '\r' < bin/activate) > bin/activatefixed my problem.

Body:
I'm running a project inside a virtualenv in python. Here's the path to the virtualenv.

~/iss/issp/bin

The problem is when I try to run the activate script with:

source activate

it throws the following error.

:~/iss/issp/bin$ source activate
: command not found
bash: activate: line 4: syntax error near unexpected token `$'{\r''
'ash: activate: line 4: `deactivate () {

Here's the code inside the script:

# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly

deactivate () {
    unset pydoc

    # reset old environment variables
    if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
        PATH="$_OLD_VIRTUAL_PATH"
        export PATH
        unset _OLD_VIRTUAL_PATH
    fi
    if [ -n "$_OLD_VIRTUAL_PYTHONHOME" ] ; then
        PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
        export PYTHONHOME
        unset _OLD_VIRTUAL_PYTHONHOME
    fi

    # This should detect bash and zsh, which have a hash command that must
    # be called to get it to forget past commands.  Without forgetting
    # past commands the $PATH changes we made may not be respected
    if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
        hash -r 2>/dev/null
    fi

    if [ -n "$_OLD_VIRTUAL_PS1" ] ; then
        PS1="$_OLD_VIRTUAL_PS1"
        export PS1
        unset _OLD_VIRTUAL_PS1
    fi

    unset VIRTUAL_ENV
    if [ ! "$1" = "nondestructive" ] ; then
    # Self destruct!
        unset -f deactivate
    fi
}

# unset irrelevant variables
deactivate nondestructive

VIRTUAL_ENV="/home/pablo/issp"
export VIRTUAL_ENV

_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH

# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "$PYTHONHOME" ] ; then
    _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
    unset PYTHONHOME
fi

if [ -z "$VIRTUAL_ENV_DISABLE_PROMPT" ] ; then
    _OLD_VIRTUAL_PS1="$PS1"
    if [ "x" != x ] ; then
        PS1="$PS1"
    else
    if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
        # special case for Aspen magic directories
        # see http://www.zetadev.com/software/aspen/
        PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
    fi
    fi
    export PS1
fi

alias pydoc="python -m pydoc"

# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.  Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
    hash -r 2>/dev/null
fi


答:
First I would make the ID in the Date-Table Auto-Increment, so you don't have to give an ID for every date and go with this Base-Query:

```<code>private static final String INSERT_DATES = "INSERT INTO date (date_time, competition_id) VALUES ";
</code>```

And then build the Statement like this:

```<code>public int insert(Competition competition) {
    // All local variables must be final because the lambdas will be executed at a undefined time
    final int id = competition.getId();
    final String name = competition.getName();

    final String[] dates = competition.getDates();
    final String dateValueStr = String.join(", ", Collections.nCopies(dates.length, "(?, ?)"));

    // Execute Updates
    int updatedRows1 = jdbcTemplate.update(conn -> {
        PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
        ps.setInt(1, id);
        ps.setString(2, name);
        return ps;
    });

    if (updatedRows1 < 1)
    {
        // Something went wrong
        return -1;
    }

    int updatedRows2 = jdbcTemplate.update(conn -> {
        PreparedStatement ps = conn.prepareStatement(INSERT_DATES + dateValueStr);

        int idx = 1;
        for (String date : dates)
        {
            ps.setString(idx, date); // date_time
            idx++;
            ps.setInt(idx, competitionID); // competition_id
            idx++;
        }

        return ps;
    });

    if (updatedRows2 < 1)
    {
        // Something went wrong
        // Rollback the first insert, idk how its made
        return -1;
    }

    return updatedRows1 + updatedRows2;
}
</code>```

Title: Perform insertion of data into multiple tables using JDBC in one function

Body:
First I would make the ID in the Date-Table Auto-Increment, so you don't have to give an ID for every date and go with this Base-Query:

private static final String INSERT_DATES = "INSERT INTO date (date_time, competition_id) VALUES ";

And then build the Statement like this:

public int insert(Competition competition) {
    // All local variables must be final because the lambdas will be executed at a undefined time
    final int id = competition.getId();
    final String name = competition.getName();

    final String[] dates = competition.getDates();
    final String dateValueStr = String.join(", ", Collections.nCopies(dates.length, "(?, ?)"));

    // Execute Updates
    int updatedRows1 = jdbcTemplate.update(conn -> {
        PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
        ps.setInt(1, id);
        ps.setString(2, name);
        return ps;
    });

    if (updatedRows1 < 1)
    {
        // Something went wrong
        return -1;
    }

    int updatedRows2 = jdbcTemplate.update(conn -> {
        PreparedStatement ps = conn.prepareStatement(INSERT_DATES + dateValueStr);

        int idx = 1;
        for (String date : dates)
        {
            ps.setString(idx, date); // date_time
            idx++;
            ps.setInt(idx, competitionID); // competition_id
            idx++;
        }

        return ps;
    });

    if (updatedRows2 < 1)
    {
        // Something went wrong
        // Rollback the first insert, idk how its made
        return -1;
    }

    return updatedRows1 + updatedRows2;
}


问:
kAudioDevicePropertyBufferFrameSizeRange returns { 0, 0}
I'm trying to use CoreAudio to get the expected buffer sizes on hardware for MacOS. My current strategy for this is based on this technical note.

The code is implemented as follows:

```<code>        AudioObjectID DeviceAudioObjectID;
        AudioObjectPropertyAddress DevicePropertyAddress;
        UInt32 AudioDeviceQuerySize;
        OSStatus Status;
        int32 BufferSize = 0;

        //Get Audio Device ID
        DevicePropertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
        DevicePropertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        DevicePropertyAddress.mElement = 0;
        AudioDeviceQuerySize = sizeof(AudioDeviceID);
        Status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &DevicePropertyAddress, 0, nullptr, &AudioDeviceQuerySize, &DeviceAudioObjectID);

        DevicePropertyAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
        DevicePropertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        DevicePropertyAddress.mElement = kAudioObjectPropertyElementMaster;
        AudioValueRange BufferSizeRange = { 0, 0 };
        AudioDeviceQuerySize = sizeof(AudioValueRange);
        Status = AudioObjectGetPropertyData(DeviceAudioObjectID, &DevicePropertyAddress, 0, nullptr, &AudioDeviceQuerySize, &BufferSizeRange);
</code>```

On my current Mac (a Mac Pro running Sierra), The final call to AudioObjectGetPropertyData here results in BufferSizeRange being explicitly set to { 0, 0 }. The call returns with 0, indicating success.

How do I properly query the range of possible buffer sizes supported by the hardware?

答:
I don't understand where's your problem. I've tried your code on my MacBook with OS X Sierra and it worked well. When I've checked the result stored in BufferSizeRange I got mMinimum = 14 and mMaximum = 4096.

I've just changed the wrong initialization of BufferSize (you wrote int32 that doesn't exist as variable), I've substitute nullptr with NULL and set DevicePropertyAddress.mElement = kAudioObjectPropertyElementMaster when you're asking for knowing who's the default output device.

However I recommend you to ask directly to CoreAudio the size of the property you want to know with AudioObjectGetPropertyDataSize and to check with an if statement functions's return value.

Body:
I'm trying to use CoreAudio to get the expected buffer sizes on hardware for MacOS. My current strategy for this is based on this technical note.

The code is implemented as follows:

        AudioObjectID DeviceAudioObjectID;
        AudioObjectPropertyAddress DevicePropertyAddress;
        UInt32 AudioDeviceQuerySize;
        OSStatus Status;
        int32 BufferSize = 0;

        //Get Audio Device ID
        DevicePropertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
        DevicePropertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        DevicePropertyAddress.mElement = 0;
        AudioDeviceQuerySize = sizeof(AudioDeviceID);
        Status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &DevicePropertyAddress, 0, nullptr, &AudioDeviceQuerySize, &DeviceAudioObjectID);

        DevicePropertyAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
        DevicePropertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        DevicePropertyAddress.mElement = kAudioObjectPropertyElementMaster;
        AudioValueRange BufferSizeRange = { 0, 0 };
        AudioDeviceQuerySize = sizeof(AudioValueRange);
        Status = AudioObjectGetPropertyData(DeviceAudioObjectID, &DevicePropertyAddress, 0, nullptr, &AudioDeviceQuerySize, &BufferSizeRange);

On my current Mac (a Mac Pro running Sierra), The final call to AudioObjectGetPropertyData here results in BufferSizeRange being explicitly set to { 0, 0 }. The call returns with 0, indicating success.

How do I properly query the range of possible buffer sizes supported by the hardware?


问:
How to map different HTTP methods on the same url to different controllers?
I have my API for a small part of my application split over two controllers, because of (external) requirements on the casing of JSON data in the API (some requests should use camelCasing, while others should use PascalCasing).

Now, I have a url that I want to map with PascalCasing for GET, but camelCasing for PUT, so I tried the following:

[PascalCasing] // custom attribute, part of our code
               // We configure all controllers that *don't* have this to use
               // camelCasing
public class PascalCasedController : ApiController
{
    [HttpGet]
    [Route("url/to/my/resource/{id}")]
    public IHttpActionResult(int id)
    {
        return Ok(GetResource(id));
    }
}

public class CamelCasedController : ApiController
{
    [HttpPut]
    [Route("url/to/my/resource/{id}")]
    public IHttpActionResult(int id, Resource resource)
    {
        SaveResource(id, resource);
        return Ok();
    }
}
```

The GET request works as expected, but if I try to PUT something there with Fiddler, I get the following error message:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

  The request has found the following matching controller types:

   MyProject.PascalCaseController

   MyProject.CamelCaseController

I realize this is probably because WebAPI maps routes to controllers first and actions next, but if HTTP methods are considered, there really isn't any ambiguity here. Is there any way that I can tell WebAPI how to do this, without having to have the methods in the same controller?

答:
@Tomas - There's an interface "System.Web.Http.Dispatcher.IHttpControllerSelector" exposed in System.Web.Http assembly. You can use that interface and create your own HttpControllerSelector. You can then replace the DefaultControllerSelector with your custom controller selector in the HttpConfiguration during AreaRegistration.

httpConfig.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(services.GetHttpControllerSelector()));

In this custom controller selector you can write your own implementation of SelectController() method of IHttpControllerSelector in which you can call GetControllerMapping() method of IHttpControllerSelector. This will give you the list of all the controllers registered. For every controller you can check for the DeclaredMethods and check for the CustomAttributes for each of the DeclaredMethods. In your case it will be either HttpGetAttribute or HttpPutAttribute.

Check the Method type of the incoming HttpRequestMessage (GET/PUT) and compare it against the value of the CustomAttributes. If you find a match of the combination of incoming request URL and the the respective Http Verb then you take that HttpControllerDiscriptor and return it from the SelectController() method..

This will allow you to have same URL with different methods in two different controllers.

Body:
I have my API for a small part of my application split over two controllers, because of (external) requirements on the casing of JSON data in the API (some requests should use camelCasing, while others should use PascalCasing).

Now, I have a url that I want to map with PascalCasing for GET, but camelCasing for PUT, so I tried the following:

[PascalCasing] // custom attribute, part of our code
               // We configure all controllers that *don't* have this to use
               // camelCasing
public class PascalCasedController : ApiController
{
    [HttpGet]
    [Route("url/to/my/resource/{id}")]
    public IHttpActionResult(int id)
    {
        return Ok(GetResource(id));
    }
}

public class CamelCasedController : ApiController
{
    [HttpPut]
    [Route("url/to/my/resource/{id}")]
    public IHttpActionResult(int id, Resource resource)
    {
        SaveResource(id, resource);
        return Ok();
    }
}

The GET request works as expected, but if I try to PUT something there with Fiddler, I get the following error message:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

  The request has found the following matching controller types:

   MyProject.PascalCaseController

   MyProject.CamelCaseController

I realize this is probably because WebAPI maps routes to controllers first and actions next, but if HTTP methods are considered, there really isn't any ambiguity here. Is there any way that I can tell WebAPI how to do this, without having to have the methods in the same controller?