问:
Am I understanding the function and its purpose correctly? Also, Syntax Error?
I am having trouble understanding why i keep getting a syntax error for this function. It returns an int such that n_times (f,n,v) applies f to v n times. For example, n_times((fun x-> x+1), 50, 0) = 50. If n<=0 return v.

```<code>let rec n_times (f, n, v) =
  (* YOUR CODE HERE *)
   raise (Failure "Not implemented")
assert (n_times((fun x-> x+1), 50, 0) = 50)
</code>```

Here is what I coded:

```<code>let rec n_times (f, n, v) =
  (* YOUR CODE HERE *)
  |n<=0 -> f v
  |n>0 -> f v * n_times(f, n, v)

  let f() = (Failure "Not implemented2")

let f() = assert (n_times((fun x-> x+1), 50, 0) = 50)
</code>```

I believe for this function v is multiplied n times. Am I understanding this right? Also I don't understand why the first line of my code gives me a syntax error?

答:
You appear to be writing a match expression, but you just have the last part (with different alternatives), and not the first part (which says match ... with). So the | token isn't allowed at the point where it shows up in your code.

As a second comment, the match statement takes patterns, and n <= 0 is not a pattern. It's a boolean expression.

So, more likely you just want to use an if statement.

Body:
I am having trouble understanding why i keep getting a syntax error for this function. It returns an int such that n_times (f,n,v) applies f to v n times. For example, n_times((fun x-> x+1), 50, 0) = 50. If n<=0 return v.

let rec n_times (f, n, v) =
  (* YOUR CODE HERE *)
   raise (Failure "Not implemented")
assert (n_times((fun x-> x+1), 50, 0) = 50)

Here is what I coded:

let rec n_times (f, n, v) =
  (* YOUR CODE HERE *)
  |n<=0 -> f v
  |n>0 -> f v * n_times(f, n, v)

  let f() = (Failure "Not implemented2")

let f() = assert (n_times((fun x-> x+1), 50, 0) = 50)

I believe for this function v is multiplied n times. Am I understanding this right? Also I don't understand why the first line of my code gives me a syntax error?


来源: stackexchange

问:
Linq query update all items in groups that meet my condition
I want to update the property "IsQualified= True" for-

All students in only qualified groups

Qualified groups? Those groups that have at least one student who passed from "University= OPQ" (Example: Group 2 and 3)

Leave other group students' "IsQualified" property unchanged. (Example: Group 1)

What I tried-

```<code>var results = studentsList
.Where(x => x.University= OPQ)
.GroupBy(x => x.GroupID)
.SelectMany(g => g)
.ToList();

results.ForEach(x => x.IsQualified = true);
</code>```

This doesn't work. Please help me.

My Code-

```<code>public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}

}

List<StudentInfo> studentsList = new List<StudentInfo>();

StudentsList.Add( new StudentInfo { Student="John", University="ABC", GroupID = 1, IsQualified=False});
StudentsList.Add( new StudentInfo { Student="Jack", University="DEF", GroupID = 1, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Peter", University="GHI", GroupID = 1, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Donald", University="JKL", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ABC", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emma", University="GHI", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Alan", University="DEF", GroupID = 2, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Adam", University="GHI", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="ABC", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Saint", University="VWX", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="TRP", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="STU", GroupID = 3, IsQualified=False} );
</code>```

答:
Your filtering is wrong.

You need to group first, then filter second. Otherwise you are grouping by a very select list.

```<code>var results = studentsList
             .GroupBy(x => x.GroupID)
             .Where(x => x.Any(y => y.University == "OPQ"))
             .SelectMany(g => g)
             .ToList();

results.ForEach(x => x.IsQualified = true);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to update the property "IsQualified= True" for-

All students in only qualified groups

Qualified groups? Those groups that have at least one student who passed from "University= OPQ" (Example: Group 2 and 3)

Leave other group students' "IsQualified" property unchanged. (Example: Group 1)

What I tried-

var results = studentsList
.Where(x => x.University= OPQ)
.GroupBy(x => x.GroupID)
.SelectMany(g => g)
.ToList();

results.ForEach(x => x.IsQualified = true);

This doesn't work. Please help me.

My Code-

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}

}

List<StudentInfo> studentsList = new List<StudentInfo>();

StudentsList.Add( new StudentInfo { Student="John", University="ABC", GroupID = 1, IsQualified=False});
StudentsList.Add( new StudentInfo { Student="Jack", University="DEF", GroupID = 1, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Peter", University="GHI", GroupID = 1, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Donald", University="JKL", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ABC", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emma", University="GHI", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Alan", University="DEF", GroupID = 2, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Adam", University="GHI", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="ABC", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Saint", University="VWX", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="TRP", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="STU", GroupID = 3, IsQualified=False} );

Body:
Your filtering is wrong.

You need to group first, then filter second. Otherwise you are grouping by a very select list.

var results = studentsList
             .GroupBy(x => x.GroupID)
             .Where(x => x.Any(y => y.University == "OPQ"))
             .SelectMany(g => g)
             .ToList();

results.ForEach(x => x.IsQualified = true);


问:
Is there a way to use Marshaller in Grails to parse JSON string into a custom object
I am trying to parse a JSON String to my custom object
I already have a Marshaller class to go from the object to JSON
and was wondering if it possible to use it for parsing in other direction as well instead of using JsonSlurper
didn't see any clear documentation on that or any other JSON to object mapping api that is not includes writing code using  JsonSlurper to manually create objects</p>

答:
groovy supports simple mapping like this:

```<code>import groovy.json.JsonSlurper
import groovy.json.JsonOutput

class A{
    int id
    String name
}

Map m = new JsonSlurper().parseText('{"id":123,"name":"Joe"}')
A a = m as A
assert a.id==123
assert a.name=="Joe"

def json = JsonOutput.toJson(a)
assert json == '{"id":123,"name":"Joe"}'
</code>```

for marshalling/unmarshalling approach I prefer to use Gson library:

```<code>@Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson

class A{
    int id
    String name
}

A a=new Gson().fromJson('{"id":123,"name":"Joe"}', A.class)
assert a.id==123
assert a.name=="Joe"

