问:
C#: How to embed DLL into resourcefile (no dll copy in program directory)
I have a C# application (project A) that requires X.dll. I have added the project that produces X.dll to A as a reference in visual studio. I have also added the release build of X.dll to a resource file in A as a binary. I have told project A not to copy X.dll to the output directory.

Now I want A.exe to load, say "hey I can't find this file", then look in the resource file and use Assembly.Load(byte[]) get X.dll back. I have the code that re-magicifies the DLL back, however this code never get called.

Currently I have a bone simple project, just trying to get it to work. It compile OK. When I run it, I get a FileNotFoundException on X.dll.

I have:

```<code>[STAThread]
static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
</code>```

But the breakpoint in *CurrentDomain_AssemblyResolve* never gets hit. I get a FileNotFoundException immediately. Surely there is something I a missing?

答:
This question seems to be very similar to what you are trying to achieve, and it worked for the asker.

Merge .dll into C# Assembly?

Are you doing something differently? Specifically, if you're targetting an older version of the .NET Framework, maybe that's a hint for understanding why your application is behaving differently.

Another direction, use a tool such as Fusion Log Viewer to analyze what was going on when you tried to load the assembly. This may give some more hints. If you manage to get log information, posting it in the question may help someone figure it out.

EDIT: Another explanation, following your comment.

Well, now I think I know what the problem is.

In your Main method, you are refering to the type in the other dll. But you are doing it in static code, i.e. you use the type explicitly in the code (as opposed to loading it dynamically by its name).

Why is this a problem? The CLR tries to load your assembly in order to JIT Main itself.

Your FileNotFoundException was thrown while Main was being compiled. Main didn't even start running, and therefore your event handler wasn't registered.

A simple way to check if I'm right is to change the code to something like this:

```<code>static public void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += MyEventHandler;
    MyMain();
}

// The CLR will actually try to load your assembly before even starting the execution
// of this method. It needs the assembly in order to JIT the method because it has to
// know the Thing type.
static public void MyMain()
{
    using(var thing = new Thing())
    {
         // ...
    }
}
</code>```

The important difference is that Main has no dependency on another assembly, so there will be no problem to JIT and run it.

By the time MyMain is being JIT'ed, your event handler is already in place so you can manually load the assembly.

By the way, to avoid another possible similar pitfall, make sure that the class in which Main is defined doesn't have any field with a type from the other assembly, because in this case also, the CLR will try loading the assembly before Main starts, in order to compile it.

Body:
I have a C# application (project A) that requires X.dll. I have added the project that produces X.dll to A as a reference in visual studio. I have also added the release build of X.dll to a resource file in A as a binary. I have told project A not to copy X.dll to the output directory.

Now I want A.exe to load, say "hey I can't find this file", then look in the resource file and use Assembly.Load(byte[]) get X.dll back. I have the code that re-magicifies the DLL back, however this code never get called.

Currently I have a bone simple project, just trying to get it to work. It compile OK. When I run it, I get a FileNotFoundException on X.dll.

I have:

[STAThread]
static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

But the breakpoint in *CurrentDomain_AssemblyResolve* never gets hit. I get a FileNotFoundException immediately. Surely there is something I a missing?

Body:
This question seems to be very similar to what you are trying to achieve, and it worked for the asker.

Merge .dll into C# Assembly?

Are you doing something differently? Specifically, if you're targetting an older version of the .NET Framework, maybe that's a hint for understanding why your application is behaving differently.

Another direction, use a tool such as Fusion Log Viewer to analyze what was going on when you tried to load the assembly. This may give some more hints. If you manage to get log information, posting it in the question may help someone figure it out.

EDIT: Another explanation, following your comment.

Well, now I think I know what the problem is.

In your Main method, you are refering to the type in the other dll. But you are doing it in static code, i.e. you use the type explicitly in the code (as opposed to loading it dynamically by its name).

Why is this a problem? The CLR tries to load your assembly in order to JIT Main itself.

Your FileNotFoundException was thrown while Main was being compiled. Main didn't even start running, and therefore your event handler wasn't registered.

A simple way to check if I'm right is to change the code to something like this:

static public void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += MyEventHandler;
    MyMain();
}

// The CLR will actually try to load your assembly before even starting the execution
// of this method. It needs the assembly in order to JIT the method because it has to
// know the Thing type.
static public void MyMain()
{
    using(var thing = new Thing())
    {
         // ...
    }
}

The important difference is that Main has no dependency on another assembly, so there will be no problem to JIT and run it.

By the time MyMain is being JIT'ed, your event handler is already in place so you can manually load the assembly.

By the way, to avoid another possible similar pitfall, make sure that the class in which Main is defined doesn't have any field with a type from the other assembly, because in this case also, the CLR will try loading the assembly before Main starts, in order to compile it.


来源: stackexchange

问:
How to use _.SortBy() with an array of Objects?
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);```
</div>
</div>
</p>

<h3>EDIT :</h3>

<p>It seems there is a problem with my array, i tried this two function, but i couldn't see any <code>console.log()</code>... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);</code>```

答:
Like others have pointed out, you should be able to do just _.sortBy(myArray, 'date') to sort your array by date.

If all else fails you could always try myArray.sort((a, b) => a.date < b.date)

ContentLicense: CC BY-SA 3.0

Body:
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);

EDIT :

It seems there is a problem with my array, i tried this two function, but i couldn't see any console.log()... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?

// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);


问:
visualize a document field in kibana
I need help to generate a visualization. A term in one of my document indicies, 'temperature', is not in the drop down box of fields to visualize in kibana. What must I change so that 'temperature' shows up as a field in the drop down?

Situation:

ES 5.1

Dynamic Templates

The field is present a portion of documents

The index mapping interprets the field as a 'long'

In Discover, Kibana can filter the documents shows a table of "temperature" and "timestamp." I seek help to visualize the data shown in that table.

A filtered search for the term in the console yields a search result with documents.

```<code>GET /_search
{
    "size" : 10,
    "_source": ["temperature", "timestamp" ],
    "query" : {
        "term" : { "name" : "HomeThermostat" }
    }
}
</code>```

答:
If you wish to visualize let's say a date histogram, where the X-Axis is the timestamp and Y-Axis is a numeric field (in your case: temperature) , then you would have to choose the following settings from the drop down:

For X-Axis

Aggregation = Date Histogram

field = timestamp

Interval = Choose your desired interval

For Y-Axis

Aggregation = Median (median of a single value is the value itself)

field = temperature

If your drop down does not show the field temperature then a possible reason is that temperature is not being recognized as a numeric value.

Go to Management -> Index Patterns -> your index and check whether the field temperature is saved as a number or not.

Title: visualize a document field in kibana

Body:
I need help to generate a visualization. A term in one of my document indicies, 'temperature', is not in the drop down box of fields to visualize in kibana. What must I change so that 'temperature' shows up as a field in the drop down?

Situation:

ES 5.1

Dynamic Templates

The field is present a portion of documents

The index mapping interprets the field as a 'long'

In Discover, Kibana can filter the documents shows a table of "temperature" and "timestamp." I seek help to visualize the data shown in that table.

A filtered search for the term in the console yields a search result with documents.

GET /_search
{
    "size" : 10,
    "_source": ["temperature", "timestamp" ],
    "query" : {
        "term" : { "name" : "HomeThermostat" }
    }
}


问:
How to modify the message in "when and otherwise" function in spark datafarme in scala?
I have dataframe where I'm doing some conditional check with it and creating a column name like valRow and maintaining their status on it. I'm also trying to display message into console, here I'm able to display the message into console successfully. I got stuck with two things

1) I wanted to display the uniqueID of the false result in otherwise function which in highlighted bold letter below, right now in the log it display their name like uniqueID as it is.

```<code>.otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ", childDF("uniqueID").toString))
</code>```

2) I wanted the count of a false result.