def json = new Gson().toJson(a)
assert json == '{"id":123,"name":"Joe"}'
</code>```

Body:
groovy supports simple mapping like this:

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

class A{
    int id
    String name
}

Map m = new JsonSlurper().parseText('{"id":123,"name":"Joe"}')
A a = m as A
assert a.id==123
assert a.name=="Joe"

def json = JsonOutput.toJson(a)
assert json == '{"id":123,"name":"Joe"}'

for marshalling/unmarshalling approach I prefer to use Gson library:

@Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson

class A{
    int id
    String name
}

A a=new Gson().fromJson('{"id":123,"name":"Joe"}', A.class)
assert a.id==123
assert a.name=="Joe"

def json = new Gson().toJson(a)
assert json == '{"id":123,"name":"Joe"}'


问:
How to sort dictionary by key in numerical order Python
Here is the dictionary looks like:

```<code>{'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
</code>```

I would like to sort the dictionary in numerical order, the result should be:

```<code>{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}
</code>```

I tried sorted(self.docs_info.items) but it doesn't work.

答:
In Python 3 sorted() has an optional parameter key. And in 3.6+ dict maintains insertion order.

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

Therefore, what OP wants can be accomplished this way.

```<code>>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> for key, value in sorted(d.items(), key=lambda item: int(item[0])):
...     print(key, value)
57480 89
57481 50
57482 18
57483 110
57484 40
57485 82
</code>```

Or if OP wants to create a new sorted dictionary.

```<code>>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> d_sorted = {key:value for key, value in sorted(d.items(), key=lambda item: int(item[0]))}
>>> d_sorted
{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}
</code>```

d.items() returns a list of tuples, e.g. ('57480': 89) and so on. The lambda functions takes this tuple and applies int function to the first value. And then the result is used for comparison.

ContentLicense: CC BY-SA 3.0

Body:
Here is the dictionary looks like:

{'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}

I would like to sort the dictionary in numerical order, the result should be:

{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}

I tried sorted(self.docs_info.items) but it doesn't work.

Body:
In Python 3 sorted() has an optional parameter key. And in 3.6+ dict maintains insertion order.

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

Therefore, what OP wants can be accomplished this way.

>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> for key, value in sorted(d.items(), key=lambda item: int(item[0])):
...     print(key, value)
57480 89
57481 50
57482 18
57483 110
57484 40
57485 82

Or if OP wants to create a new sorted dictionary.

>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> d_sorted = {key:value for key, value in sorted(d.items(), key=lambda item: int(item[0]))}
>>> d_sorted
{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}

d.items() returns a list of tuples, e.g. ('57480': 89) and so on. The lambda functions takes this tuple and applies int function to the first value. And then the result is used for comparison.


问:
How to put string variables into a Python array?
I'm rather new at this (it's my first question ha!), and my english isn't as good and technical as yours so I apologize in advance. That being said, I'm trying to fit string variables to an array but I can't get it done. Here are the variables:

```<code>basket1 = {'vanilla wafers', 'bananas' , 'dog food'}
basket2 = {'bananas', 'bread', 'yogurt'}
basket3 = {'bananas','apples','yogurt'}
basket4 = {'vanilla wafers','bananas','whipped cream'}
basket5 = {'bread', 'vanilla wafers' , 'yogurt'}
basket6 = {'milk', 'bread', 'bananas'}
basket7 = {'vanilla wafers', 'apples' , 'bananas'}
basket8 = {'yogurt', 'apples', 'vanilla wafers'}
basket9 = {'vanilla wafers', 'bananas' , 'milk'}
basket10 =  {'bananas', 'bread', 'peanut butter'}
</code>```

Any ideas? Should I use a list instead? It must have a 10x3 shape though.

答:
Replace the brackets with parentheses, so like this

```<code>basket1 = ['bread', 'cake', 'soap']
</code>```

For multi-dimensional arrays, write

```<code>baskets = [['bread', 'cake', 'soap'], ['carrot', 'milk', 'wheat']]
</code>```

Body:
I'm rather new at this (it's my first question ha!), and my english isn't as good and technical as yours so I apologize in advance. That being said, I'm trying to fit string variables to an array but I can't get it done. Here are the variables:

basket1 = {'vanilla wafers', 'bananas' , 'dog food'}
basket2 = {'bananas', 'bread', 'yogurt'}
basket3 = {'bananas','apples','yogurt'}
basket4 = {'vanilla wafers','bananas','whipped cream'}
basket5 = {'bread', 'vanilla wafers' , 'yogurt'}
basket6 = {'milk', 'bread', 'bananas'}
basket7 = {'vanilla wafers', 'apples' , 'bananas'}
basket8 = {'yogurt', 'apples', 'vanilla wafers'}
basket9 = {'vanilla wafers', 'bananas' , 'milk'}
basket10 =  {'bananas', 'bread', 'peanut butter'}

Any ideas? Should I use a list instead? It must have a 10x3 shape though.

Body:
Replace the brackets with parentheses, so like this

basket1 = ['bread', 'cake', 'soap']

For multi-dimensional arrays, write

baskets = [['bread', 'cake', 'soap'], ['carrot', 'milk', 'wheat']]


问:
erlang: receive response from ssl
I added a new module (-behavior(gen_mod)) inside ejabberd and I was able to open a ssl connection to a server and send a message directly using the ssl connection(ssl:send() function). However, I am unable to receive response after this.

I tried using the receive option in erlang to catch messages, and still no luck.

I tried changing the module to be a stateful module by using the gen_server behavior and I still don't observe any handle_info calls with any message.

I could not get any response using ssl:recv/2 either.

Am I missing something? How do I asynchronously receive the response from the ssl socket in erlang?

Any pointers would be really appreciated. Thank you!

code: Adding only relevant parts of the code.

```<code>sendPacketToServer() ->
 case ssl:connect(Gateway, Port, Options, ?SSL_TIMEOUT) of
        {ok, Socket} ->
            ssl:controlling_process(Socket, self()),
            Packet = .....,
            Result = ssl:send(Socket, Packet),
            receiveMessage(),
            ssl:close(Socket),
            ?INFO_MSG("~n~n~n~n Successfully sent payload to the server, result: ~p for the user: ~p", [Result, Username]);
        {error, Reason} = Err ->
            ?ERROR_MSG("Unable to connect to the server: ~s for the user: ~p", [ssl:format_error(Reason), Username]),
            Err
 end
...
....
receiveMessage() ->
  receive ->
      {ssl, Msg, Data} ->  % incoming msg from SSL, send it to process
      ......
    {ssl_closed, Msg} ->  % incoming msg from SSL, send it to process
      .....
    {ssl_error, Msg} ->  % incoming msg from SSL, send it to process
      .....
    {ssl_passive, Msg} ->  % incoming msg from SSL, send it to process
      ....
  end.
</code>```

Added the following code for gen_server: (when doing the following, i do not close the socket immediately, but it still does not work).

```<code>start(Host, Opts) ->
        gen_mod:start_child(?MODULE, Host, Opts).
stop(Host) ->
        gen_mod:stop_child(?MODULE, Host).
init([ServerHost|_]) ->
    Opts = gen_mod:get_module_opts(ServerHost, ?MODULE),
    start(ServerHost, Opts),
    {ok, #state{host = ServerHost}}.

handle_call(Request, From, State) ->
    ?WARNING_MSG("Unexpected call from ~p: ~p", [From, Request]),
    {noreply, State}.
handle_cast(Msg, State) ->
    ?WARNING_MSG("Unexpected cast: ~p", [Msg]),
    {noreply, State}.
handle_info(Info, State) ->
    ?WARNING_MSG("Unexpected info: ~p", [Info]),
    {noreply, State}.
terminate(_Reason, State) ->
    ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
</code>```

答: I was able to overcome the problem by using a gen_server module, since it has explicit callbacks for any messages.</p>

Title: erlang: receive response from ssl

Body:
I added a new module (-behavior(gen_mod)) inside ejabberd and I was able to open a ssl connection to a server and send a message directly using the ssl connection(ssl:send() function). However, I am unable to receive response after this.

I tried using the receive option in erlang to catch messages, and still no luck.

I tried changing the module to be a stateful module by using the gen_server behavior and I still don't observe any handle_info calls with any message.

I could not get any response using ssl:recv/2 either.

Am I missing something? How do I asynchronously receive the response from the ssl socket in erlang?

Any pointers would be really appreciated. Thank you!

code: Adding only relevant parts of the code.

sendPacketToServer() ->
 case ssl:connect(Gateway, Port, Options, ?SSL_TIMEOUT) of
        {ok, Socket} ->
            ssl:controlling_process(Socket, self()),
            Packet = .....,
            Result = ssl:send(Socket, Packet),
            receiveMessage(),
            ssl:close(Socket),
            ?INFO_MSG("~n~n~n~n Successfully sent payload to the server, result: ~p for the user: ~p", [Result, Username]);
        {error, Reason} = Err ->
            ?ERROR_MSG("Unable to connect to the server: ~s for the user: ~p", [ssl:format_error(Reason), Username]),
            Err
 end
...
....
receiveMessage() ->
  receive ->
      {ssl, Msg, Data} ->  % incoming msg from SSL, send it to process
      ......
    {ssl_closed, Msg} ->  % incoming msg from SSL, send it to process
      .....
    {ssl_error, Msg} ->  % incoming msg from SSL, send it to process
      .....
    {ssl_passive, Msg} ->  % incoming msg from SSL, send it to process
      ....
  end.

Added the following code for gen_server: (when doing the following, i do not close the socket immediately, but it still does not work).

start(Host, Opts) ->
        gen_mod:start_child(?MODULE, Host, Opts).
stop(Host) ->
        gen_mod:stop_child(?MODULE, Host).
init([ServerHost|_]) ->
    Opts = gen_mod:get_module_opts(ServerHost, ?MODULE),
    start(ServerHost, Opts),
    {ok, #state{host = ServerHost}}.

handle_call(Request, From, State) ->
    ?WARNING_MSG("Unexpected call from ~p: ~p", [From, Request]),
    {noreply, State}.
handle_cast(Msg, State) ->
    ?WARNING_MSG("Unexpected cast: ~p", [Msg]),
    {noreply, State}.
handle_info(Info, State) ->
    ?WARNING_MSG("Unexpected info: ~p", [Info]),
    {noreply, State}.
terminate(_Reason, State) ->
    ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.


问:
How to prompt the program to continue reading other csv files in csv folder even when one of the csv file is not found?
Cells(i,41) represents the csv file locations that i suppose the csv folder has it which i have stored them in my spreadsheet. However, some of my csv files are not in my csv folder but still i want the programme to continue to read what i have. Unfortunately, the programme stop with an error that says file path not found at the Set o_file = fs2.OpenTextFile line. I tried to solve the issue using error resume next and on error goto 0 but this time it cause another error at the line Do While o_file.atendofstream <> True which says object variable or with object variable not set error and i tried to use error resume next again but it still wont solve it. </p>

```<code>Sub main()

call get_file_namevcap

end sub

Private Sub get_file_namevcap() 'check csv file using readdata sub

Dim i As Integer
Dim filename As String
Dim location As String
location = Me.ComboBox2
i = 2
Do While ActiveWorkbook.Sheets("IndexPTN_STI").Cells(i, 41) <> ""
      filename = location & "\" & ActiveWorkbook.Sheets("IndexPTN_STI").Cells(i, 41) 'getting csv file name eg:"Vramp_bke_2019.09.28_09.10.51.csv"
Call readdatavcap1(filename, i)

    i = i + 1
Loop
end sub

Private Sub readdatavcap1(filename As String, i As Integer)
Application.ScreenUpdating = False

Dim sl As String
Dim first As Integer
Dim second As Integer
Dim j As Long
Dim fs2 As New Scripting.FileSystemObject
Dim o_file As Scripting.TextStream
j = 2        'variable not defined at fs2

If Dir(filename) <> "" Then

Set fs2 = CreateObject("Scripting.FileSystemObject") 'FileSystemObject also called as FSO, provides an easy object based model to access computer's file system.
                                                      'o_file contains filename(csv file link)
Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse) '1=Open a file for reading only. You can't write to this file. TristateFalse means u get ascii file by default
                                                          '2=ForWriting, 8= Forappending
                   'o_file contains filename(text file data)
 sl = o_file.readline 'Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
 On Error GoTo 0

 Do While Left(sl, 1) = "#"   'Left Function is used to extract N number of characters from a string from the left side.
 sl = o_file.readline
 Loop

 Do While o_file.atendofstream <> True 'atendofstream = Read-only property that returns True if the file pointer is at the end of a TextStream file; False if it is not.
 On Error GoTo 0

    sl = o_file.readline

    first = InStr(32, sl, ",", 1) - 15 'INSTR function returns the position of the first occurrence of a substring in a string.
On Error GoTo 0

    second = InStr(first + 2, sl, ",", 1) 'syntax of InStr( [start], string, substring, [compare] )
                                          'start sets string position for each search, string = string being search, substring= string expression searched ,
                                          'eg:InStr(1, "Tech on the Net", "t") Result: 9    'Shows that search is case-sensitive
                                          'compare= optional 1= textcompare
                                          'searching for commas in the file in this case

         If second = 0 Then
         second = Len(sl) + 1 'len=length of file string
         End If

    'Write the normal current trace
        ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)

         ' The MID function returns the specified number of characters in a text string, starting from a specified position (
       'ie. starting from a specified character number).
       'Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers).

        ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
    On Error GoTo 0
     End If

 j = j + 1
 Loop

 o_file.Close

end if

End Sub
</code>```

答:
Do not rely on error handling for this. It is simple to check to see if the file exists first, and then skip it if it does not exist:

```<code>' start your loop

If Dir(filenameIncludingPath) <> "" Then
  ' file was found, so open it and do what you want with it here

  ' dont forget to close it here when you are done

Else

    MsgBox "NOT FOUND: " & filenameIncludingPath

End If

' continue the loop
</code>```

Keep in mind that On Error Resume Next should only be used in very rare cases, as this is certainly not one of them, because you are not just ignoring the one error you think might happen, you are ignoring all other possible errors as well.

Body:
Cells(i,41) represents the csv file locations that i suppose the csv folder has it which i have stored them in my spreadsheet. However, some of my csv files are not in my csv folder but still i want the programme to continue to read what i have. Unfortunately, the programme stop with an error that says file path not found at the Set o_file = fs2.OpenTextFile line. I tried to solve the issue using error resume next and on error goto 0 but this time it cause another error at the line Do While o_file.atendofstream <> True which says object variable or with object variable not set error and i tried to use error resume next again but it still wont solve it.

Sub main()

call get_file_namevcap

end sub

Private Sub get_file_namevcap() 'check csv file using readdata sub

Dim i As Integer
Dim filename As String
Dim location As String
location = Me.ComboBox2
i = 2
Do While ActiveWorkbook.Sheets("IndexPTN_STI").Cells(i, 41) <> ""
      filename = location & "\" & ActiveWorkbook.Sheets("IndexPTN_STI").Cells(i, 41) 'getting csv file name eg:"Vramp_bke_2019.09.28_09.10.51.csv"
Call readdatavcap1(filename, i)

    i = i + 1
Loop
end sub

Private Sub readdatavcap1(filename As String, i As Integer)
Application.ScreenUpdating = False

Dim sl As String
Dim first As Integer
Dim second As Integer
Dim j As Long
Dim fs2 As New Scripting.FileSystemObject
Dim o_file As Scripting.TextStream
j = 2        'variable not defined at fs2

If Dir(filename) <> "" Then

Set fs2 = CreateObject("Scripting.FileSystemObject") 'FileSystemObject also called as FSO, provides an easy object based model to access computer's file system.
                                                      'o_file contains filename(csv file link)
Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse) '1=Open a file for reading only. You can't write to this file. TristateFalse means u get ascii file by default
                                                          '2=ForWriting, 8= Forappending
                   'o_file contains filename(text file data)
 sl = o_file.readline 'Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
 On Error GoTo 0

 Do While Left(sl, 1) = "#"   'Left Function is used to extract N number of characters from a string from the left side.
 sl = o_file.readline
 Loop

 Do While o_file.atendofstream <> True 'atendofstream = Read-only property that returns True if the file pointer is at the end of a TextStream file; False if it is not.
 On Error GoTo 0

    sl = o_file.readline

    first = InStr(32, sl, ",", 1) - 15 'INSTR function returns the position of the first occurrence of a substring in a string.
On Error GoTo 0

    second = InStr(first + 2, sl, ",", 1) 'syntax of InStr( [start], string, substring, [compare] )
                                          'start sets string position for each search, string = string being search, substring= string expression searched ,
                                          'eg:InStr(1, "Tech on the Net", "t") Result: 9    'Shows that search is case-sensitive
                                          'compare= optional 1= textcompare
                                          'searching for commas in the file in this case

         If second = 0 Then
         second = Len(sl) + 1 'len=length of file string
         End If

    'Write the normal current trace
        ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)

         ' The MID function returns the specified number of characters in a text string, starting from a specified position (
       'ie. starting from a specified character number).
       'Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers).

        ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
    On Error GoTo 0
     End If

 j = j + 1
 Loop

 o_file.Close

end if

End Sub

Body:
Do not rely on error handling for this. It is simple to check to see if the file exists first, and then skip it if it does not exist:

' start your loop

If Dir(filenameIncludingPath) <> "" Then
  ' file was found, so open it and do what you want with it here

  ' dont forget to close it here when you are done

Else

    MsgBox "NOT FOUND: " & filenameIncludingPath

End If

' continue the loop

Keep in mind that On Error Resume Next should only be used in very rare cases, as this is certainly not one of them, because you are not just ignoring the one error you think might happen, you are ignoring all other possible errors as well.


问:
I can't fill 'input' and 'textarea'
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>
  <!--  <input type='text' style='color:black;' class='userInfo' id='userName' /> I tried textarea becuase
                                                                                input tag does not work.-->
</div></code>```

Thanks for your help :)

答: I'm not too sure what the issue is could you include the entire code, I got a three.js cdn and linked it to a page with your snippet and everything is working as it should.</p>

Title: I can't fill 'input' and 'textarea'

Body:
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}

  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>

Thanks for your help :)


问:
How to ignore case in String.replace
```<code>string sentence = "We know it contains 'camel' word.";
// Camel can be in different cases:
string s1 = "CAMEL";
string s2 = "CaMEL";
string s3 = "CAMeL";
// ...
string s4 = "Camel";
// ...
string s5 = "camel";
</code>```

How to replace 'camel' in sentence with 'horse' despite of string.Replace doesn't support ignoreCase on left string?

答:
Use a regular expression:

```<code>var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );
</code>```

Of course, this will also match words containing camel, but it's not clear if you want that or not.

If you need exact matches you can use a custom MatchEvaluator.

```<code>public static class Evaluators
{
    public static string Wrap( Match m, string original, string format )
    {
        // doesn't match the entire string, otherwise it is a match
        if (m.Length != original.Length)
        {
            // has a preceding letter or digit (i.e., not a real match).
            if (m.Index != 0 && char.IsLetterOrDigit( original[m.Index - 1] ))
            {
                return m.Value;
            }
            // has a trailing letter or digit (i.e., not a real match).
            if (m.Index + m.Length != original.Length && char.IsLetterOrDigit( original[m.Index + m.Length] ))
            {
                return m.Value;
            }
        }
        // it is a match, apply the format
        return string.Format( format, m.Value );
    }
}
</code>```

Used with the previous example to wrap the match in a span as:

```<code>var regex = new Regex( highlightedWord, RegexOptions.IgnoreCase );
foreach (var sentence in sentences)
{
    var evaluator = new MatchEvaluator( match => Evaluators.Wrap( match, sentence, "<span class='red'>{0}</span>" ) );
    Console.WriteLine( regex.Replace( sentence, evaluator ) );
}
</code>```

Title: How to ignore case in String.replace

Body:
string sentence = "We know it contains 'camel' word.";
// Camel can be in different cases:
string s1 = "CAMEL";
string s2 = "CaMEL";
string s3 = "CAMeL";
// ...
string s4 = "Camel";
// ...
string s5 = "camel";

How to replace 'camel' in sentence with 'horse' despite of string.Replace doesn't support ignoreCase on left string?

Body:
Use a regular expression:

var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );

Of course, this will also match words containing camel, but it's not clear if you want that or not.

If you need exact matches you can use a custom MatchEvaluator.

public static class Evaluators
{
    public static string Wrap( Match m, string original, string format )
    {
        // doesn't match the entire string, otherwise it is a match
        if (m.Length != original.Length)
        {
            // has a preceding letter or digit (i.e., not a real match).
            if (m.Index != 0 && char.IsLetterOrDigit( original[m.Index - 1] ))
            {
                return m.Value;
            }
            // has a trailing letter or digit (i.e., not a real match).
            if (m.Index + m.Length != original.Length && char.IsLetterOrDigit( original[m.Index + m.Length] ))
            {
                return m.Value;
            }
        }
        // it is a match, apply the format
        return string.Format( format, m.Value );
    }
}

Used with the previous example to wrap the match in a span as:

var regex = new Regex( highlightedWord, RegexOptions.IgnoreCase );
foreach (var sentence in sentences)
{
    var evaluator = new MatchEvaluator( match => Evaluators.Wrap( match, sentence, "<span class='red'>{0}</span>" ) );
    Console.WriteLine( regex.Replace( sentence, evaluator ) );
}


问:
Call default JsonSerializer in a JsonConverter for certain value type arrays
I'm trying to achieve roughly what's described here:

Recursively call JsonSerializer in a JsonConverter

In short; To examine a value being deserialised, then either consume it in my own code, or hand it off the the default deserializer.

The example uses a nifty trick to avoid the same custom code being called recursively:

```<code>...
else if (reader.TokenType == JsonToken.StartObject)
    // Use DummyDictionary to fool JsonSerializer into not using this converter recursively
    dictionary = serializer.Deserialize<DummyDictionary>(reader);
else
    dictionary = new Dictionary<TKey, TValue>();
return dictionary;

/// <summary>
/// Dummy to fool JsonSerializer into not using this converter recursively
/// </summary>
private class DummyDictionary : Dictionary<TKey, TValue> { }
</code>```

The DummyDictionary class acts as a proxy to control flow when Json.Net looks for a new deserializer.

I need to achieve the same for a byte[] instead of a Dictionary. If it's a string, I want to pass it off to the default handler. If an array of int, I'll handle myself.

Unfortunately, I can't implement a

```<code>private class DummyByteArray : byte[] { }
</code>```

as byte is a value type and isn't an inheritable interface.

How can I achieve the control I need without changing every instance of a byte[] in my objects to SomeNoddyByteProxy?

答:
Firstly, as an aside, I note that Json.NET supports deserializing both an array of integers and a Base64 string to a byte [] array natively.  I.e. the following unit test assertions both just work:

```<code>Assert.IsTrue(JsonConvert.DeserializeObject<byte []>("[1, 2]")
              .SequenceEqual(new [] { (byte)1, (byte)2 }));
Assert.IsTrue(JsonConvert.DeserializeObject<byte []>("\"AQI=\"")
              .SequenceEqual(new [] { (byte)1, (byte)2 }));
</code>```

Demo fiddle #1 here.

That being said, there are a few options given in JSON.Net throws StackOverflowException when using [JsonConvert()] as well as this answer to Newtonsoft Json.NET JsonConverter attribute preserve references issue when deserializing for recursively calling the serializer to get a "default" deserialization:

If you don't need to pre-load the JSON into a JToken hierarchy, you can have the converter disable itself using a thread static member, and then call serializer.Deserialize() recursively.

If you do need to pre-load the JSON into a JToken hierarchy, you can embed the hierarchy inside a parent container and supersede and disable the converter using a dummy converter on the container's member.

An example converter using option #1 might look as follows:

```<code>public sealed class ByteConverter : JsonConverter<byte[]>
{
    [ThreadStatic]
    static bool disabled;

    // Disables the converter in a thread-safe manner.
    bool Disabled { get { return disabled; } set { disabled = value; } }

    public override bool CanRead { get { return !Disabled; } }

    public override byte[] ReadJson(JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        switch (reader.MoveToContentAndAssert().TokenType) // Skip past comments
        {
            case JsonToken.Null:
                return null;

            case JsonToken.StartArray:
                // Your custom logic here, e.g.:
                return serializer.Deserialize<List<byte>>(reader).ToArray();

            default:
                using (new PushValue<bool>(true, () => Disabled, val => Disabled = val))
                    return serializer.Deserialize<byte []>(reader);
        }
    }

    // Remainder omitted
    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, byte[] value, JsonSerializer serializer) => throw new NotImplementedException();
}

public struct PushValue<T> : IDisposable
{
    Action<T> setValue;
    T oldValue;

    public PushValue(T value, Func<T> getValue, Action<T> setValue)
    {
        if (getValue == null || setValue == null)
            throw new ArgumentNullException();
        this.setValue = setValue;
        this.oldValue = getValue();
        setValue(value);
    }

    // By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
    public void Dispose()
    {
        if (setValue != null)
            setValue(oldValue);
    }
}

public static partial class JsonExtensions
{
    public static JsonReader MoveToContentAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
            reader.ReadAndAssert();
        while (reader.TokenType == JsonToken.Comment) // Skip past comments.
            reader.ReadAndAssert();
        return reader;
    }

    public static JsonReader ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
            throw new JsonReaderException("Unexpected end of JSON stream.");
        return reader;
    }
}
</code>```

Demo fiddle #2 here.

However, in your case things are simpler.  Json.NET considers a byte [] array represented as a Base64 string to be a primitive, so you can simply load it into a JToken and use the JToken Explicit Conversion (JToken toByte[]) operator to cast it to a byte[] array like so:

```<code>public class ByteConverter : JsonConverter<byte[]>
{
    public override byte[] ReadJson(JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        switch (reader.MoveToContentAndAssert().TokenType) // Skip past comments
        {
            case JsonToken.Null:
                return null;

            case JsonToken.StartArray:
                // Your custom logic here, e.g.:
                return serializer.Deserialize<List<byte>>(reader).ToArray();

            default:
                return (byte[])JToken.Load(reader);
        }
    }

    // Remainder omitted
</code>```

This entirely avoids use of the serializer.  Demo fiddle #3 here.

Body:
I'm trying to achieve roughly what's described here:

Recursively call JsonSerializer in a JsonConverter

In short; To examine a value being deserialised, then either consume it in my own code, or hand it off the the default deserializer.

The example uses a nifty trick to avoid the same custom code being called recursively:

...
else if (reader.TokenType == JsonToken.StartObject)
    // Use DummyDictionary to fool JsonSerializer into not using this converter recursively
    dictionary = serializer.Deserialize<DummyDictionary>(reader);
else
    dictionary = new Dictionary<TKey, TValue>();
return dictionary;

///
/// Dummy to fool JsonSerializer into not using this converter recursively
///
private class DummyDictionary : Dictionary<TKey, TValue> { }

The DummyDictionary class acts as a proxy to control flow when Json.Net looks for a new deserializer.

I need to achieve the same for a byte[] instead of a Dictionary. If it's a string, I want to pass it off to the default handler. If an array of int, I'll handle myself.

Unfortunately, I can't implement a

private class DummyByteArray : byte[] { }

as byte is a value type and isn't an inheritable interface.

How can I achieve the control I need without changing every instance of a byte[] in my objects to SomeNoddyByteProxy?

Body:
Firstly, as an aside, I note that Json.NET supports deserializing both an array of integers and a Base64 string to a byte [] array natively.  I.e. the following unit test assertions both just work:

Assert.IsTrue(JsonConvert.DeserializeObject<byte []>("[1, 2]")
              .SequenceEqual(new [] { (byte)1, (byte)2 }));
Assert.IsTrue(JsonConvert.DeserializeObject<byte []>("\"AQI=\"")
              .SequenceEqual(new [] { (byte)1, (byte)2 }));

Demo fiddle #1 here.

That being said, there are a few options given in JSON.Net throws StackOverflowException when using [JsonConvert()] as well as this answer to Newtonsoft Json.NET JsonConverter attribute preserve references issue when deserializing for recursively calling the serializer to get a "default" deserialization:

If you don't need to pre-load the JSON into a JToken hierarchy, you can have the converter disable itself using a thread static member, and then call serializer.Deserialize() recursively.

If you do need to pre-load the JSON into a JToken hierarchy, you can embed the hierarchy inside a parent container and supersede and disable the converter using a dummy converter on the container's member.

An example converter using option #1 might look as follows:

public sealed class ByteConverter : JsonConverter<byte[]>
{
    [ThreadStatic]
    static bool disabled;

    // Disables the converter in a thread-safe manner.
    bool Disabled { get { return disabled; } set { disabled = value; } }

    public override bool CanRead { get { return !Disabled; } }

    public override byte[] ReadJson(JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        switch (reader.MoveToContentAndAssert().TokenType) // Skip past comments
        {
            case JsonToken.Null:
                return null;

            case JsonToken.StartArray:
                // Your custom logic here, e.g.:
                return serializer.Deserialize<List<byte>>(reader).ToArray();

            default:
                using (new PushValue<bool>(true, () => Disabled, val => Disabled = val))
                    return serializer.Deserialize<byte []>(reader);
        }
    }

    // Remainder omitted
    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, byte[] value, JsonSerializer serializer) => throw new NotImplementedException();
}

public struct PushValue<T> : IDisposable
{
    Action<T> setValue;
    T oldValue;

    public PushValue(T value, Func<T> getValue, Action<T> setValue)
    {
        if (getValue == null || setValue == null)
            throw new ArgumentNullException();
        this.setValue = setValue;
        this.oldValue = getValue();
        setValue(value);
    }

    // By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
    public void Dispose()
    {
        if (setValue != null)
            setValue(oldValue);
    }
}

public static partial class JsonExtensions
{
    public static JsonReader MoveToContentAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
            reader.ReadAndAssert();
        while (reader.TokenType == JsonToken.Comment) // Skip past comments.
            reader.ReadAndAssert();
        return reader;
    }

    public static JsonReader ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
            throw new JsonReaderException("Unexpected end of JSON stream.");
        return reader;
    }
}

Demo fiddle #2 here.

However, in your case things are simpler.  Json.NET considers a byte [] array represented as a Base64 string to be a primitive, so you can simply load it into a JToken and use the JToken Explicit Conversion (JToken toByte[]) operator to cast it to a byte[] array like so:

public class ByteConverter : JsonConverter<byte[]>
{
    public override byte[] ReadJson(JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        switch (reader.MoveToContentAndAssert().TokenType) // Skip past comments
        {
            case JsonToken.Null:
                return null;

            case JsonToken.StartArray:
                // Your custom logic here, e.g.:
                return serializer.Deserialize<List<byte>>(reader).ToArray();

            default:
                return (byte[])JToken.Load(reader);
        }
    }

    // Remainder omitted

This entirely avoids use of the serializer.  Demo fiddle #3 here.


问:
How to execute code if the difference in the value of a variable is over 20
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

```<code>if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}
</code>```

答:
Maybe this is what you wanted

if (var2-var1 >= 20) {
    // Insert code here
}
```

<p>But if you want to check both if var2 and var1 are apart by 20 atleast one could be lesser one could be greater, then</p>

<pre class="lang-js prettyprint-override"><code>if (Math.abs(var2-var1) >= 20) {
    // Insert code here
}
</code>```

Body:
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}

Body:
Maybe this is what you wanted

if (var2-var1 >= 20) {
    // Insert code here
}

But if you want to check both if var2 and var1 are apart by 20 atleast one could be lesser one could be greater, then

if (Math.abs(var2-var1) >= 20) {
    // Insert code here
}


问:
PHP Excel can't save on folder
I want to save my excel file to my server.

Folder location is public_html/PHPExcel/generated/

Please see code below:

```<code>header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="filename.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace(__FILE__,'public_html/PHPExcel/generated/filename.xls',__FILE__));
</code>```

Thank you

答:
Try this

```<code>$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$file = "file.csv";
ob_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename='.$file);
$objWriter->save('php://output', 'w');
</code>```

Title: PHP Excel can't save on folder

Body:
I want to save my excel file to my server.

Folder location is public_html/PHPExcel/generated/

Please see code below:

header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="filename.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace(__FILE__,'public_html/PHPExcel/generated/filename.xls',__FILE__));

Thank you

Body:
Try this

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$file = "file.csv";
ob_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename='.$file);
$objWriter->save('php://output', 'w');


问:
Why does foreach fail to find my GetEnumerator extension method?
I'm trying to make some code more readable. For Example foreach(var row in table) {...} rather than foreach(DataRow row in table.Rows) {...}.

To do this I created an extension method:

```<code>namespace System.Data {
    public static class MyExtensions {
        public static IEnumerable<DataRow> GetEnumerator( this DataTable tbl ) {
            foreach ( DataRow r in tbl.Rows ) yield return r;
        }
    }
}
</code>```

But the compiler still throws foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator'.

To confirm that I implemented the extension method appropriately I tried the following code instead and the compiler had no problem with it.

```<code>for ( IEnumerator<DataRow> enm = data.GetEnumerator(); enm.MoveNext(); ) {
    var row = enm.Current;
    ...
}
</code>```

Before you say that it is because IEnumerator or IEnumerator<DataRow> is not implemented, consider that the following does compile:

```<code>public class test {
    public void testMethod() {
        foreach ( var i in new MyList( 1, 'a', this ) ) { }
    }
}
public class MyList {
    private object[] _list;
    public MyList( params object[] list ) { _list = list; }
    public IEnumerator<object> GetEnumerator() { foreach ( var o in _list ) yield return o; }
}
</code>```

答: Current proposal to add GetEnumerator via Extension to C# https://github.com/dotnet/csharplang/issues/3194 </p>

Body:
I'm trying to make some code more readable. For Example foreach(var row in table) {...} rather than foreach(DataRow row in table.Rows) {...}.

To do this I created an extension method:

namespace System.Data {
    public static class MyExtensions {
        public static IEnumerable<DataRow> GetEnumerator( this DataTable tbl ) {
            foreach ( DataRow r in tbl.Rows ) yield return r;
        }
    }
}

But the compiler still throws foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator'.

To confirm that I implemented the extension method appropriately I tried the following code instead and the compiler had no problem with it.