```<code>childDF=
+--------+-------------+-------------+---------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |
+--------+-------------+-------------+---------+
|    2568|            F|            3|      S  |
|    2569|            F|            1|      S  |
|    2570|            F|            1|      C  |
|    2571|            F|             |      S  |
|    2572|            F|            3|      S  |
|    2572|            F|            3|      S  |
|    2574|            F|             |      C  |
+--------+-------------+-------------+---------+

Dataframe creates in runtime.
    +--------+-------------+-------------+---------+---------+
    |uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |valRow   |
    +--------+-------------+-------------+---------+---------+
    |    2568|            F|            3|      S  |  true   |
    |    2569|            F|            1|      S  |  true   |
    |    2570|            F|            1|      C  |  true   |
    |    2571|            F|            1|      S  |  false  |
    |    2572|            F|            3|      S  |  true   |
    |    2573|            F|            3|      S  |  true   |
    |    2574|            F|            3|      C  |  false  |
    +--------+-------------+-------------+---------+---------+

def getFlagStatus(flagValue:Boolean,functionName:String,message:String,uniqueID:String) :Boolean =  {

        if(flagValue.equals(false)) {
          ValidationMap.put(ValidationStatus,false)
          logger.mdLog(LogTypeError, functionName, Map(
            Message -> message,
            idNumber->uniqueID
          ))

        }
        false
      }

val newChildDF2 =childD
 .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
              .otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ",childDF("uniqueID").toString)))
              .drop("valRow")
</code>```

My English is not so much good if anybody faces any problem with it please leave your message,any help will be appricated.

答:
Your method looks complicated. You can do it simple as below.

What I would suggest is to use when function as below

```<code>val newChildDF2 =childDF
  .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
    .otherwise(false))
</code>```

You already have the dataframe

```<code>+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|2568    |F            |3            |S       |true  |
|2569    |F            |1            |S       |true  |
|2570    |F            |1            |C       |true  |
|2571    |F            |             |S       |false |
|2572    |F            |3            |S       |true  |
|2572    |F            |3            |S       |true  |
|2574    |F            |             |C       |false |
+--------+-------------+-------------+--------+------+
</code>```

Now you can just use filter function to get the dataframe which has false in valRow as

```<code>val tempDF = newChildDF2.filter($"valRow"===false)
</code>```

dataframe would be

```<code>+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|2571    |F            |             |S       |false |
|2574    |F            |             |C       |false |
+--------+-------------+-------------+--------+------+
</code>```

Now to print the uniqueID in the console you can convert to rdd and use println as

```<code>tempDF.select("uniqueID").rdd.foreach(println)
</code>```

Output would be

```<code>[2571]
[2574]
</code>```

You can even save them to files

You can save rdd to text tiles as

```<code>tempDF.select("uniqueID").rdd.saveAsTextFile("path to output file")
</code>```

You can even save the dataframe as csv too as

```<code>tempDF.write.format("csv").save("path to output file")
</code>```

I hope the answer is helpful

Body:
I have dataframe where I'm doing some conditional check with it and creating a column name like valRow and maintaining their status on it. I'm also trying to display message into console, here I'm able to display the message into console successfully. I got stuck with two things

1) I wanted to display the uniqueID of the false result in otherwise function which in highlighted bold letter below, right now in the log it display their name like uniqueID as it is.

.otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ", childDF("uniqueID").toString))

2) I wanted the count of a false result.

childDF=
+--------+-------------+-------------+---------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |
+--------+-------------+-------------+---------+
|    2568|            F|            3|      S  |
|    2569|            F|            1|      S  |
|    2570|            F|            1|      C  |
|    2571|            F|             |      S  |
|    2572|            F|            3|      S  |
|    2572|            F|            3|      S  |
|    2574|            F|             |      C  |
+--------+-------------+-------------+---------+

Dataframe creates in runtime.
    +--------+-------------+-------------+---------+---------+
    |uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |valRow   |
    +--------+-------------+-------------+---------+---------+
    |    2568|            F|            3|      S  |  true   |
    |    2569|            F|            1|      S  |  true   |
    |    2570|            F|            1|      C  |  true   |
    |    2571|            F|            1|      S  |  false  |
    |    2572|            F|            3|      S  |  true   |
    |    2573|            F|            3|      S  |  true   |
    |    2574|            F|            3|      C  |  false  |
    +--------+-------------+-------------+---------+---------+

def getFlagStatus(flagValue:Boolean,functionName:String,message:String,uniqueID:String) :Boolean =  {

        if(flagValue.equals(false)) {
          ValidationMap.put(ValidationStatus,false)
          logger.mdLog(LogTypeError, functionName, Map(
            Message -> message,
            idNumber->uniqueID
          ))

        }
        false
      }

val newChildDF2 =childD
 .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
              .otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ",childDF("uniqueID").toString)))
              .drop("valRow")

My English is not so much good if anybody faces any problem with it please leave your message,any help will be appricated.

Body:
Your method looks complicated. You can do it simple as below.

What I would suggest is to use when function as below

val newChildDF2 =childDF
  .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
    .otherwise(false))

You already have the dataframe

+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|2568    |F            |3            |S       |true  |
|2569    |F            |1            |S       |true  |
|2570    |F            |1            |C       |true  |
|2571    |F            |             |S       |false |
|2572    |F            |3            |S       |true  |
|2572    |F            |3            |S       |true  |
|2574    |F            |             |C       |false |
+--------+-------------+-------------+--------+------+

Now you can just use filter function to get the dataframe which has false in valRow as

val tempDF = newChildDF2.filter($"valRow"===false)

dataframe would be

+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|2571    |F            |             |S       |false |
|2574    |F            |             |C       |false |
+--------+-------------+-------------+--------+------+

Now to print the uniqueID in the console you can convert to rdd and use println as

tempDF.select("uniqueID").rdd.foreach(println)

Output would be

[2571]
[2574]

You can even save them to files

You can save rdd to text tiles as

tempDF.select("uniqueID").rdd.saveAsTextFile("path to output file")

You can even save the dataframe as csv too as

tempDF.write.format("csv").save("path to output file")

I hope the answer is helpful


问:
Serialize as object using json.net
I want certain properties to be serialized as 'objects' and not strings. E.g.

{"onClickHandler": OnClickHandler,
  "onMouseOut": OnMouseOutHandler}

The class def is like this:

```<code>public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}
</code>```

Currently it comes out as:

handlers: {"onClickHandler": "OnClickHandler",
  "onMouseOut": "OnMouseOutHandler"}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.

Edit:

Taking a cue out of Dave's answer, figured out a way:

first a little bit of scrubbing:

```<code>for (var handler in this.handlers) {
   if(window[this.handlers[handler]])
        this.handlers[handler] = window[this.handlers[handler]];
};
</code>```

and then call jQuery bind normally

```<code> $elem.bind(this.handlers);
</code>```

Accepting Dave's answer as that is closest.

答:
JSON does not support representing functions. JSON consists of arrays of values, and objects (containing variables). Values in JSON can only be strings, numbers, objects or arrays (see the linked page for nice grammar diagram).

What you're after is javascript code, not a JSON object. If you're wanting to emit a reference to a function defined elsewhere, you may have to (shudder) use eval to execute it.

ContentLicense: CC BY-SA 2.5

Title: Serialize as object using json.net

Body:
I want certain properties to be serialized as 'objects' and not strings. E.g.

{"onClickHandler": OnClickHandler,
  "onMouseOut": OnMouseOutHandler}

The class def is like this:

public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}

Currently it comes out as:

handlers: {"onClickHandler": "OnClickHandler",
  "onMouseOut": "OnMouseOutHandler"}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.

Edit:

Taking a cue out of Dave's answer, figured out a way:

first a little bit of scrubbing:

for (var handler in this.handlers) {
   if(window[this.handlers[handler]])
        this.handlers[handler] = window[this.handlers[handler]];
};

and then call jQuery bind normally

 $elem.bind(this.handlers);

Accepting Dave's answer as that is closest.


问:
Django run def index(reuqest) in other def without duplication of code
in my view.py I have a def index(request): and def other(request):

In def other(request): I want to run the exact same code like def index(request): if request.method == 'POST': and else do something different

Copy the code from def index(request): to def other(request): after if request.method == 'POST': works but duplicate code is bad. If I do index(request) after the if statement, def other(request): return nothing.

What is the right method to achieve this?

```<code>@login_required
def other(request):
    if request.method == 'POST':
        # do the same like in def index(request):
        index(request)
    else:
        # do somthing different
        pass
    return render(request, 'search/index.html')

@login_required
def index(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            # do something
            pass
    return render(request, 'search/index.html')
</code>```

答:
You can redirect to index function using redirect function.
let your url.py file contains something like

```<code>url(r'^index/$', 'app.views.index', name='index'),
</code>```

then you can redirect your other view to index like