for ( IEnumerator<DataRow> enm = data.GetEnumerator(); enm.MoveNext(); ) {
    var row = enm.Current;
    ...
}

Before you say that it is because IEnumerator or IEnumerator<DataRow> is not implemented, consider that the following does compile:

public class test {
    public void testMethod() {
        foreach ( var i in new MyList( 1, 'a', this ) ) { }
    }
}
public class MyList {
    private object[] _list;
    public MyList( params object[] list ) { _list = list; }
    public IEnumerator<object> GetEnumerator() { foreach ( var o in _list ) yield return o; }
}


问:
Java Array vs Array List
Java array vs Java ArrayList: I wrote a program to compare the time it takes to store a Java array and ArrayList of size MAX with random numbers. Are these results coming out right? Is ArrayList supposed to be faster?

```<code>package arraylists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class arraylists {

    public final static int MAX = 10000;
    static Random rand = new Random();
    static int rand_int1 = rand.nextInt(1000);
    static int rand_int2 = rand.nextInt(1000);

    public static void arrayFunc(int a1 ) {

        int [] arry = new int[a1];

        for(int i = 0; i < a1; i++) {
            arry[i] =  rand_int1;
        }

    }

    public static void arrayList(int a2) {

        ArrayList<Integer> num = new ArrayList<Integer>();

        for(int i = 0; i < a2; i++) {
            num.add(rand_int2);
        }

}

    public static void main(String args[]) {

        for(int i = 0; i < 10; i++){
            int num;
            System.out.println("Enter the number of iterations: ");
            Scanner input = new Scanner(System.in);
            num = input.nextInt();

            long start1 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end1 = System.nanoTime();
            long timeElapsed1 = end1 - start1;

            long start2 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end2 = System.nanoTime();
            long timeElapsed2 = end2 - start2;

            System.out.println("Java Array execution time (in nanonseconds): " + timeElapsed1);
            System.out.println("Java Array List execution time (in nanoseconds): " + timeElapsed2);
        }

    }

}
</code>```

Java Array vs Java Array List: I wrote a program to compare the time it takes to store a java array and array list of size MAX with random numbers, are these numbers coming out right? is array list suppose to be faster?

答:
Both of your tests call arrayFunc(). Your arrayList() method is never used.

After correcting your test, I get the following output:

Enter the number of iterations:
10
Java Array execution time (in nanoseconds): 7703329
Java Array List execution time (in nanoseconds): 49696074
```

<p>This indicates that the array version is about <strong>6.45</strong> times faster. I suspect that the bulk of that difference stems from the fact that the array that is backing the <code>ArrayList</code> needs to be re-dimensioned several times. This can be mitigated by specifying the required capacity for the <code>ArrayList</code> beforehand:</p>

```ArrayList<Integer> num = new ArrayList<Integer>(a2);
```

Cursory tests indicate that this will speed up your ArrayList method by a factor of 2.

Note that there might also be some concerns about the methods used to benchmark, but I expect that even with correct benchmarking, you will get similar results.

Title: Java Array vs Array List

Body:
Java array vs Java ArrayList: I wrote a program to compare the time it takes to store a Java array and ArrayList of size MAX with random numbers. Are these results coming out right? Is ArrayList supposed to be faster?

package arraylists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class arraylists {

    public final static int MAX = 10000;
    static Random rand = new Random();
    static int rand_int1 = rand.nextInt(1000);
    static int rand_int2 = rand.nextInt(1000);

    public static void arrayFunc(int a1 ) {

        int [] arry = new int[a1];

        for(int i = 0; i < a1; i++) {
            arry[i] =  rand_int1;
        }

    }

    public static void arrayList(int a2) {

        ArrayList<Integer> num = new ArrayList<Integer>();

        for(int i = 0; i < a2; i++) {
            num.add(rand_int2);
        }

}

    public static void main(String args[]) {

        for(int i = 0; i < 10; i++){
            int num;
            System.out.println("Enter the number of iterations: ");
            Scanner input = new Scanner(System.in);
            num = input.nextInt();

            long start1 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end1 = System.nanoTime();
            long timeElapsed1 = end1 - start1;

            long start2 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end2 = System.nanoTime();
            long timeElapsed2 = end2 - start2;

            System.out.println("Java Array execution time (in nanonseconds): " + timeElapsed1);
            System.out.println("Java Array List execution time (in nanoseconds): " + timeElapsed2);
        }

    }

}

Java Array vs Java Array List: I wrote a program to compare the time it takes to store a java array and array list of size MAX with random numbers, are these numbers coming out right? is array list suppose to be faster?

Body:
Both of your tests call arrayFunc(). Your arrayList() method is never used.

After correcting your test, I get the following output:

Enter the number of iterations:
10
Java Array execution time (in nanoseconds): 7703329
Java Array List execution time (in nanoseconds): 49696074

This indicates that the array version is about 6.45 times faster. I suspect that the bulk of that difference stems from the fact that the array that is backing the ArrayList needs to be re-dimensioned several times. This can be mitigated by specifying the required capacity for the ArrayList beforehand:

ArrayList<Integer> num = new ArrayList<Integer>(a2);

Cursory tests indicate that this will speed up your ArrayList method by a factor of 2.

Note that there might also be some concerns about the methods used to benchmark, but I expect that even with correct benchmarking, you will get similar results.


问:
USB Mass Storrage on File Level
The Challenge: I have an Linux hand-held device, which records data and stores it to the disc. It should exchange these data with a Windows application via USB. When this data is accessible by the user - e.g. via USB-mass-storage - it has to be encrypted. It should work out-of-the-box, with a variety of OS, also for citrix terminal sessions, etc.

The Plan: I create a file-system in user-space with FUSE, and offer it to windows via mass-storage. Whenever Windows accesses one file, I get a callback and encrypt the data on the fly. Further more, we can have some dynamic content - e.g. when some password is written into a file, more content is shown.

The Problem: When using the mass-storage gadget (e.g. g_file_storage) it only accepts files or block-devices - but no file-systems (directories). Why?

[...] it provides a simple interface to read and write sectors of data—much like the low-level interface used to access any hard drive [...]. Operating systems may treat the USB drive like a hard drive, and can format it with any file system they like. (from wikipedia)

So there is no chance to have a dynamic file-system via mass-storage... and this seems to be the reason, why my android mobile phone un-mounts all data on the phone, when I connect it to the PC.

Options:

Create a 'block-device in userspace' - similar to FUSE (need a reverse-FAT-driver, when I want to offer files dynamically)

Implement my own nbd-server to create a block-device (need a reverse-FAT-driver as well?)

I save encrypted files to a partition, and pass this partition to the mass-storage gadget (Problem would be the performance and the lack of dynamic interaction)

Do not offer a mass-storrage device and watch out for other ideas (eth over USB)

At the moment, only the last option seems to be realistic - or do you have another tip for me?

I would be grateful!

Charly

答:
It may interest you to know that Android, which previously exposed itself as a USB mass storage device to the host, is instead acting as an MTP device (as of Honeycomb).

That being said, somebody has already implemented your option 1, though with the "device" and "host" a bit reversed.  QEMU has an insane hack called vvfat which is able to create a fake block device which to the VM looks like it contains a VFAT filesytem just from a directory/file tree on the host.  It requires a full recursive scan before starting, is dependent on details of how OSes write to filesystems, and falls over if you independently change any files while it's in use, but (somehow) manages to (sometimes) work.

Title: USB Mass Storrage on File Level


问:
Converting null-terminated lines to JSON strings with jq
I've come up with a jq-based one-liner that converts a sequence of null-terminated strings to a sequence of JSON strings:

```<code>xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_
</code>```

I'd like to cut xargs and/or dash out of it if possible. Is there a way to do the same thing with just jq?

Example usage:

```<code># Create a new dir with some funny-named files
mkdir funny
cd funny
touch $'ABC\nDEF' $' GHI\nJKL ' ' - はじめまして - '
# Use find -print0 to list the files
find -type f -print0 |
# Convert the null-terminated lines to JSON strings
xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_
</code>```

Output:

```<code>"./ - はじめまして - "
"./ GHI\nJKL "
"./ABC\nDEF"
</code>```

答:
The following produces the output you've specified:</p>

```<code>find . -type f -print0 | jq -Rs 'split("\u0000")[]'
</code>```

Body:
I've come up with a jq-based one-liner that converts a sequence of null-terminated strings to a sequence of JSON strings:

xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_

I'd like to cut xargs and/or dash out of it if possible. Is there a way to do the same thing with just jq?

Example usage:

# Create a new dir with some funny-named files
mkdir funny
cd funny
touch $'ABC\nDEF' $' GHI\nJKL ' ' - はじめまして - '
# Use find -print0 to list the files
find -type f -print0 |
# Convert the null-terminated lines to JSON strings
xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_

Output:

"./ - はじめまして - "
"./ GHI\nJKL "
"./ABC\nDEF"

Body:
The following produces the output you've specified:

find . -type f -print0 | jq -Rs 'split("\u0000")[]'


答:
Demo on dotnet fiddle

You need to get all qualified groups by grouping then where the condition

Loop all StudentsList list to update IsQualified accordingly.

```<code>var qualifiedGroups = StudentsList
             .GroupBy(x => x.GroupID)
             .Where(x => x.Any(y => y.University == "OPQ"))
             .Select(g => g.Key).ToArray();

StudentsList.ForEach(x => x.IsQualified = Array.IndexOf(qualifiedGroups, x.GroupID) != -1);

foreach(var item in StudentsList)
    Console.WriteLine("Group:" + item.GroupID + " Student:" + item.Student +  " IsQualified:" + item.IsQualified);