```<code>from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse

def index(request, *args, **kwargs):
    # your index code
    return HttpResponse(result)

def other(request, *args, **kwargs):
    if request.method == 'POST':
        return redirect(reverse('index', args=args, kwargs=kwargs))
    else:
        # else code for GET, PUT,...
</code>```

if you don't want to redirect, follow the code below

```<code>def index(request, *args, **kwargs):
    # your index code
    return HttpResponse(result)

def other(request, *args, **kwargs):
    if request.method == 'POST':
        return index(request, *args, **kwargs)
    else:
        # else code for GET, PUT,...
</code>```

Body:
in my view.py I have a def index(request): and def other(request):

In def other(request): I want to run the exact same code like def index(request): if request.method == 'POST': and else do something different

Copy the code from def index(request): to def other(request): after if request.method == 'POST': works but duplicate code is bad. If I do index(request) after the if statement, def other(request): return nothing.

What is the right method to achieve this?

@login_required
def other(request):
    if request.method == 'POST':
        # do the same like in def index(request):
        index(request)
    else:
        # do somthing different
        pass
    return render(request, 'search/index.html')

@login_required
def index(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            # do something
            pass
    return render(request, 'search/index.html')

Body:
You can redirect to index function using redirect function.
let your url.py file contains something like

url(r'^index/$', 'app.views.index', name='index'),

then you can redirect your other view to index like

from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse

def index(request, *args, **kwargs):
    # your index code
    return HttpResponse(result)

def other(request, *args, **kwargs):
    if request.method == 'POST':
        return redirect(reverse('index', args=args, kwargs=kwargs))
    else:
        # else code for GET, PUT,...

if you don't want to redirect, follow the code below

def index(request, *args, **kwargs):
    # your index code
    return HttpResponse(result)

def other(request, *args, **kwargs):
    if request.method == 'POST':
        return index(request, *args, **kwargs)
    else:
        # else code for GET, PUT,...


问:
Android Studio AVD not working despite having image on linux
I downloaded a nexus 4 x86-x64 image on my x64 ubuntu i5 laptop. Here are the error lines:

6:22:45 PM EmptyThrowable: /home/youssef/Android/Sdk/tools/mksdcard:
  error while loading shared libraries: libgcc_s.so.1: cannot open
  shared object file: No such file or directory

6:26:22 PM EmptyThrowable: /home/youssef/Android/Sdk/tools/mksdcard:
  error while loading shared libraries: libgcc_s.so.1: cannot open
  shared object file: No such file or directory

答:
I had this error. I tried to find fix and found on askubuntu.com
apt-get install gcc-multilib

This fix solved  this problem for me! Here it is!


问:
How to remove Google Search engine placeholder (Cse)
I am trying to remove the placeholder of the google search engine using jquery addClass and css.

Website url: https://gragop.herokuapp.com

Inspect console: if you add class w3-hide inside gsc-input class it removes it but I don't know how to do it.

CSS

```<code>.w3-hide{display:none!important}
</code>```

Jquery I am trying with no success:

```<code>$(".gsc-input").addClass("gsc-input w3-hide");
</code>```

答:
I m assuming you would want to hide the placeholder, but you would still want it to be a search bar. Adding  w3-hide class to gsc-i-id1, would hide the search bar altogether, leaving it non-typable. Instead you would need to override the background img (Google's Logo) style which is applied.

```<code>$( window ).on( "load", function() {
    $('#gsc-i-id1').removeAttr('placeholder');
    $('#gsc-i-id1').css('background', 'none');

    $('#gsc-i-id1').on('blur', function() {
        $('#gsc-i-id1').css('background', 'none');
    });
});
</code>```

Body:
I am trying to remove the placeholder of the google search engine using jquery addClass and css.

Website url: https://gragop.herokuapp.com

Inspect console: if you add class w3-hide inside gsc-input class it removes it but I don't know how to do it.

CSS

.w3-hide{display:none!important}

Jquery I am trying with no success:

$(".gsc-input").addClass("gsc-input w3-hide");

Body:
I m assuming you would want to hide the placeholder, but you would still want it to be a search bar. Adding  w3-hide class to gsc-i-id1, would hide the search bar altogether, leaving it non-typable. Instead you would need to override the background img (Google's Logo) style which is applied.

$( window ).on( "load", function() {
    $('#gsc-i-id1').removeAttr('placeholder');
    $('#gsc-i-id1').css('background', 'none');

    $('#gsc-i-id1').on('blur', function() {
        $('#gsc-i-id1').css('background', 'none');
    });
});


问:
How can I horizontally and vertically center an  in a
?
I don't want to center a div, I want the contents of a div to be centered.  I would like horizontal and vertical alignment.

Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right.

Grae

I am using IE7

答:
If you know the height and width of your image, position it absolutely, set top/left to 50% and margin-top/left to negative half the height/width of your image.

```<code>#foo {
    position:relative; /* Ensure that this is a positioned parent */
}
#foo img {
    width:240px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-120px;
    margin-top:-100px;
}
</code>```

Live example: http://jsfiddle.net/Zd2pz/

Title: How can I horizontally and vertically center an <img> in a <div>?

Body:
If you know the height and width of your image, position it absolutely, set top/left to 50% and margin-top/left to negative half the height/width of your image.

#foo {
    position:relative; /* Ensure that this is a positioned parent */
}
#foo img {
    width:240px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-120px;
    margin-top:-100px;
}

Live example: http://jsfiddle.net/Zd2pz/


问:
Select next row based on current row field within one query
Let's say the table contains a list of waypoints.

```<code> id | nextID
----+--------
  1 |      2
  2 |      4
  3 |      5
  4 |      1
  5 |      0
</code>```

Based on this table we have two pathes

Circular (1 - 2 - 4 - 1)

Linear (3 - 5)

How do I query the table to get these results:

```<code>      When starting ID = 1
 id | nextID
----+--------
  1 |      2
  2 |      4
  4 |      1

      When starting ID = 3
 id | nextID
----+--------
  3 |      5
  5 |      0
</code>```

答:
What you are trying to achieve is called hierarchical query.

A hierarchical query is operated on Hierarchical Data where
  parent-child relationship is stored in the same table.

Oracle, DB2, Postgres have special syntaxes to query on hierarchical data.

In Oracle if you want to find the all possible path from a start point you have to use START WITH CONNECT BY query.

Query

```<code>SELECT id "start_point", CONNECT_BY_ISCYCLE "Cycle",
  LEVEL, SYS_CONNECT_BY_PATH(id, '/') "Path"
FROM waypoints START WITH id = 1
CONNECT BY NOCYCLE PRIOR next_id = id AND LEVEL <= 4;
</code>```

OUTPUT

MySQL 8 will support this feature in future. But you can implement your own by following this blog post.

Hope this helps you. Ping me if you need further clarifications.

Body:
Let's say the table contains a list of waypoints.

 id | nextID
----+--------
  1 |      2
  2 |      4
  3 |      5
  4 |      1
  5 |      0

Based on this table we have two pathes

Circular (1 - 2 - 4 - 1)

Linear (3 - 5)

How do I query the table to get these results:

      When starting ID = 1
 id | nextID
----+--------
  1 |      2
  2 |      4
  4 |      1

      When starting ID = 3
 id | nextID
----+--------
  3 |      5
  5 |      0

Body:
What you are trying to achieve is called hierarchical query.

A hierarchical query is operated on Hierarchical Data where
  parent-child relationship is stored in the same table.

Oracle, DB2, Postgres have special syntaxes to query on hierarchical data.

In Oracle if you want to find the all possible path from a start point you have to use START WITH CONNECT BY query.

Query

SELECT id "start_point", CONNECT_BY_ISCYCLE "Cycle",
  LEVEL, SYS_CONNECT_BY_PATH(id, '/') "Path"
FROM waypoints START WITH id = 1
CONNECT BY NOCYCLE PRIOR next_id = id AND LEVEL <= 4;

OUTPUT

MySQL 8 will support this feature in future. But you can implement your own by following this blog post.

Hope this helps you. Ping me if you need further clarifications.


问:
How to edit input style by using ng-pattern
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}</code>```

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

```

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

答:
If ng-pattern fails, which means the regex is not fulfilled, a class ng-invalid-pattern is added to the <input> element. This means that you should be able to add the the red border to an input field that isn't passing the ng-pattern with the following CSS:

```<code>input[name=my_input].ng-invalid-pattern{
    border: 2px solid red;
}
</code>```

Body:
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}

.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

Body:
If ng-pattern fails, which means the regex is not fulfilled, a class ng-invalid-pattern is added to the <input> element. This means that you should be able to add the the red border to an input field that isn't passing the ng-pattern with the following CSS:

input[name=my_input].ng-invalid-pattern{
    border: 2px solid red;
}


问:
Why does my observation of tcp connection termination in the web differ from the standard termination of the given sequence diagram?
Let's create the whole process of tcp connection establishment, http request and response and tcp connection  termination.

Content of my files:

/var/www/html/phplearn/send.php

```<code><form action="http://127.0.0.1/phplearn/do.php" method="post">
name: <input type="text" name="userName" size="12"/>
key:  <input type="text" name="PS" size="12"/>
<input type="submit" value="login">
</form>
</code>```

/var/www/html/phplearn/do.php

```<code><?php
$userName = $_POST["userName"];
$PS = $_POST["PS"];
echo "the name is:  ".$userName;
echo "<br>key word is:  ".$PS;
?>
</code>```

Opening tcpdump with this parameters:

sudo tcpdump -i lo host 127.0.0.1 -w /tmp/dataDst.pcap

Sending info with curl

curl -d  "userName=test&PS=test_pass"  127.0.0.1/phplearn/do.php

Opening /tmp/dataDst.pcap  with wireshark

Process1: tcp connection establishment.

From no1 till no3,no problem.

Process2:http request and response.

no5  client send http request from port 38219 to 80 at server

no6  server send tcp signal to client

no7  server send http response to client

Process3:tcp connection termination

The process of tcp connection termination observed from tcpdump totally differ from the diagram on web.

In my observation,

no7   from client on port 38219 to server port 80 ACK

no8   from client on port 38219 to server port 80 FIN

no9   from server port 80 to client on port 38219 FIN

no10  from client on port 38219 to server port 80 ACK

From the diagram, there are two tcp packets from client to server and two tcp packets from  server to client .

From my tcpdump, there are three tcp packets from client to server and only one tcp packet from server to client.

Could you explain the cause for the difference between my observation and the sequence diagram in detail?

答:
In packet 7 the client acknowledges the recievement of the HTTP
Response OK packet from the server. This is not pictured in your TCP-connection-closement sequence diagram as it does not belong to it, but to the normal TCP transmission.

The client then indicates in packet 8 that it wants to close the
connection. Note that although the ACK-flag is set in this packet this does not acknowledge the recievement of any new data as the value of the ACK-number is the same (194). Check this with packet 7. There the value of the ACK-number was also 194. This step corresponds to the first arrow of your diagramm.

In packet 9 the server acknowledges the close indication of the
client and tells the client, that it also wants to terminate his side
of the connection. This step corresponds to the two arrows from the server to the client of your diagramm. Your server packed this in one packet, which is clever as it saves data compared to sending two packets.

In packet 10 the client acknowledges, that the server does also want
to terminate his part of the connection and the connection is
therefore shut down on both sides. This step corresponds to the last arrow of your diagramm.

This follows exactly the sequence diagram you embedded in your question, but that the ACK-packet is send together with the FIN-packet

Note that TCP is bidirektional so the client can send to the server and the server can respond to this via the same connection. But it also allows half-closed connections. This means, although the client indicatet in packet 8, that he does not want to send anymore, he could still recieve data from the server.
But as the server does not want to send anymore data he also indicates this by his FIN packet in packet 9. I'm telling you this as you might wonder, why the Server also needs to send a FIN-packet to the client.

A helpful and more detailed graphic to the state model of a TCP-connection can be found in Tanenbaum p. 532 or it is also depicted on this lecture slides of ETH Zurich.

Body:
Let's create the whole process of tcp connection establishment, http request and response and tcp connection  termination.

Content of my files:

/var/www/html/phplearn/send.php

<form action="http://127.0.0.1/phplearn/do.php" method="post">
name: <input type="text" name="userName" size="12"/>
key:  <input type="text" name="PS" size="12"/>
<input type="submit" value="login">
</form>

/var/www/html/phplearn/do.php

<?php
$userName = $_POST["userName"];
$PS = $_POST["PS"];
echo "the name is:  ".$userName;
echo "
key word is:  ".$PS;
?>

Opening tcpdump with this parameters:

sudo tcpdump -i lo host 127.0.0.1 -w /tmp/dataDst.pcap

Sending info with curl

curl -d  "userName=test&PS=test_pass"  127.0.0.1/phplearn/do.php

Opening /tmp/dataDst.pcap  with wireshark

Process1: tcp connection establishment.

From no1 till no3,no problem.

Process2:http request and response.

no5  client send http request from port 38219 to 80 at server

no6  server send tcp signal to client

no7  server send http response to client

Process3:tcp connection termination

The process of tcp connection termination observed from tcpdump totally differ from the diagram on web.

In my observation,

no7   from client on port 38219 to server port 80 ACK

no8   from client on port 38219 to server port 80 FIN

no9   from server port 80 to client on port 38219 FIN

no10  from client on port 38219 to server port 80 ACK

From the diagram, there are two tcp packets from client to server and two tcp packets from  server to client .

From my tcpdump, there are three tcp packets from client to server and only one tcp packet from server to client.

Could you explain the cause for the difference between my observation and the sequence diagram in detail?


问:
Movie DB - storage of Actors / actress / Tags?
Creating a movie db and I dont like the idea of giving each actor/actress and also each tag its own row as if there are 10 million moives total, each has a cast of atleast 20-30 people we will have 200-300 million rows in the table.

And it gets more complex with tags which can be unlimited per movie. So how to best store these 3 items? Ideally these can be modeled as a Many to Many but still it will have hundreds of millions of rows. Any better suggestions on storing these? I am using MySQL.

I would dump it all in a textfile but I need to link actors between movies and do some analytics also and allow users to rate actors find movies by tag, etc so need to use a DB.

答:
10 million movies seems pretty ambitious. IMDb's current statistics show that they have less than 1.8M titles and around 3.9M people.

Having said that, I see no problem with creating a table of titles, a table of actors, and a junction table to resolve the many-to-many relationship between the two. The same holds true for tags.


问:
Exposing a web site through web services
I know what I am asking is somehow weird. There is a web application (which we don't have access to its source code), and we want to expose a few of its features as web services.

I was thinking to use something like Selenium WebDriver, so I simulate web clicks on the application according to the web service request.

I want to know whether this is a better solution or pattern to do this.

I shall mention that the application is written using Java, Spring MVC (it is not SPA) and Spring Security. And there is a CAS server providing SSO.

答:
Selenium isn't a best way to consume webservices. Selenium is preferably an automation tool largely used for testing the applications.
Assuming the services are already developed, the first thing we need to do is authenticate user request.
This can be done by adding a HttpHeader with key as "Authorization" and value as "Basic "+ Base64Encode(username+":"+password)

If the user is valid (Users login credentials match with credentials in server) then generate a unique token, store the token in server by mapping with the user Id and
set the same token in the response header or create a cookie containing token.
By doing this we can avoid validating credentials for the following requests form the same user by just looking for the token in the response header or cookie.
If the services are designed to chcek login every time the "Authorization" header needs to be set in request every time when the request is made.


问:
When to call SetProcessWorkingSetSize? (Convincing the memory manager to release the memory)
In a previous post ( My program never releases the memory back. Why? ) I show that FastMM can cache (read as hold for itself) pretty large amounts of memory. If your application just loaded a large data set in RAM, after releasing the data, you will see that impressive amounts of RAM are not released back to the memory pool.

I looked around and it seems that calling the SetProcessWorkingSetSize API function will "flush" the cache to disk. However, I cannot decide when to call this function. I wanted to call it at the end of the OnClick event on the button that is performing the RAM intensive operation. However, some people are saying that this may cause AV.

If anybody used this function successfully, please let me (us) know.

Many thanks.

Edit:

1. After releasing the data set, the program still takes large amounts of RAM. After calling SetProcessWorkingSetSize the size returns to few MB. Some argue that nothing was released back. I agree. But the memory foot print is now small AND it is NOT increasing back after using the program normally (for example when performing normal operation that does not involves loading large data sets). Unfortunately, there is no way to demonstrate that the memory swapped to disk is ever loaded back into memory, but I think it is not.
2. I have already demonstrated (I hope) this is not a memory leak:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答: I agree with Lars Truijens 100%, if you don't than you can check the FasttMM memory usage via FasttMM calls GetMemoryManagerState and GetMemoryManagerUsageSummary before and after calling API SetProcessWorkingSetSize.


问:
Realm write transaction failing, despite being in transaction
I have this code, which should append messages with a new message:

```<code>func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}
</code>```

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

答:
The trouble was I was using a plain Realm object with no special configuration. Since I am using Realm Mobile Platform, I needed to create a Realm object with the same config each time I want to write to that DB:

```<code>let configuration = Realm.Configuration(
                syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://127.0.0.1:9080/~/speciail")!)
            )
self.realm = try! Realm(configuration: configuration)

//now do the write transaction!
</code>```

It took a bit of refactoring, but I have it now. My thanks to those of you who took the time to help me.

Body:
I have this code, which should append messages with a new message:

func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

Body:
The trouble was I was using a plain Realm object with no special configuration. Since I am using Realm Mobile Platform, I needed to create a Realm object with the same config each time I want to write to that DB:

let configuration = Realm.Configuration(
                syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://127.0.0.1:9080/~/speciail")!)
            )
self.realm = try! Realm(configuration: configuration)

//now do the write transaction!

It took a bit of refactoring, but I have it now. My thanks to those of you who took the time to help me.


问:
Building and Installing cx_Oracle with conda skeleton/ conda build not working
I have installed the package cx_Oracle, using conda skeleton command on my Windows 64bits machine, within Anaconda python

conda skeleton pypi cx_Oracle

af5f7daad67d6820670d582dfc045/cx_Oracle-6.0rc1.tar.gz (200 KB) for cx_Oracle.

Downloading cx_Oracle

Using cached download

Unpacking cx_Oracle...

done

when I am checking the file/ directory  is finally set, I see it there

```<code>    File "C:\Anaconda3_version4.3\lib\site-packages\conda_build\skeletons\pypi.py", line 339, in skeletonize
    raise RuntimeError("directory already exists: %s" % dir_path)
RuntimeError: directory already exists: .\cx_oracle
</code>```

but when I am calling it, it cannot be  found

```<code>  import cx_oracle
Traceback (most recent call last):

  File "<ipython-input-3-fa7af752f8a0>", line 1, in <module>
    import cx_oracle

ModuleNotFoundError: No module named 'cx_oracle'
</code>```

The directory of cx_Oracle contains the files,
and know I need to build the package with conda build:

conda build cx_Oracle

Just so, it still  doesn't work

Provides me the following error:

```<code>Anaconda3_version4.3\conda-bld\cx_oracle_1499164
353203\_b_env\Library\include /Tcsrc/cx_Oracle.c /Fobuild\temp.win-amd64-3.6\Rel
ease\src/cx_Oracle.obj -DBUILD_VERSION=6.0rc1
error: command 'cl.exe' failed: No such file or directory
</code>```

I do not understand what else is needed to finally install the package

Thanks for reading.

答:
Finally, I got a hint about this error thanks to the comments from @darthbith,

Building cx_Oracle requires you to have working C(++) compiler since cx_Oracle is written in C, not in Python even it's a Python module.

Body:
I have installed the package cx_Oracle, using conda skeleton command on my Windows 64bits machine, within Anaconda python

conda skeleton pypi cx_Oracle

af5f7daad67d6820670d582dfc045/cx_Oracle-6.0rc1.tar.gz (200 KB) for cx_Oracle.

Downloading cx_Oracle

Using cached download

Unpacking cx_Oracle...

done

when I am checking the file/ directory  is finally set, I see it there

    File "C:\Anaconda3_version4.3\lib\site-packages\conda_build\skeletons\pypi.py", line 339, in skeletonize
    raise RuntimeError("directory already exists: %s" % dir_path)
RuntimeError: directory already exists: .\cx_oracle

but when I am calling it, it cannot be  found

  import cx_oracle
Traceback (most recent call last):

  File "<ipython-input-3-fa7af752f8a0>", line 1, in <module>
    import cx_oracle

ModuleNotFoundError: No module named 'cx_oracle'

The directory of cx_Oracle contains the files,
and know I need to build the package with conda build:

conda build cx_Oracle

Just so, it still  doesn't work

Provides me the following error:

Anaconda3_version4.3\conda-bld\cx_oracle_1499164
353203\_b_env\Library\include /Tcsrc/cx_Oracle.c /Fobuild\temp.win-amd64-3.6\Rel
ease\src/cx_Oracle.obj -DBUILD_VERSION=6.0rc1
error: command 'cl.exe' failed: No such file or directory

I do not understand what else is needed to finally install the package

Thanks for reading.


问:
Why doesn't google sheets show the full array returned by my function?
I've been writing a custom function that returns a 365 element array. The problem is that it just doesn't seem to return the values I'd expect. Some of the initial values display, but not others.

The weird thing is that the log files do show the data that I would expect. It's just when I try to output the data to Google sheets that it goes missing.

Which is why I'm wondering if there is some sort of limit on the data that I can return.

A bit more background

My google sheet enables staff to record holiday that they have booked. They enter their holiday in the format Name, StartDate, EndDate.

But I'd also like to show the data in something more like a Gantt chart, with days of the year along the top row and members of staff along the left hand column.

So my function loops through each entry in the holiday table until it finds a matching staff name, then it puts an X in the appropriate days. I call the function again for each staff name until I've fully populated the whole array.

```<code>function myFunction(LeaveDates, StaffName, YearStart) {

  var ResultsArray = new Array(365);
  var MillisecondsInDay = 24*60*60*1000;

  for (var i = 0; i < LeaveDates.length; i++) {
    if (LeaveDates[i][0] == StaffName) {
      for (var j = ((LeaveDates[i][2] - YearStart) / MillisecondsInDay); j < (((LeaveDates[i][3] - YearStart) / MillisecondsInDay)+1); j++) {
       ResultsArray[j] = LeaveDates[i][6];
      }
      Logger.log("Start Date: " + LeaveDates[i][2] + " - End Date: " + LeaveDates[i][3] + " - Type: " +  ResultsArray[j-1]);
    }
  }

  return ResultsArray;
}
</code>```

LeaveDates is the range of cells that contains the holiday data

StaffName is the name of the current member of staff e.g. John Smith

YearStart is the first day of the current year i.e. 01/01/2017

When I call this function from a cell it only populates some of the cells that I'd expect it to. The exact number changes depending on the input data. Sometimes it returns just the first two instances of holiday. Other times it returns the first five. But it's not like it only returns holiday up to a certain date

But the logs show that the data in the array has been populated correctly. So I'm very confused.

Any help is much appreciated!

答:
Thank you everyone who took some time to read my question.

I realised after a good night's sleep that the problem was with my index to the array (j). j was the number for the day of the year (i.e. a number between 0 and 364)

I calculated it by dividing the date by the number of milliseconds in the day. Which works well until the clocks change for daylight savings (British Summer Time). So any entries after the end of March returned array indices that were not whole numbers.

I added Math.round() to my calculation to ensure that I get an integer result and now it works as intended.

I'm a bit surprised that I didn't get any errors when I tried to assign values to non-integer places in the array. Does anyone know of a reason why that is? Are there occasions when you should be able to use non-integer values?

Body:
I've been writing a custom function that returns a 365 element array. The problem is that it just doesn't seem to return the values I'd expect. Some of the initial values display, but not others.

The weird thing is that the log files do show the data that I would expect. It's just when I try to output the data to Google sheets that it goes missing.

Which is why I'm wondering if there is some sort of limit on the data that I can return.

A bit more background

My google sheet enables staff to record holiday that they have booked. They enter their holiday in the format Name, StartDate, EndDate.

But I'd also like to show the data in something more like a Gantt chart, with days of the year along the top row and members of staff along the left hand column.

So my function loops through each entry in the holiday table until it finds a matching staff name, then it puts an X in the appropriate days. I call the function again for each staff name until I've fully populated the whole array.

function myFunction(LeaveDates, StaffName, YearStart) {

  var ResultsArray = new Array(365);
  var MillisecondsInDay = 24*60*60*1000;

  for (var i = 0; i < LeaveDates.length; i++) {
    if (LeaveDates[i][0] == StaffName) {
      for (var j = ((LeaveDates[i][2] - YearStart) / MillisecondsInDay); j < (((LeaveDates[i][3] - YearStart) / MillisecondsInDay)+1); j++) {
       ResultsArray[j] = LeaveDates[i][6];
      }
      Logger.log("Start Date: " + LeaveDates[i][2] + " - End Date: " + LeaveDates[i][3] + " - Type: " +  ResultsArray[j-1]);
    }
  }

  return ResultsArray;
}

LeaveDates is the range of cells that contains the holiday data

StaffName is the name of the current member of staff e.g. John Smith

YearStart is the first day of the current year i.e. 01/01/2017

When I call this function from a cell it only populates some of the cells that I'd expect it to. The exact number changes depending on the input data. Sometimes it returns just the first two instances of holiday. Other times it returns the first five. But it's not like it only returns holiday up to a certain date

But the logs show that the data in the array has been populated correctly. So I'm very confused.

Any help is much appreciated!


问:
Kotlin for assertThat(foo, instanceOf(Bar.class))
How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?

Seems that it does not like the .class

I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible

答:
Bar::class returns instance of KClass, which is Kotlin equivalent of Java's Class.

instanceOf method requires Class instance, not KClass, so you have to convert it using Bar::class.java.

So your assertion should be like:

```<code>assertThat(foo, instanceOf(Bar::class.java))
</code>```

More info about Java interop you can find here.

Also you can have a look at Hamkrest library which may add more fluency to your assertions:

```<code>assert.that(foo, isA<Bar>())
</code>```

Body:
Bar::class returns instance of KClass, which is Kotlin equivalent of Java's Class.

instanceOf method requires Class instance, not KClass, so you have to convert it using Bar::class.java.

So your assertion should be like:

assertThat(foo, instanceOf(Bar::class.java))

More info about Java interop you can find here.

Also you can have a look at Hamkrest library which may add more fluency to your assertions:

assert.that(foo, isA<Bar>())


问:
How to fix [Errno13] permission denied when trying to read excel file?
I tried the following code to be able to read an excel file from my personal computer.

```<code>import xlrd

book = xlrd.open_workbook('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx')
</code>```

But I am getting the error 'Permission denied'. I am using windows and if I look at the properties of the directory and look at the 'Security' tab I have three groups/users and all three have permissions for all the authorities, except for the last option which is called 'special authorities' (as far as I know I do not need this authority to read the excel file in Python).

I have no idea how to fix this error. Furthermore, I do not have the Excel file open on my computer when running the simulation.

I really hope someone can help me to fix this error.

答:
```<code>book = xlrd.open_workbook('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx')
</code>```

You cannot give path like this to xlrd. path need to be single string.

If you insist you can use os module

```<code>import os
book = xlrd.open_workbook(os.path.join('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx'))
</code>```

[Errno13] permission denied in your case is happening because you want to read folder like a file which is not allowed.

Body:
I tried the following code to be able to read an excel file from my personal computer.

import xlrd

book = xlrd.open_workbook('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx')

But I am getting the error 'Permission denied'. I am using windows and if I look at the properties of the directory and look at the 'Security' tab I have three groups/users and all three have permissions for all the authorities, except for the last option which is called 'special authorities' (as far as I know I do not need this authority to read the excel file in Python).

I have no idea how to fix this error. Furthermore, I do not have the Excel file open on my computer when running the simulation.

I really hope someone can help me to fix this error.

Body:
book = xlrd.open_workbook('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx')

You cannot give path like this to xlrd. path need to be single string.

If you insist you can use os module

import os
book = xlrd.open_workbook(os.path.join('C:\\Users\eline\Documents\***\***\Python', 'Example 1.xlsx'))

[Errno13] permission denied in your case is happening because you want to read folder like a file which is not allowed.


问:
Limit this PHP foreach statement to just 5 loops
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it. </p>

```<code> <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
</code>```

答:
You can use array_slice() first to get a new array with no more than 5 elements.

```<code>$locations = array_slice($locations, 0, 5);
</code>```

Then everything unchanged.

Body:
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>

    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>

    <?php if($param->count): ?>

<?php echo intval($location["count"]) ?>

    <?php endif; ?>

<?php endforeach; ?>

Body:
You can use array_slice() first to get a new array with no more than 5 elements.

$locations = array_slice($locations, 0, 5);

Then everything unchanged.


问:
Remove element from vector of maps
I have a vector of maps:

```<code>typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;
</code>```

How can I remove some elements from rows?

The following code does not work.

```<code>struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());
</code>```

I got the following error.

```<code>error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'
</code>```

Thanks.

答:
1) First off: please provide a single compilable example.