</code>```

Output

```<code>Group:1 Student:John IsQualified:False
Group:1 Student:Jack IsQualified:False
Group:1 Student:Peter IsQualified:False
Group:2 Student:Donald IsQualified:True
Group:2 Student:Olivia IsQualified:True
Group:2 Student:Emity IsQualified:True
Group:2 Student:Emma IsQualified:True
Group:2 Student:Alan IsQualified:True
Group:3 Student:Adam IsQualified:True
Group:3 Student:Jacob IsQualified:True
Group:3 Student:Matthew IsQualified:True
Group:3 Student:Saint IsQualified:True
Group:3 Student:Joshua IsQualified:True
Group:3 Student:Aubrey IsQualified:True
</code>```

Title: Linq query update all items in groups that meet my condition

Body:
I want to update the property "IsQualified= True" for-

All students in only qualified groups

Qualified groups? Those groups that have at least one student who passed from "University= OPQ" (Example: Group 2 and 3)

Leave other group students' "IsQualified" property unchanged. (Example: Group 1)

What I tried-

var results = studentsList
.Where(x => x.University= OPQ)
.GroupBy(x => x.GroupID)
.SelectMany(g => g)
.ToList();

results.ForEach(x => x.IsQualified = true);

This doesn't work. Please help me.

My Code-

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}

}

List<StudentInfo> studentsList = new List<StudentInfo>();

StudentsList.Add( new StudentInfo { Student="John", University="ABC", GroupID = 1, IsQualified=False});
StudentsList.Add( new StudentInfo { Student="Jack", University="DEF", GroupID = 1, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Peter", University="GHI", GroupID = 1, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Donald", University="JKL", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ABC", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Emma", University="GHI", GroupID = 2, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Alan", University="DEF", GroupID = 2, IsQualified=False} );

StudentsList.Add( new StudentInfo { Student="Adam", University="GHI", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="ABC", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Saint", University="VWX", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="TRP", GroupID = 3, IsQualified=False} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="STU", GroupID = 3, IsQualified=False} );

Body:
Demo on dotnet fiddle

You need to get all qualified groups by grouping then where the condition

Loop all StudentsList list to update IsQualified accordingly.

var qualifiedGroups = StudentsList
             .GroupBy(x => x.GroupID)
             .Where(x => x.Any(y => y.University == "OPQ"))
             .Select(g => g.Key).ToArray();

StudentsList.ForEach(x => x.IsQualified = Array.IndexOf(qualifiedGroups, x.GroupID) != -1);

foreach(var item in StudentsList)
    Console.WriteLine("Group:" + item.GroupID + " Student:" + item.Student +  " IsQualified:" + item.IsQualified);

Output

Group:1 Student:John IsQualified:False
Group:1 Student:Jack IsQualified:False
Group:1 Student:Peter IsQualified:False
Group:2 Student:Donald IsQualified:True
Group:2 Student:Olivia IsQualified:True
Group:2 Student:Emity IsQualified:True
Group:2 Student:Emma IsQualified:True
Group:2 Student:Alan IsQualified:True
Group:3 Student:Adam IsQualified:True
Group:3 Student:Jacob IsQualified:True
Group:3 Student:Matthew IsQualified:True
Group:3 Student:Saint IsQualified:True
Group:3 Student:Joshua IsQualified:True
Group:3 Student:Aubrey IsQualified:True


问:
can not load the css file
I know this is a very basic question but I cannot deal with it in this situation. I'm using Vertx. When I deploy my verticle which render index.peb file but cannot load the css files.

This is my folder :

this is link to css file :

```<code><link rel="stylesheet" href="../statics/css/bootstrap.min.css">
</code>```

and the error :

WARNING: 0:0:0:0:0:0:0:1 - - [Mon, 17 Feb 2020 03:19:48 GMT] "GET
  /statics/css/bootstrap.min.css HTTP/1.1" 404 53

答:
The problem here is pretty simple, the href attribute in index.peb is referencing the wrong place for your css file.

The ".." means to go up one folder, so href = ../statics/css/bootstrap.min.css never leaves the templates folder and attempts to reference a file at templates/statics/css/bootstap.min.css.

Fixing this is as simple as adding an extra ../ to the start:

<link rel="stylesheet" href="../../statics/css/bootstrap.min.css">

Title: can not load the css file

Body:
I know this is a very basic question but I cannot deal with it in this situation. I'm using Vertx. When I deploy my verticle which render index.peb file but cannot load the css files.

This is my folder :

this is link to css file :

<link rel="stylesheet" href="../statics/css/bootstrap.min.css">

and the error :

WARNING: 0:0:0:0:0:0:0:1 - - [Mon, 17 Feb 2020 03:19:48 GMT] "GET
  /statics/css/bootstrap.min.css HTTP/1.1" 404 53


问:
How do I compare 2 different sized 2D arrays?
The first 2D array is

```<code>[[1, 10], [0, 4], [1, 1]]
</code>```

The second 2D array is

```<code>[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]
</code>```

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].

答:
If duplicate key found in first 2D array, the last one will override the previous value.
Simple for loop for the beginner of Java.</p>

```<code>public static void main(String[] args) {
    int[][] firsts = {{1, 10}, {0, 4}, {1, 1}};
    int[][] seconds = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}};

    for(int[] secondRow : seconds) {
        for(int[] firstRow: firsts) {
            if(firstRow[1] == secondRow[1])
                secondRow[0] = firstRow[0];
        }
    }

    // Use for displaying updated result only
    for(int[] secondRow : seconds)
        System.out.println("[" + secondRow[0] + ", " + secondRow[1] + "]");

}
</code>```

Body:
The first 2D array is

[[1, 10], [0, 4], [1, 1]]

The second 2D array is

[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].

Body:
If duplicate key found in first 2D array, the last one will override the previous value.
Simple for loop for the beginner of Java.

public static void main(String[] args) {
    int[][] firsts = {{1, 10}, {0, 4}, {1, 1}};
    int[][] seconds = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}};

    for(int[] secondRow : seconds) {
        for(int[] firstRow: firsts) {
            if(firstRow[1] == secondRow[1])
                secondRow[0] = firstRow[0];
        }
    }

    // Use for displaying updated result only
    for(int[] secondRow : seconds)
        System.out.println("[" + secondRow[0] + ", " + secondRow[1] + "]");

}


问:
Calculating factorial of large numbers in C
In my C code, I want to calculate the factorial for numbers in the range 1 to 100. For small numbers, the function works, but for bigger numbers (for example 100!) it returns incorrect result. Is there any way to handle factorial of large numbers in C?

The compiler I'm using is gcc v4.3.3.
My code is as follows:

```<code>#include <stdio.h>
#include <math.h>

double print_solution(int);

int main(void)
{
        int no_of_inputs, n;
        int ctr = 1;

        scanf("%d",&no_of_inputs); //Read no of inputs

        do
        {
                scanf("%d",&n); //Read the input
                printf("%.0f\n", print_solution(n));
                ctr++;
        } while(ctr <= no_of_inputs);

        return 0;
}

double print_solution(int n)
{
        if(n == 0 || n == 1)
                return 1;
        else
                return n*print_solution(n-1);
}
</code>```

OwnerDisplayName: ronk

Body:
In my C code, I want to calculate the factorial for numbers in the range 1 to 100. For small numbers, the function works, but for bigger numbers (for example 100!) it returns incorrect result. Is there any way to handle factorial of large numbers in C?

The compiler I'm using is gcc v4.3.3.
My code is as follows:

#include <stdio.h>
#include <math.h>

double print_solution(int);

int main(void)
{
        int no_of_inputs, n;
        int ctr = 1;

        scanf("%d",&no_of_inputs); //Read no of inputs

        do
        {
                scanf("%d",&n); //Read the input
                printf("%.0f\n", print_solution(n));
                ctr++;
        } while(ctr <= no_of_inputs);

        return 0;
}

double print_solution(int n)
{
        if(n == 0 || n == 1)
                return 1;
        else
                return n*print_solution(n-1);
}

Body:
Factorials up to 12! fit into a 32-bit integer. Factorials up to 20! fit into a 64-bit integer. After that, you've run out of bits on most machines. However, 34! fits into an unsigned 128-bit integer, 57! fits into a 256-bit integer, and 98! fits into an unsigned 512-bit integer. To calculate 100! as an integer, you need at least 525 bits.

This bc script calculates factorials (up to 35! but you can change the limit easily):

#!/usr/bin/bc -l

define f(n) {
   auto r, i
   r = 1
   for (i = 1; i <= n; i++)
   {
       r *= i;
       print "n = ", i, ", log2 = ", l(r)/l(2), ", n! = ", r, "\n"
   }
}

f(35)
quit

And some sample values:

# Key values
# n =  1, log2 =   0.00000000000000000000, n! = 1
# n =  2, log2 =   1.00000000000000000000, n! = 2
# n =  3, log2 =   2.58496250072115618147, n! = 6
# n =  4, log2 =   4.58496250072115618149, n! = 24
# n =  5, log2 =   6.90689059560851852938, n! = 120
# n =  6, log2 =   9.49185309632967471087, n! = 720
# n =  7, log2 =  12.29920801838727881834, n! = 5040
# n =  8, log2 =  15.29920801838727881836, n! = 40320
# n =  9, log2 =  18.46913301982959118130, n! = 362880
# n = 10, log2 =  21.79106111471695352921, n! = 3628800
# n = 11, log2 =  25.25049273335425078544, n! = 39916800
# n = 12, log2 =  28.83545523407540696694, n! = 479001600
# n = 13, log2 =  32.53589495221649912738, n! = 6227020800
# n = 14, log2 =  36.34324987427410323486, n! = 87178291200
# n = 15, log2 =  40.25014046988262176421, n! = 1307674368000
# n = 16, log2 =  44.25014046988262176426, n! = 20922789888000
# n = 17, log2 =  48.33760331113296117256, n! = 355687428096000
# n = 18, log2 =  52.50752831257527353551, n! = 6402373705728000
# n = 19, log2 =  56.75545582601885902935, n! = 121645100408832000
# n = 20, log2 =  61.07738392090622137726, n! = 2432902008176640000
# n = 21, log2 =  65.46970134368498166621, n! = 51090942171709440000
# ...
# n = 34, log2 = 127.79512061296909618950, n! = 295232799039604140847618609643520000000
# n = 35, log2 = 132.92440362991406264487, n! = 10333147966386144929666651337523200000000
# ...
# n = 57, log2 = 254.48541573017643505939
# n = 58, log2 = 260.34339672530400718017
# ...
# n = 98, log2 = 511.49178048020535201128
# n = 99, log2 = 518.12113710028496163045
# n = 100, log2 = 524.76499329005968632625

For the factorials 57!, 58!, 98!, 99!, 100! I've omitted the factorial value as it spreads over multiple lines in the output and isn't all that important.  Note that 100! requires at least 525 bits of precision.

This code is available in my SOQ (Stack Overflow Questions) repository on GitHub as file factorial.bc in the src/miscellany sub-directory.

You could use double or long double to extend the range of values, but you lose some accuracy.


问:
Why the sequence of SASS @mixin does't matter?
If the @mixin is defined after the rule, there will be an error:

Error: Undefined mixin 'parent'.

```<code>.child {
  @include parent();
}