Your code posted above is problematic as rVec and rowsVector have been interchanged (you would have seen that yourself if you had posted real code).

2) You are using the wrong remove. It should be remove_if

3) It is normal for the functor to be const

4) The operator() should get object of type aMap (as that is what is in your vector) not a reference back to the vector.

5) Don't be lazy add std:: in-front of objects in the standard namespace.

rather than using using namespace std;

```<code>#include <map>
#include <vector>
#include <string>
#include <algorithm>

typedef std::map<std::string, std::string> aMap;
typedef std::vector<aMap>        rVec;

rVec rows;

struct remove_it
{
                 // Corrected type here
  bool operator() (aMap const& row) const  // const here
  {
    // Validation code here!
    return true;
  }
};

int main()
{
                                 // _if herer
    rVec::iterator it = std::remove_if(rows.begin(), rows.end(), remove_it());
    rows.erase(it, rows.end());
}
</code>```

Title: Remove element from vector of maps

Body:
I have a vector of maps:

typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;

How can I remove some elements from rows?

The following code does not work.

struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());

I got the following error.

error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'

Thanks.

Body:
1) First off: please provide a single compilable example.

Your code posted above is problematic as rVec and rowsVector have been interchanged (you would have seen that yourself if you had posted real code).

2) You are using the wrong remove. It should be remove_if

3) It is normal for the functor to be const

4) The operator() should get object of type aMap (as that is what is in your vector) not a reference back to the vector.

5) Don't be lazy add std:: in-front of objects in the standard namespace.

rather than using using namespace std;

#include <map>
#include <vector>
#include <string>
#include <algorithm>

typedef std::map<std::string, std::string> aMap;
typedef std::vector<aMap>        rVec;

rVec rows;

struct remove_it
{
                 // Corrected type here
  bool operator() (aMap const& row) const  // const here
  {
    // Validation code here!
    return true;
  }
};

int main()
{
                                 // _if herer
    rVec::iterator it = std::remove_if(rows.begin(), rows.end(), remove_it());
    rows.erase(it, rows.end());
}


问:
C# Error: OutOfMemoryException - Reading a large text file and replacing from dictionary
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

```<code>// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }
</code>```

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

```<code>            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();
</code>```

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

答:
If you have very large files you should try  MemoryMappedFile which is designed for this purpose(files > 1GB) and enables to read "windows" of a file into memory. But it's not easy to use.

A simple optimization would be to read and replace line by line

```<code>int lineNumber = 0;
var _replacementInfo = new Dictionary<int, List<string>>();

using (StreamReader sr = new StreamReader(logF))
{
    using (StreamWriter sw = new StreamWriter(logF_Temp))
    {
        while (!sr.EndOfStream)
        {
            string line = sr.ReadLine();
            lineNumber++;
            foreach (var kv in replacements)
            {
                bool contains = line.Contains(kv.Key);
                if (contains)
                {
                    List<string> lineReplaceList;
                    if (!_replacementInfo.TryGetValue(lineNumber, out lineReplaceList))
                        lineReplaceList = new List<string>();
                    lineReplaceList.Add(kv.Key);
                    _replacementInfo[lineNumber] = lineReplaceList;

                    line = line.Replace(kv.Key, kv.Value);
                }
            }
            sw.WriteLine(line);
        }
    }
}
</code>```

At the end you can use File.Copy(logF_Temp, logF, true); if you want to overwite the old.

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

Body:
If you have very large files you should try  MemoryMappedFile which is designed for this purpose(files > 1GB) and enables to read "windows" of a file into memory. But it's not easy to use.

A simple optimization would be to read and replace line by line

int lineNumber = 0;
var _replacementInfo = new Dictionary<int, List<string>>();

using (StreamReader sr = new StreamReader(logF))
{
    using (StreamWriter sw = new StreamWriter(logF_Temp))
    {
        while (!sr.EndOfStream)
        {
            string line = sr.ReadLine();
            lineNumber++;
            foreach (var kv in replacements)
            {
                bool contains = line.Contains(kv.Key);
                if (contains)
                {
                    List<string> lineReplaceList;
                    if (!_replacementInfo.TryGetValue(lineNumber, out lineReplaceList))
                        lineReplaceList = new List<string>();
                    lineReplaceList.Add(kv.Key);
                    _replacementInfo[lineNumber] = lineReplaceList;

                    line = line.Replace(kv.Key, kv.Value);
                }
            }
            sw.WriteLine(line);
        }
    }
}

At the end you can use File.Copy(logF_Temp, logF, true); if you want to overwite the old.


问:
How to handle onBackPressed in KeyguardManager
I want to perform some action on click of back button of KeyguardManager.exitKeyguardSecurely() method. My purpose is to finish the activity from which the KeyguardManager security Activity is Opened .

In the Home Activity of my app I have opened security pattern screen using below code.

```<code> KeyguardManager keyguardManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
        Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
        keyguardManager.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
            @Override
            public void onKeyguardExitResult(boolean success) {
                if (success) {

                }
            }
        });
        startActivity(intent);
</code>```

And I want to finish the Home Activity on click of the back button of the phone,How can I achieve it ?
Thank you

答:
You could use the following </p>

<p>@Override</p>

```<code>public void onBackPressed()
{
    // put action here
    super.onBackPressed();  // optional depending on your needs
    // you could add 'finish()' to finish your current activity
}
</code>```

Body:
I want to perform some action on click of back button of KeyguardManager.exitKeyguardSecurely() method. My purpose is to finish the activity from which the KeyguardManager security Activity is Opened .

In the Home Activity of my app I have opened security pattern screen using below code.

 KeyguardManager keyguardManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
        Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
        keyguardManager.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
            @Override
            public void onKeyguardExitResult(boolean success) {
                if (success) {

                }
            }
        });
        startActivity(intent);

And I want to finish the Home Activity on click of the back button of the phone,How can I achieve it ?
Thank you

Body:
You could use the following

@Override

public void onBackPressed()
{
    // put action here
    super.onBackPressed();  // optional depending on your needs
    // you could add 'finish()' to finish your current activity
}


问:
Kendo UI kendo is undefined
I'm just starting to use Kendo UI and I'm having trouble getting one of the demos to work. I get  Uncaught TypeError: Cannot read property 'observable' of undefined on line 43. How can I fix this? Any help is appreciated. </p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="./styles/kendo.common.min.css" rel="stylesheet" />
    <script src="./js/jquery.min.js"></script>
    <script src="./js/angular.min.js"></script>
    <script src="./js/kendo.core.min.js"></script>
</head>
<body>
    <div id="example">
    <div class="demo-section k-header">
        <div class="box-col" style="width: 300px">
            <h4>Change the value</h4>
            <input data-role="slider"
                   data-min="0"
                   data-max="50"
                   data-small-step="5"
                   data-large-step="10"
                   data-bind="visible: isVisible,
                              enabled: isEnabled,
                              value: selectedNumber,
                              events: { change: onChange }"
                   style="width: 180px">
        </div>
        <div class="box-col console-section">
            <h4>Console</h4>
            <div class="console"></div>
        </div>
    </div>
    <div class="box">
        <div class="box-col" style="width: 300px">
            <h4>Configuration</h4>
            <div>
                <label><input type="checkbox" data-bind="checked: isEnabled">Enable</label>
            </div>
            <div>
                <label><input type="checkbox" data-bind="checked: isVisible">Visible</label>
            </div>
        </div>
    </div>
<script>
    var viewModel = kendo.observable({
        selectedNumber: 0,
        isEnabled: true,
        isVisible: true,
        onChange: function() {
            kendoConsole.log("event :: change (" + this.get("selectedNumber") + ")");
        }
    });
    kendo.bind($("#example"), viewModel);
</script>
</div>

</body>
</html>
</code>```

答:
You can try fo this:
check your "jquery.min.js" version compatibility with kendo version. this might be the issue in you case.

most of the time you can use jquery 1.8 version with kendo 2015.x.x version

Title: Kendo UI kendo is undefined

Body:
I'm just starting to use Kendo UI and I'm having trouble getting one of the demos to work. I get  Uncaught TypeError: Cannot read property 'observable' of undefined on line 43. How can I fix this? Any help is appreciated.

<!DOCTYPE html>

    <title></title>
    <link href="./styles/kendo.common.min.css" rel="stylesheet" />

Change the value

            <input data-role="slider"
                   data-min="0"
                   data-max="50"
                   data-small-step="5"
                   data-large-step="10"
                   data-bind="visible: isVisible,
                              enabled: isEnabled,
                              value: selectedNumber,
                              events: { change: onChange }"
                   style="width: 180px">

Console

Configuration

                <input type="checkbox" data-bind="checked: isEnabled">Enable

                <input type="checkbox" data-bind="checked: isVisible">Visible


问:
Find all files without broken links
I need to find all source files including linked files, but avoid broken links.

I have a c/c++ source code area, with some files linked to files to other directories and I want to index them using cscope. When there are broken links, cscope gives an error:

```<code>cscope: cannot find file /...file....
</code>```

What I need actually is to create a clean cscope.files without broken linked files.

What I'm currently doing is:

```<code>find $code_path -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' >> cscope.files
</code>```

答:
find with little help from file to get the filetype, and print-ing the files that do not have broken symbolic link target:

```<code>find "$code_path" -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' \
    -exec sh -c 'file "$1" | grep -qv broken' _ {} \; -print
</code>```

This has the caveat of processing one file at a time.

if you do not have any filename with whitespace(s) or any control character(s), you can leverage find ... -exec {} + capability of dealing with maximum number of file(s) in one go without triggering ARG_MAX, and getting the desired filenames with awk:

```<code>find "$code_path" -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' \
    -exec file {} + | awk '!/broken/ {print $1}'
</code>```

Side note: Quote your variable expansions to prevent word splitting and pathname expansion from taking place on the expansion.

Title: Find all files without broken links

Body:
I need to find all source files including linked files, but avoid broken links.

I have a c/c++ source code area, with some files linked to files to other directories and I want to index them using cscope. When there are broken links, cscope gives an error:

cscope: cannot find file /...file....

What I need actually is to create a clean cscope.files without broken linked files.

What I'm currently doing is:

find $code_path -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' >> cscope.files

Body:
find with little help from file to get the filetype, and print-ing the files that do not have broken symbolic link target:

find "$code_path" -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' \
    -exec sh -c 'file "$1" | grep -qv broken' _ {} \; -print

This has the caveat of processing one file at a time.

if you do not have any filename with whitespace(s) or any control character(s), you can leverage find ... -exec {} + capability of dealing with maximum number of file(s) in one go without triggering ARG_MAX, and getting the desired filenames with awk:

find "$code_path" -type f -name '*.h' -o -name '*.c' -o -name '*.cpp' \
    -exec file {} + | awk '!/broken/ {print $1}'

Side note: Quote your variable expansions to prevent word splitting and pathname expansion from taking place on the expansion.


问:
Input accessory view from one view controller incorrectly appears in another view controller
I've encountered a bug in my app where the UIToolbar in first view controller appears in the third view controller despite me overriding the input accessory view.

First view controller:

```<code>class FirstViewController: BaseViewController {

    @IBOutlet weak var toolbar: UIToolbar!

    override var inputAccessoryView: UIView? {
        return toolbar
    }

    ...
</code>```

Second view controller:

```<code>class SecondViewController: BaseViewController {

    override var inputAccessoryView: UIView? {
        return nil
    }

    ...
</code>```

Third view controller:

```<code>class ThirdViewController: BaseViewController {

    override var inputAccessoryView: UIView? {
        return nil
    }

    ...
</code>```

I am unsure of what is causing the toolbar to appear in the second view controller. These view controllers are not embedded in a UINavigationController so I don't understand how it can carry over to another screen.

答:
So this was a difficult problem to solve but I eventually figured out the problem.

So the issue is the method canBecomeFirstResponder. If we design our storyboard as follows:

FirstViewController -(show)-> SecondViewController -(show )-> ThirdViewController

When we segue to ThirdViewController, iOS asks FirstViewController if it can become first responder. If canBecomeFirstResponder returns true, then the input accessory view of FirstViewController will appear in ThirdViewController.

The solution is a tad hacky, unfortunately, but it's the only solution I can think of at the moment.

Base view controller:

```<code>class BaseViewController: UIViewController {

    var shouldBecomeFirstResponder: Bool = false

    override var canBecomeFirstResponder: Bool {
        return shouldBecomeFirstResponder
    }

    ...
}
</code>```

First view controller:

```<code>class FirstViewController: BaseViewController {

    @IBOutlet weak var toolbar: UIToolbar!

    override func viewDidLoad() {
        super.viewDidLoad()
        shouldBecomeFirstResponder = true
    }

    override var inputAccessoryView: UIView? {
        return toolbar
    }

    @IBAction didTap() {
        shouldBecomeFirstResponder = false
        performSegue(withIdentifier: "showSecond", sender: self)
    }
    ...
}
</code>```

Second view controller:

```<code>class SecondViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        shouldBecomeFirstResponder = false
    }
    ...

    @IBAction didTap() {
        performSegue(withIdentifier: "showThird", sender: self)
    }

    ...
}
</code>```

Third view controller:

```<code>class ThirdViewController: BaseViewController {

    ...
}
</code>```

Body:
I've encountered a bug in my app where the UIToolbar in first view controller appears in the third view controller despite me overriding the input accessory view.

First view controller:

class FirstViewController: BaseViewController {

    @IBOutlet weak var toolbar: UIToolbar!

    override var inputAccessoryView: UIView? {
        return toolbar
    }

    ...

Second view controller:

class SecondViewController: BaseViewController {

    override var inputAccessoryView: UIView? {
        return nil
    }

    ...

Third view controller:

class ThirdViewController: BaseViewController {

    override var inputAccessoryView: UIView? {
        return nil
    }

    ...

I am unsure of what is causing the toolbar to appear in the second view controller. These view controllers are not embedded in a UINavigationController so I don't understand how it can carry over to another screen.

Body:
So this was a difficult problem to solve but I eventually figured out the problem.

So the issue is the method canBecomeFirstResponder. If we design our storyboard as follows:

FirstViewController -(show)-> SecondViewController -(show )-> ThirdViewController

When we segue to ThirdViewController, iOS asks FirstViewController if it can become first responder. If canBecomeFirstResponder returns true, then the input accessory view of FirstViewController will appear in ThirdViewController.

The solution is a tad hacky, unfortunately, but it's the only solution I can think of at the moment.

Base view controller:

class BaseViewController: UIViewController {

    var shouldBecomeFirstResponder: Bool = false

    override var canBecomeFirstResponder: Bool {
        return shouldBecomeFirstResponder
    }

    ...
}

First view controller:

class FirstViewController: BaseViewController {

    @IBOutlet weak var toolbar: UIToolbar!

    override func viewDidLoad() {
        super.viewDidLoad()
        shouldBecomeFirstResponder = true
    }

    override var inputAccessoryView: UIView? {
        return toolbar
    }

    @IBAction didTap() {
        shouldBecomeFirstResponder = false
        performSegue(withIdentifier: "showSecond", sender: self)
    }
    ...
}

Second view controller:

class SecondViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        shouldBecomeFirstResponder = false
    }
    ...

    @IBAction didTap() {
        performSegue(withIdentifier: "showThird", sender: self)
    }

    ...
}

Third view controller:

class ThirdViewController: BaseViewController {

    ...
}


问:
automatically add commas to a number in a label similar like Indian currency system
```<code>using System.Globalization;

Label11.Text = totalPrice.ToString("0#,#0.00");
</code>```

My problem is that I am showing this number in Indian currency format. Please help.

答:
Paste the full code, the problem might not be where you think...

but try this

```<code>NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String convRupees = formatter.format(totalPrice);
Label1.Text = convRupees
</code>```

EDIT - THIS IS HOW YOU DO IN JAVA, THIS IS IN C#

```<code>CultureInfo hindi = new CultureInfo("hi-IN");
string conv = string.Format(hindi, "{0:c}", totalPrice.toString());
Label11.Text = conv;
</code>```

Body:
using System.Globalization;

Label11.Text = totalPrice.ToString("0#,#0.00");

My problem is that I am showing this number in Indian currency format. Please help.

Body:
Paste the full code, the problem might not be where you think...

but try this

NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String convRupees = formatter.format(totalPrice);
Label1.Text = convRupees

EDIT - THIS IS HOW YOU DO IN JAVA, THIS IS IN C#

CultureInfo hindi = new CultureInfo("hi-IN");
string conv = string.Format(hindi, "{0:c}", totalPrice.toString());
Label11.Text = conv;


答:
What's the reason for your aversion to the millions of rows? A perceived performance issue?

It's going to have hundreds of millions of relations somewhere. You do have to capture the mapping between actor and film and as you say, there are 200-300  million of those (although I don't believe there are 10 million movies in existence?)

If you really wanted, you could (for example) pack the ids for actors for a film into multiple columns (or into one column) but that would make searching unpleasant.

Title: Movie DB - storage of Actors / actress / Tags?

Body:
Creating a movie db and I dont like the idea of giving each actor/actress and also each tag its own row as if there are 10 million moives total, each has a cast of atleast 20-30 people we will have 200-300 million rows in the table.

And it gets more complex with tags which can be unlimited per movie. So how to best store these 3 items? Ideally these can be modeled as a Many to Many but still it will have hundreds of millions of rows. Any better suggestions on storing these? I am using MySQL.

I would dump it all in a textfile but I need to link actors between movies and do some analytics also and allow users to rate actors find movies by tag, etc so need to use a DB.


问:
How can I check if the race detector is enabled at runtime?
Is there any way I can check if the Go program is compiled with -race enabled at runtime (for e.g. logging/informational purposes)?

I checked the documentation, as well as the obvious locations (runtime/*), but I can't find anything.

答:
Since Go 1.18 there's debug.ReadBuildInfo(), which provides this; for example:

```<code>func race() {
    b, ok := debug.ReadBuildInfo()
    if !ok {
        fmt.Println("could not read build info")
        return
    }

    for _, s := range b.Settings {
        if s.Key == "-race" {
            fmt.Println("-race=" + s.Value)
            return
        }
    }
    fmt.Println("-race=false")
}
</code>```

Which will print -race=true or -race=false.

In most cases, simply using the debug.BuildInfo.String() method is probably the easiest, as it prints out other useful stuff as well.

Since this is available since Go 1.18, which is comparatively new at the time of writing, you may want to consider putting a // +build go.18 build tag and provide a shim for older Go versions.

Older pre-Go 1.18 answer, kept for posterity.

As far as I can find there is no simple check for this, but when -race is enabled the race build tag is set, so you can take advantage of that.

I made a new directory israce, and put two files there:

israce/race.go:

```<code>// +build race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = true
</code>```

israce/norace.go:

```<code>// +build !race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = false
</code>```

Due to the build tag only one of the two files will get compiled.

This is also how the Go standard library does it (race.go, norace.go), but since that's an internal package it can't be imported outside of the Go source base.

Body:
Since Go 1.18 there's debug.ReadBuildInfo(), which provides this; for example:

func race() {
    b, ok := debug.ReadBuildInfo()
    if !ok {
        fmt.Println("could not read build info")
        return
    }

    for _, s := range b.Settings {
        if s.Key == "-race" {
            fmt.Println("-race=" + s.Value)
            return
        }
    }
    fmt.Println("-race=false")
}

Which will print -race=true or -race=false.

In most cases, simply using the debug.BuildInfo.String() method is probably the easiest, as it prints out other useful stuff as well.

Since this is available since Go 1.18, which is comparatively new at the time of writing, you may want to consider putting a // +build go.18 build tag and provide a shim for older Go versions.

Older pre-Go 1.18 answer, kept for posterity.

As far as I can find there is no simple check for this, but when -race is enabled the race build tag is set, so you can take advantage of that.

I made a new directory israce, and put two files there:

israce/race.go:

// +build race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = true

israce/norace.go:

// +build !race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = false

Due to the build tag only one of the two files will get compiled.

This is also how the Go standard library does it (race.go, norace.go), but since that's an internal package it can't be imported outside of the Go source base.

ContentLicense: CC BY-SA 4.0