@mixin parent() {
  box-sizing: border-box;
}
</code>```

But if mixin2 is defined after the mixin1, there is no error, why is this?

```<code>@mixin parent() {
  @include parent2();
  box-sizing: border-box;
}

@mixin parent2() {
  margin: 1px;
}

.child {
  @include parent();
}
</code>```

And the same for the variables:

```<code>.child {
  margin: $variable1;
}

$variable1 : 1px;
</code>```

This produces an error:

Error: Undefined variable: "$variable1".

But this won't

```<code>@mixin parent() {
  margin: $variable1;
}

$variable1 : 1px;

.child {
  @include parent();
}
</code>```

答:
Defining vs Using

When you compiled below scss to css no code will be generated, because mixin doesn't get compiled until you use it.

```<code>@mixin parent() {
  @include parent2();
  box-sizing: border-box;
}

@mixin parent2() {
  margin: 1px;
}
</code>```

and when you do this

```<code>.child {
  @include parent();
}
</code>```

It will look for mixin to generate css while compiling.

In your first case it throws error because .child needs to compile,
  and in second case it did not because mixin never gets compiled until you
  use it

This is the reason we declare mixin/variables or import mixin/variables file before using it.

Hope I answered your question!

Body:
If the @mixin is defined after the rule, there will be an error:

Error: Undefined mixin 'parent'.

.child {
  @include parent();
}

@mixin parent() {
  box-sizing: border-box;
}

But if mixin2 is defined after the mixin1, there is no error, why is this?

@mixin parent() {
  @include parent2();
  box-sizing: border-box;
}

@mixin parent2() {
  margin: 1px;
}

.child {
  @include parent();
}

And the same for the variables:

.child {
  margin: $variable1;
}

$variable1 : 1px;

This produces an error:

Error: Undefined variable: "$variable1".

But this won't

@mixin parent() {
  margin: $variable1;
}

$variable1 : 1px;

.child {
  @include parent();
}

Body:
Defining vs Using

When you compiled below scss to css no code will be generated, because mixin doesn't get compiled until you use it.

@mixin parent() {
  @include parent2();
  box-sizing: border-box;
}

@mixin parent2() {
  margin: 1px;
}

and when you do this

.child {
  @include parent();
}

It will look for mixin to generate css while compiling.

In your first case it throws error because .child needs to compile,
  and in second case it did not because mixin never gets compiled until you
  use it

This is the reason we declare mixin/variables or import mixin/variables file before using it.

Hope I answered your question!


问:
Apache Camel : "direct:start" endpoint - what does it mean?
I'm new to Apache Camel. Can someone explain what "direct:start" means in Camel.
Please see

https://camel.apache.org/components/latest/http-component.html

```<code>from("direct:start")
.to("http://myhost/mypath");
</code>```

Thanks.

答:
It should be fairly easy to explain: exchange is always sent from a source to a destination. For that to happen, you need to create those 02 endpoints: one will consume (yes the start) and the other one will emit.
from("direct:start") means "directly consume the exchange from the "start" endpoint and process it anyhow.
to("direct:start") means "send" the exchange to the "start" endpoint "directly" within the same camel context.
What makes this really ambiguous is that the endpoint itself (i.e: "direct:start") is implicitly created on the fly so when writing your code, you are assuming that there is an endpoint called "direct:start" so you can retrieve exchange from it but you can also send an exchange to it.
Good luck!</p>

Body:
I'm new to Apache Camel. Can someone explain what "direct:start" means in Camel.
Please see

https://camel.apache.org/components/latest/http-component.html

from("direct:start")
.to("http://myhost/mypath");

Thanks.


问:
movie clips on iOS
Hi all
Im looking to play a movie on an iOS device and found MPMoviePlayerController which works very easily. So i have my movie playing but i dont want any of the video controls to be visible/active. i was looking through the settings and found things like

```<code>[moviePlayerController setMovieControlMode:MPMovieControlModeHidden];

[moviePlayerController setMovieControlMode:MPMovieControlStyleNone];
</code>```

and while they do remove the on screen control while the movie is playing they are still visible on initial start of movie.
basically just want to play my movie at start of app without any extra overlays of controls at all ever.
any ideas how to do this?
any help would be appreciated

g

答: AVFoundation has the AVPlayerLayer class (it is ios4 only): http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html#//apple_ref/doc/uid/TP40010188-CH3-SW4</p>

Title: movie clips on iOS

Body:
Hi all
Im looking to play a movie on an iOS device and found MPMoviePlayerController which works very easily. So i have my movie playing but i dont want any of the video controls to be visible/active. i was looking through the settings and found things like

[moviePlayerController setMovieControlMode:MPMovieControlModeHidden];

[moviePlayerController setMovieControlMode:MPMovieControlStyleNone];

and while they do remove the on screen control while the movie is playing they are still visible on initial start of movie.
basically just want to play my movie at start of app without any extra overlays of controls at all ever.
any ideas how to do this?
any help would be appreciated

g


问:
Can't connect to api endpoint from mobile app
I created a .NET Core web api endpoint where I can retrieve some images that I want to display in my mobile app. I tested the endpoint locally by navigating to that route and via postman and both are working fine (showing the proper response). However, when I try to hit the endpoint from mobile side, it doesn't work. I get this cryptic error:

```<code>System.Net.Http.HttpRequestException: Network subsystem is down
</code>```

Here's more of the exception info:

```<code>System.Net.Http.HttpRequestException: Network subsystem is down ---> System.Net.Sockets.SocketException: Network subsystem is down
  at System.Net.Http.ConnectHelper.ConnectAsync (System.String host, System.Int32 port, System.Threading.CancellationToken cancellationToken) [0x000c8] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs:65
</code>```

I'm not sure what I'm doing wrong on the mobile side. I know for postman to get it to show, I had to turn SSL certification setting off. Do I need to do something similar on the mobile side?

Here's how I'm trying to do the call to the endpoint. I'm using refit:

```<code>    public static class FetchMediaService
    {
        public static INevarroApi apiService;
        static string baseUrl = "https://localhost:5001";

        public static async Task<List<Uri>> CallImagesEndpoint()
        {
            apiService = RestService.For<INevarroApi>(baseUrl);
            var images = await apiService.GetImages();
            return images;
        }

    }
</code>```

Where:

```<code>    public interface INevarroApi
    {
        [Get("/images")]
        Task<List<Uri>> GetImages();
    }
</code>```

OnAppearing in my codebehind for one of my views:

```<code>        protected override async void OnAppearing()
        {
            DualScreenLayoutInfo.PropertyChanged += OnFormsWindowPropertyChanged;
            DualScreenInfo.Current.PropertyChanged += OnFormsWindowPropertyChanged;
            var images = await FetchMediaService.CallImagesEndpoint(); //Where the exception is thrown

        }
</code>```

What am I doing wrong above?

I'm testing this on Android 10 (API 29) emulator on Mac OSX and backend code is running locally using Visual Studio for Mac (backend is .NET Core 3.1 web api project).

答:
If you are using IISExpress try to change your debug configuration.

Change to http://localhost:[PORT] to http://127.0.0.1:[PORT]

Then you should be able to access it in android with http://10.0.2.2:[PORT]

For Kestrel

Settings should be done via IHostBuilder in Program.cs as following:

```<code>public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    // This should do it
                    webBuilder.UseUrls("http://127.0.0.1:5000");
                    webBuilder.UseStartup<Startup>();
                });
}
</code>```

Body:
I created a .NET Core web api endpoint where I can retrieve some images that I want to display in my mobile app. I tested the endpoint locally by navigating to that route and via postman and both are working fine (showing the proper response). However, when I try to hit the endpoint from mobile side, it doesn't work. I get this cryptic error:

System.Net.Http.HttpRequestException: Network subsystem is down

Here's more of the exception info:

System.Net.Http.HttpRequestException: Network subsystem is down ---> System.Net.Sockets.SocketException: Network subsystem is down
  at System.Net.Http.ConnectHelper.ConnectAsync (System.String host, System.Int32 port, System.Threading.CancellationToken cancellationToken) [0x000c8] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs:65

I'm not sure what I'm doing wrong on the mobile side. I know for postman to get it to show, I had to turn SSL certification setting off. Do I need to do something similar on the mobile side?

Here's how I'm trying to do the call to the endpoint. I'm using refit:

    public static class FetchMediaService
    {
        public static INevarroApi apiService;
        static string baseUrl = "https://localhost:5001";

        public static async Task<List<Uri>> CallImagesEndpoint()
        {
            apiService = RestService.For<INevarroApi>(baseUrl);
            var images = await apiService.GetImages();
            return images;
        }

    }

Where:

    public interface INevarroApi
    {
        [Get("/images")]
        Task<List<Uri>> GetImages();
    }

OnAppearing in my codebehind for one of my views:

        protected override async void OnAppearing()
        {
            DualScreenLayoutInfo.PropertyChanged += OnFormsWindowPropertyChanged;
            DualScreenInfo.Current.PropertyChanged += OnFormsWindowPropertyChanged;
            var images = await FetchMediaService.CallImagesEndpoint(); //Where the exception is thrown

        }

What am I doing wrong above?

I'm testing this on Android 10 (API 29) emulator on Mac OSX and backend code is running locally using Visual Studio for Mac (backend is .NET Core 3.1 web api project).

Body:
If you are using IISExpress try to change your debug configuration.

Change to http://localhost:[PORT] to http://127.0.0.1:[PORT]

Then you should be able to access it in android with http://10.0.2.2:[PORT]

For Kestrel

Settings should be done via IHostBuilder in Program.cs as following:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    // This should do it
                    webBuilder.UseUrls("http://127.0.0.1:5000");
                    webBuilder.UseStartup<Startup>();
                });
}


问:
Creating Excel file in Windows Forms application using C#
I would like to ask how I can create a new Excel file. I am writing a program and there is one part I can't find out how to do it.

I have a button which should create the new Excel file, so you click on it and it will open the file dialog and then save it somewhere. But I can't find out how to do it, I have tried hundreds of videos and pages but I just can't figure it out.

Could you just show me please how it is done? Thank you

答:
You can try to use Microsoft.Office.Interop.Excel. Before using, please make sure you have Excel installed.

The following are the steps how to use it.

Fisrt, install the package Microsoft.Office.Interop.Excel from Nuget.

Then, refer to the demo code below.

```<code>private void button1_Click(object sender, EventArgs e)
{
    object Nothing = System.Reflection.Missing.Value;
    var app = new Microsoft.Office.Interop.Excel.Application();
    app.Visible = false;
    Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(Nothing);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1];
    worksheet.Name = "WorkSheet";
    // Write data
    worksheet.Cells[1, 1] = "FileName";
    worksheet.Cells[1, 2] = "FindString";
    worksheet.Cells[1, 3] = "ReplaceString";

    // Show save file dialog
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        worksheet.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        workBook.Close(false, Type.Missing, Type.Missing);
        app.Quit();
    }
}
</code>```

Body:
You can try to use Microsoft.Office.Interop.Excel. Before using, please make sure you have Excel installed.

The following are the steps how to use it.

Fisrt, install the package Microsoft.Office.Interop.Excel from Nuget.

Then, refer to the demo code below.

private void button1_Click(object sender, EventArgs e)
{
    object Nothing = System.Reflection.Missing.Value;
    var app = new Microsoft.Office.Interop.Excel.Application();
    app.Visible = false;
    Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(Nothing);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1];
    worksheet.Name = "WorkSheet";
    // Write data
    worksheet.Cells[1, 1] = "FileName";
    worksheet.Cells[1, 2] = "FindString";
    worksheet.Cells[1, 3] = "ReplaceString";

    // Show save file dialog
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        worksheet.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        workBook.Close(false, Type.Missing, Type.Missing);
        app.Quit();
    }
}


问:
Microsoft Azure Speech SDK - Disable Audio Logging
I am trying to use Microsoft Azure Speech to text service. I have a working example using the Python Quickstarts. But I am wondering if Microsoft saves the audio files and if there is anyway to opt-out of it? Any thoughts will be much appreciated.

I did find this property inside of the Speech SDk Azure speech SpeechServiceConnection_EnableAudioLogging - but I am not sure how to use it.

答:
Logging to file is an optional feature for the Speech SDK. During development logging provides additional information and diagnostics from the Speech SDK's core components. It can be enabled by setting the property Speech_LogFilename on a speech configuration object to the location and name of the log file. Logging will be activated globally once a recognizer is created from that configuration and can't be disabled afterwards.

The log file name is specified on a configuration object. Taking the SpeechConfig as an example and assuming that you have created an instance called config:


问:
Unable to "Import Certificate" using API in PowerShell
I have a self signed certificate that I am trying to import to Azure Key Vault Certificate, and I am facing issues. I am not doing it using the Import-AzKeyVaultCertificate command, but using the API.

I was successfully able to create a Key via the API route, but for the life of me, I am not able to Import a certificate. FYI, it also works when I do it over an Azure DevOps pipeline, so I know the Service Principle isn't the issue.

Here's how I am creating the certificate (over PowerShell locally - all examples here will be local and not for Azure DevOps):

```<code>$certroopath = "C:\cert"
$location = "eastus"
$vmName = "arsmpvm"
$certname = "$vmName"
$certpassword = "P@ssw0rd1234"

$cert = New-SelfSignedCertificate -DnsName "$certname" -CertStoreLocation cert:\LocalMachine\My
$pwd = ConvertTo-SecureString -String $certpassword -Force -AsPlainText
$certwithThumb = "cert:\localMachine\my\"+$cert.Thumbprint
$filepath = "$certroopath\$certname.pfx"
Export-PfxCertificate -cert $certwithThumb -FilePath $filepath -Password $pwd
Remove-Item -Path $certwithThumb
</code>```

Here's how I am importing the certificate over a POST operation:

```<code>$pfxcontent = Get-Content 'C:\cert\arsmpvm.pfx' -Encoding Byte
$base64Stringpfxcontent = [System.Convert]::ToBase64String($pfxcontent)

#The payload
$json_new = '{
  "value": "$base64Stringpfxcontent",
  "pwd": "$pwd",
  "policy": {
    "key_props": {
      "exportable": true,
      "kty": "RSA",
      "key_size": 2048,
      "reuse_key": false
    },
    "secret_props": {
      "contentType": "application/x-pem-file"
    }
  }
}'

$header = @{Authorization = "Bearer " + $token.access_token}
Invoke-RestMethod -Method Post -Uri "https://$kvname.vault.azure.net/certificates/$certname/import?api-version=7.0" -Body $json_new -Headers $header -ContentType "application/json"
</code>```

Here's the error I am thrown:
Invoke-RestMethod : {"error":{"code":"BadParameter","message":"The specified PEM X.509 certificate content is in an unexpected format. Please check if certificate is in valid PEM format."}}

Even if I replace the value of $base64Stringpfxcontent (in $json_new) to the content of it, which is like a 3500 char string, I get the same issue. Even if I change $pwd to its hard-coded value, which is P@ssw0rd1234, I am thrown the same error.

Reference taken from: https://learn.microsoft.com/en-us/rest/api/keyvault/importcertificate/importcertificate

Screenshot of the error:

答:
If you use the $base64Stringpfxcontent and $pwd in '', they will be recognized as string instead of variable, and from the doc, the pwd is string, you could not use a SecureString instead of it, you need to pass P@ssw0rd1234 directly to the request body.

Try the script below, it works fine on my side.

```<code>$kvname = "joykeyvault"
$certname = "testcer123"

$pfxcontent = Get-Content 'C:\Users\joyw\Desktop\arsmpvm.pfx' -Encoding Byte
$base64Stringpfxcontent = [System.Convert]::ToBase64String($pfxcontent)

$json_new = @{
  value= $base64Stringpfxcontent
  pwd= "P@ssw0rd1234"
  policy= @{
    secret_props= @{
      contentType= "application/x-pkcs12"
    }
  }
}

$json = $json_new | ConvertTo-Json

$header = @{Authorization = "Bearer " + $token.access_token}
Invoke-RestMethod -Method Post -Uri "https://$kvname.vault.azure.net/certificates/$certname/import?api-version=7.0" -Body $json -Headers $header -ContentType "application/json"
</code>```

Check in the portal:

Body:
I have a self signed certificate that I am trying to import to Azure Key Vault Certificate, and I am facing issues. I am not doing it using the Import-AzKeyVaultCertificate command, but using the API.

I was successfully able to create a Key via the API route, but for the life of me, I am not able to Import a certificate. FYI, it also works when I do it over an Azure DevOps pipeline, so I know the Service Principle isn't the issue.

Here's how I am creating the certificate (over PowerShell locally - all examples here will be local and not for Azure DevOps):

$certroopath = "C:\cert"
$location = "eastus"
$vmName = "arsmpvm"
$certname = "$vmName"
$certpassword = "P@ssw0rd1234"

$cert = New-SelfSignedCertificate -DnsName "$certname" -CertStoreLocation cert:\LocalMachine\My
$pwd = ConvertTo-SecureString -String $certpassword -Force -AsPlainText
$certwithThumb = "cert:\localMachine\my\"+$cert.Thumbprint
$filepath = "$certroopath\$certname.pfx"
Export-PfxCertificate -cert $certwithThumb -FilePath $filepath -Password $pwd
Remove-Item -Path $certwithThumb

Here's how I am importing the certificate over a POST operation:

$pfxcontent = Get-Content 'C:\cert\arsmpvm.pfx' -Encoding Byte
$base64Stringpfxcontent = [System.Convert]::ToBase64String($pfxcontent)

#The payload
$json_new = '{
  "value": "$base64Stringpfxcontent",
  "pwd": "$pwd",
  "policy": {
    "key_props": {
      "exportable": true,
      "kty": "RSA",
      "key_size": 2048,
      "reuse_key": false
    },
    "secret_props": {
      "contentType": "application/x-pem-file"
    }
  }
}'

$header = @{Authorization = "Bearer " + $token.access_token}
Invoke-RestMethod -Method Post -Uri "https://$kvname.vault.azure.net/certificates/$certname/import?api-version=7.0" -Body $json_new -Headers $header -ContentType "application/json"

Here's the error I am thrown:
Invoke-RestMethod : {"error":{"code":"BadParameter","message":"The specified PEM X.509 certificate content is in an unexpected format. Please check if certificate is in valid PEM format."}}

Even if I replace the value of $base64Stringpfxcontent (in $json_new) to the content of it, which is like a 3500 char string, I get the same issue. Even if I change $pwd to its hard-coded value, which is P@ssw0rd1234, I am thrown the same error.

Reference taken from: https://learn.microsoft.com/en-us/rest/api/keyvault/importcertificate/importcertificate

Screenshot of the error:

Body:
If you use the $base64Stringpfxcontent and $pwd in '', they will be recognized as string instead of variable, and from the doc, the pwd is string, you could not use a SecureString instead of it, you need to pass P@ssw0rd1234 directly to the request body.

Try the script below, it works fine on my side.

$kvname = "joykeyvault"
$certname = "testcer123"

$pfxcontent = Get-Content 'C:\Users\joyw\Desktop\arsmpvm.pfx' -Encoding Byte
$base64Stringpfxcontent = [System.Convert]::ToBase64String($pfxcontent)

$json_new = @{
  value= $base64Stringpfxcontent
  pwd= "P@ssw0rd1234"
  policy= @{
    secret_props= @{
      contentType= "application/x-pkcs12"
    }
  }
}

$json = $json_new | ConvertTo-Json

$header = @{Authorization = "Bearer " + $token.access_token}
Invoke-RestMethod -Method Post -Uri "https://$kvname.vault.azure.net/certificates/$certname/import?api-version=7.0" -Body $json -Headers $header -ContentType "application/json"

Check in the portal: