问:
ClosedXML. Memory leak while Workbook.Save()
I need to add new worksheet from dataTable. For this task I use ClosedXML:

```<code>workbook.Worksheets.Add(dataTable);
workbook.Save();
workbook = new XLWorkbook(filePath); //reload file to avoid exception at next saving
</code>```

My process used 128 Mb of memory but after Workbook.Save() this number is rised to 382 Mb. After I've added next worksheet memory usage rised from 464 Mb to 619 Mb. But actual file at this point was 1.6 Mb.

What could be the reason of this?

答:
XLWorkbook implements IDisposable which you should call to free any resources it holds. If you don't do this - they will only be released (assuming XLWorkbook implements proper finalizer) when instance is garbage collected, which will happen some time in the future. You should do it like this:

```<code>workbook.Save();
workbook.Dispose(); // < important
workbook = new XLWorkbook(filePath);
</code>```

Of course better would be to wrap workbook into using statement or at least use try and finally to ensure release on exception, but that is not directly related to the question.

Body:
I need to add new worksheet from dataTable. For this task I use ClosedXML:

workbook.Worksheets.Add(dataTable);
workbook.Save();
workbook = new XLWorkbook(filePath); //reload file to avoid exception at next saving

My process used 128 Mb of memory but after Workbook.Save() this number is rised to 382 Mb. After I've added next worksheet memory usage rised from 464 Mb to 619 Mb. But actual file at this point was 1.6 Mb.

What could be the reason of this?

Body:
XLWorkbook implements IDisposable which you should call to free any resources it holds. If you don't do this - they will only be released (assuming XLWorkbook implements proper finalizer) when instance is garbage collected, which will happen some time in the future. You should do it like this:

workbook.Save();
workbook.Dispose(); // < important
workbook = new XLWorkbook(filePath);

Of course better would be to wrap workbook into using statement or at least use try and finally to ensure release on exception, but that is not directly related to the question.


来源: stackexchange

问:
Early exit from function in a forEach?
How can I early exit from a function in my TypeScript file?

```<code>checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}
</code>```

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

答:
You could also not fight foreach :) and do it this way:

```<code>checkIfFollowed(){

    const filtered = this.currentUserInfos.followed
       .filter(el => el.id === 18785) // or some other condition
       .forEach(element => {
         // maybe you don't need to do anything here
         // or you can continue processing the element and you know you only have
         // items that you want
      });

   this.alreadyFollowed = filtered.length > 0;
   console.log('the end');
//    return; // no need for an empty return at the end of a function.
}
</code>```

HTH

ContentLicense: CC BY-SA 4.0

Title: Early exit from function in a forEach?

Body:
How can I early exit from a function in my TypeScript file?

checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

Body:
You could also not fight foreach :) and do it this way:

checkIfFollowed(){

    const filtered = this.currentUserInfos.followed
       .filter(el => el.id === 18785) // or some other condition
       .forEach(element => {
         // maybe you don't need to do anything here
         // or you can continue processing the element and you know you only have
         // items that you want
      });

   this.alreadyFollowed = filtered.length > 0;
   console.log('the end');
//    return; // no need for an empty return at the end of a function.
}

HTH

ContentLicense: CC BY-SA 3.0


问:
Effect of removal "static" keyword for function
Recently, I have learned the existence of "backtrace" function.
This function allow one to retrieve, at some conditions, the callstack of an ELF running program compiled without debugging information.

It's perfect for me (I can't insert debugging symbol in production program), but for "backtrace" to work, there is (roughly) two condition :

Tell the linker to add extra information (by passing -rdynamic option).

Convert all "static" function to "non-static" function.

My worries is that if I fullfill this two condition, my program will be slower (because compiler can't optimise non-static function as he optimize static function ?).
As far as I know, adding extra information with -rdynamic doesn't impact program's performance : it's just add a little weight to the ELF binary.

So here's my question :

What is the effect in term of running performance when all static function become non-static function ?

答:
What is the effect in term of running performance when all static function become non-static function ?

Ans - None

A Static function means that function is only visible to that file only and cannot be called outside that file. i.e. it has file scope.

Static functions are typically used in large programs when you do not want your functions to clash with other people's functions. A static function ensures that you can define a function and use it inside your own file, and somebody else can also define the same static function name in other file.

If your code compiles after removing the static keyword, then you do not have two functions with the same name and it will work just like any normal function.

It will have no run time penalty.


问:
Gnuplot misreads time data
I can't seem to get gnuplot to properly plot my time data. (I'm using version 4.6, patchlevel 3.)

For an MWE (well, non-working...), the input file

```<code>reset

set xdata time
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"

plot '-' using ($1):($2) with lines lw 3
15:36:12  1.0
15:43:17  3.0
16:12:02  2.0
e
</code>```

produces the following output:

Apparently, gnuplot interprets the hours as seconds and ignores the rest. I have tried a bunch of other format strings (also single/double quotes), but gnuplot seems to ignore everything except the first number.

Is something wrong with my format, or is this a bug, or something else?

答:
With $1 you explicitely select the numerical value of the first column, which bypasses any gnuplot automatism to interpret the column values as appropriate (as time value in your case). Simply use using 1:2:

```<code>reset
set xdata time
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"

plot '-' using 1:2 with lines lw 3
15:36:12  1.0
15:43:17  3.0
16:12:02  2.0
e
</code>```

Use the syntax $1 only when doing calculations with the actual numerical value in the respective column. $1 is a shortcut for column(1), gnuplot also knows stringcolumn(1) and timecolumn(1) for other purposes.

Title: Gnuplot misreads time data

Body:
I can't seem to get gnuplot to properly plot my time data. (I'm using version 4.6, patchlevel 3.)

For an MWE (well, non-working...), the input file

reset

set xdata time
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"

plot '-' using ($1):($2) with lines lw 3
15:36:12  1.0
15:43:17  3.0
16:12:02  2.0
e

produces the following output:

Apparently, gnuplot interprets the hours as seconds and ignores the rest. I have tried a bunch of other format strings (also single/double quotes), but gnuplot seems to ignore everything except the first number.

Is something wrong with my format, or is this a bug, or something else?

Body:
With $1 you explicitely select the numerical value of the first column, which bypasses any gnuplot automatism to interpret the column values as appropriate (as time value in your case). Simply use using 1:2:

reset
set xdata time
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"

plot '-' using 1:2 with lines lw 3
15:36:12  1.0
15:43:17  3.0
16:12:02  2.0
e

Use the syntax $1 only when doing calculations with the actual numerical value in the respective column. $1 is a shortcut for column(1), gnuplot also knows stringcolumn(1) and timecolumn(1) for other purposes.


问:
Getting undefined/no result when printing out api callback
I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.

OBS: I get undefined when using this $("" + plot + "	"), but blank when using $("").append(title). You can find that code in the middle of the renderMovies function.

For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.

```<code>$(document).ready(function(){
  $(init);

  function init() {
    $("#searchMovie").click(searchMovie);
    var movieTitle = $("#movieTitle");
    var table = $("#results");
    var tbody = $("#results tbody");

    function searchMovie(){
      var title = movieTitle.val();

      $.ajax({
        url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
        dataType: "jsonp",
        success: renderMovies
      });
    };

    function renderMovies(movies) {
      console.log(movies);
      tbody.empty();

      for(var m in movies) {
        var movie = movies[m];
        var title = movie.title;
        var plot = movie.simplePlot;
        var posterUrl = movie.urlPoster;
        var imdbUrl = movie.urlIMDB;

        var tr = $("<tr>");
        var titleTd = $("<td>").append(title); // blank
        var plotTd = $("<td>" + plot + "</td>"); // undefined on my website

        tr.append(titleTd);
        tr.append(plotTd);

        tbody.append(tr);
      }
    }
  }
});
</code>```

答:
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))

This returns a response on a button click.

```<code>    $(document).ready(function () {

function searchMovie() {
    var movieTitle = $("#movieTitle");
    var title = movieTitle.val();

    $.ajax({
        url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
        dataType: "jsonp",
        success: renderMovies
    });
}

function renderMovies(movies) {
    console.log(movies);
    var movieInfo = movies.data.movies;

    var table = $("#results");
    var tbody = $("#results tbody");

    tbody.empty();

    for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
    {

        var movie = movieInfo[m];
        var title = movie.title;
        var plot = movie.simplePlot;
        var posterUrl = movie.urlPoster;
        var imdbUrl = movie.urlIMDB;

        var tr = $("<tr>");
        var titleTd = $("<td>").append(title); // blank
        var plotTd = $("<td>" + plot + "</td>"); // undefined on my website

        tr.append(titleTd);
        tr.append(plotTd);

        tbody.append(tr);

    }

}

$("#searchMovie").click(searchMovie);

});
</code>```

Body:
I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.

OBS: I get undefined when using this $("" + plot + "	"), but blank when using $("").append(title). You can find that code in the middle of the renderMovies function.

For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.

$(document).ready(function(){
  $(init);

  function init() {
    $("#searchMovie").click(searchMovie);
    var movieTitle = $("#movieTitle");
    var table = $("#results");
    var tbody = $("#results tbody");

    function searchMovie(){
      var title = movieTitle.val();

      $.ajax({
        url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
        dataType: "jsonp",
        success: renderMovies
      });
    };

    function renderMovies(movies) {
      console.log(movies);
      tbody.empty();

      for(var m in movies) {
        var movie = movies[m];
        var title = movie.title;
        var plot = movie.simplePlot;
        var posterUrl = movie.urlPoster;
        var imdbUrl = movie.urlIMDB;

        var tr = $("
");
        var titleTd = $("").append(title); // blank
        var plotTd = $("" + plot + "	"); // undefined on my website

        tr.append(titleTd);
        tr.append(plotTd);

        tbody.append(tr);
      }
    }
  }
});

Body:
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))

This returns a response on a button click.

    $(document).ready(function () {

function searchMovie() {
    var movieTitle = $("#movieTitle");
    var title = movieTitle.val();

    $.ajax({
        url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
        dataType: "jsonp",
        success: renderMovies
    });
}

function renderMovies(movies) {
    console.log(movies);
    var movieInfo = movies.data.movies;

    var table = $("#results");
    var tbody = $("#results tbody");

    tbody.empty();

    for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
    {

        var movie = movieInfo[m];
        var title = movie.title;
        var plot = movie.simplePlot;
        var posterUrl = movie.urlPoster;
        var imdbUrl = movie.urlIMDB;

        var tr = $("<tr>");
        var titleTd = $("<td>").append(title); // blank
        var plotTd = $("<td>" + plot + "</td>"); // undefined on my website

        tr.append(titleTd);
        tr.append(plotTd);

        tbody.append(tr);

    }

}

$("#searchMovie").click(searchMovie);

});


问:
How to create Entity dynamically in Objective-C?
I'm building an iPad application where I need user to create entity dynamically. I'm already having 3 entities which program uses.

Could you help me with code how to do it?

I want to understand the whole structure according to my understanding I have to create new managedObjectModel, add new entities and than merge it with existing one, is it correct?

答:
While it is possible to create a new entity and a new model on the fly in practice this is massively complex. If nothing else you would have to migrate any existing persisted data to the new model and a new persistent store file. I strongly recommend against attempting this especially if you are just starting out with Core Data.

You do have options:

Firstly, are you sure you actually need a new entity? People just starting out with Core Data often mistake entities for managed objects. Entities are to managed objects as classes are to instances. Entities are abstractions used to create the object graph. They don't actually contain data. The times when you need new entities are very,very rare.

Secondly, if you do need some kind of dynamic entity, it would usually be best to decompose the dynamic entity into numerous fixed subentities and then use relationships to create a virtual entity. E.g. you need a dynamic Person "entity" so you create several entities in the model each of which holds one attribute of the person. You could have a Field entity which would have a fieldName attribute and then a fieldValue attribute. Then have a an actual Person entity that has no attributes but just relationships to the necessary Field objects. You could add any fields needed to any person and then reconstitute an virtual person object by walking the relationships to its fields.

I rather doubt however that you need that kind of flexibility. Such a need is very rare. I would step back and see exactly what dynamic data you think the user might need to enter.

ContentLicense: CC BY-SA 2.5


问:
Setting Json values in Powershell found using pipecommands
I have a JSON file that I am reading into a PowerShell object. I want to be able to replace certain values which I find using the where command and pipes.

```<code>[
   {
      "name":"name-1",
      "targets":[
         {
            "attribute":"Country",
            "opt":"In",
            "values":[
               "@country"
            ]
         },
         {
            "attribute":"Environment",
            "opt":"In",
            "values":[
               "@Environment"
            ]
         }
      ],
      "value":{
         "Url":"@url",
         "Version":"@version"
      }
   }
]
</code>```

I specifically want to replace the what @url, @version, @country and @environment with the values I specify in the powershell.

Setting the value.Url and value.Version seems to work with:

```<code>$body=Get-Content -Raw -Path "$path\$filename.json" | ConvertFrom-Json
$body.value.Url=$applicationUrl;
$body.Value.Version = $applicationVersion;
</code>```

But the targets attribute is a list, so I have to find using the where statement and pipes. Although I can find the correct element using:

```<code>$body.Targets | where { $_.attribute -eq "environment" } | Select -First 1 | Select-Object -Property values
</code>```

All my attempts to set the value have failed, it always remains as is.  Powershell is interpreting the object like:

```<code>$body.Targets | where { $_.attribute -eq "environment" } | Select -First 1 | Select-Object -Property values

TypeName: Selected.System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
values      NoteProperty Object[] values=System.Object[]
</code>```

How could I set the values property on this object?  I just want it to be a string like "qa" or "production"

Thanks

答:
Try to set the value attribute as follows:</p>

```<code>($body.Targets | Where-Object { $_.attribute -eq "environment" } | Select-Object -First 1).values = @("VALUE");
</code>```

Body:
I have a JSON file that I am reading into a PowerShell object. I want to be able to replace certain values which I find using the where command and pipes.

[
   {
      "name":"name-1",
      "targets":[
         {
            "attribute":"Country",
            "opt":"In",
            "values":[
               "@country"
            ]
         },
         {
            "attribute":"Environment",
            "opt":"In",
            "values":[
               "@Environment"
            ]
         }
      ],
      "value":{
         "Url":"@url",
         "Version":"@version"
      }
   }
]

I specifically want to replace the what @url, @version, @country and @environment with the values I specify in the powershell.

Setting the value.Url and value.Version seems to work with:

$body=Get-Content -Raw -Path "$path\$filename.json" | ConvertFrom-Json
$body.value.Url=$applicationUrl;
$body.Value.Version = $applicationVersion;

But the targets attribute is a list, so I have to find using the where statement and pipes. Although I can find the correct element using:

$body.Targets | where { $_.attribute -eq "environment" } | Select -First 1 | Select-Object -Property values

All my attempts to set the value have failed, it always remains as is.  Powershell is interpreting the object like:

$body.Targets | where { $_.attribute -eq "environment" } | Select -First 1 | Select-Object -Property values

TypeName: Selected.System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
values      NoteProperty Object[] values=System.Object[]

How could I set the values property on this object?  I just want it to be a string like "qa" or "production"

Thanks

Body:
Try to set the value attribute as follows:

($body.Targets | Where-Object { $_.attribute -eq "environment" } | Select-Object -First 1).values = @("VALUE");


问:
Get first value of Model's List in jQuery (document).ready using Razor?
How can I get the value of the first item from the model's List? My ViewModel:

```<code>namespace TestWeb
{
  public class NavViewModel
  {
    public NavViewModel()
    {
      NavStepList = new List<NavStep>();
    }

    public List<NavStep> NavStepList { get; set; }
  }
}
</code>```

In my View:

```<code>@using TestWeb
@model NavViewModel

<script>
  $(document).ready(function () {
    var Testvalue = @Model.NavStepList.First();
  });
</script>
</code>```

I want the first value of NavStepList. However an error occurs when I call this function:

TestWeb is undefined

I already test with testing value assign to NavStepList but the error still occurs.

My NavStep Class Property:

```<code>public class NavStep{
        public int NavStepId { get; set; }
        public int SortId { get; set; }
        public string StepName { get; set; }
        public string IdentifierKey { get; set; }
        public bool IsAvailible { get; set; }
}
</code>```

答:
Here @Model ought to refer to NavViewModel directly. Also, as Rory said, trying to assign a class, NavStep to a javascript variable isn't going to work out. What you probably want is:</p>

```<code>var navStepId = @Model.First().NavStepId;
var sortId = @Model.First().SortId;
var stepName = "@Model.First().StepName"; //wrap strings in "" so javascript recognizes them as such
var identifierKey = "@Model.First().IdentifierKey";
var isAvailable = "@(Model.First().IsAvailable)" === '@true'; //method to convert c# true to javascript true
</code>```

Body:
How can I get the value of the first item from the model's List? My ViewModel:

namespace TestWeb
{
  public class NavViewModel
  {
    public NavViewModel()
    {
      NavStepList = new List<NavStep>();
    }

    public List<NavStep> NavStepList { get; set; }
  }
}

In my View:

@using TestWeb
@model NavViewModel

I want the first value of NavStepList. However an error occurs when I call this function:

TestWeb is undefined

I already test with testing value assign to NavStepList but the error still occurs.

My NavStep Class Property:

public class NavStep{
        public int NavStepId { get; set; }
        public int SortId { get; set; }
        public string StepName { get; set; }
        public string IdentifierKey { get; set; }
        public bool IsAvailible { get; set; }
}

Body:
Here @Model ought to refer to NavViewModel directly. Also, as Rory said, trying to assign a class, NavStep to a javascript variable isn't going to work out. What you probably want is:

var navStepId = @Model.First().NavStepId;
var sortId = @Model.First().SortId;
var stepName = "@Model.First().StepName"; //wrap strings in "" so javascript recognizes them as such
var identifierKey = "@Model.First().IdentifierKey";
var isAvailable = "@(Model.First().IsAvailable)" === '@true'; //method to convert c# true to javascript true


问:
HC-06 (BC 417) how to disconnect to activate something
I was working on a project that involves using the HC-06, and the aim was to turn the led on when the bluetooth and my phone are far apart enough to disconnect. But I have no idea how to do it.

Here's the code I'm using on Arduino:

```<code>while (Serial.available()) {
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);                       // wait for a second
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);                       // wait for a second
};
</code>```

So I know here's the problem but I've search everywhere online and I have no idea how to activate the led as soon as they disconnect.

Please be descriptive because I'm new to coding.

答:
To activate the LED just do:

digitalWrite(13, HIGH);

To detect when the bluetooth is disconnedted just refer to this question.

https://electronics.stackexchange.com/questions/175083/can-i-tell-if-the-hc-06-bluetooth-is-connected

Basically you have two options:

Hardware solution: one option is to connect the status LED of the HC06 to an input pin on the Arduino and read it to determine if the LED is blinking or steady.

Software solution: Send an AT commend and check if you receive an OK back (not paired) or nothing back (paired)

By the way, It's strange that you haven't found anything after "searching everywhere online" since it just took 10 seconds to google search and find a solution.

Body:
I was working on a project that involves using the HC-06, and the aim was to turn the led on when the bluetooth and my phone are far apart enough to disconnect. But I have no idea how to do it.

Here's the code I'm using on Arduino:

while (Serial.available()) {
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);                       // wait for a second
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);                       // wait for a second
};

So I know here's the problem but I've search everywhere online and I have no idea how to activate the led as soon as they disconnect.

Please be descriptive because I'm new to coding.


问:
Octopus gem not working with active record relation
Recently we thought of using slave databases for few of our search / read operations . We do not have any plans to send all our read request to slaves. We just want to few of our search queries to hit to slave databases

I tried almost all the available gems, octopus, octoshark, db-charmer, makara, knockoff , But none of them are working correctly.

For example on Octopus (other gems too), below is a big issue

Octopus.using(:slave1) do User.first end .

This works fine and uses "slave1".

But not sure why the below is not working .

Octopus.using(:slave1) do User.where(id: 1) end

This one is not using slave1 but it fires on master database and most of our search queries are in this format.

It's quite frustrating till now. Any help would be greatly appreciated.

答:
Perhaps try establishing the database connection directly in the User model?

```<code>class User < ActiveRecord::Base
  octopus_establish_connection(db_url_to_slave)
  ..
 end
</code>```

We are currently using Octopus in production and I'm fairly certain the where use case works for us :P

This section in the docs details the approach, in case you want more information.

Body:
Perhaps try establishing the database connection directly in the User model?

class User < ActiveRecord::Base
  octopus_establish_connection(db_url_to_slave)
  ..
 end

We are currently using Octopus in production and I'm fairly certain the where use case works for us :P

This section in the docs details the approach, in case you want more information.


问:
Query showing records that do NOT match in between tables
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

```<code>Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly
</code>```

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

```<code>SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

And my results:

```<code>AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32
</code>```

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

```<code>AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly
</code>```

答:
This join will multiply the records from two tables into each other (Cartesian), and that  is why you are getting more records coming back.

Remember you are joining on AssessmentId and there are multiple records with the same assessmentId. Although you are filtering out those not having same ReportType  but you come across new combinations.

```<code>SELECT #QuarterlyReportsDue.InstallationDate,
       #QuarterlyReportsDue.QuarterlyReportType
FROM #QuarterlyReportsDue
WHERE NOT EXISTS
      (
      SELECT 1
      FROM Reports
      WHERE Reports.ReportType = QuarterlyReportsDue.QuarterlyReportType
      AND #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
      )
</code>```

Body:
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID

And my results:

AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly

Body:
This join will multiply the records from two tables into each other (Cartesian), and that  is why you are getting more records coming back.

Remember you are joining on AssessmentId and there are multiple records with the same assessmentId. Although you are filtering out those not having same ReportType  but you come across new combinations.

SELECT #QuarterlyReportsDue.InstallationDate,
       #QuarterlyReportsDue.QuarterlyReportType
FROM #QuarterlyReportsDue
WHERE NOT EXISTS
      (
      SELECT 1
      FROM Reports
      WHERE Reports.ReportType = QuarterlyReportsDue.QuarterlyReportType
      AND #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
      )


问:
Facebook SDK Android, java.lang.RuntimeException: Unable to get provider com.facebook.internal.FacebookInitProvider
Has anyone encountered this error before with Facebook SDK for Android?

java.lang.RuntimeException: Unable to get provider
  com.facebook.internal.FacebookInitProvider:
  java.lang.ClassNotFoundException: Didn't find class
  "com.facebook.internal.FacebookInitProvider" on path: DexPathList[[zip
  file "/data/app/com.hellogold.app.dev-2/base.apk"]

答:
The following code fixed my multidex issues for me. I got them from a group on engineer's blog post, thought I can't remember the original link, if anyone can find it, please link it in the comments and I will edit my answer to reflect that I got my solution from his blog post.

```<code>android.applicationVariants.all { variant ->
    task "fix${variant.name.capitalize()}MainDexClassList" << {
        logger.info "Fixing main dex keep file for $variant.name"
        File keepFile = new File("$buildDir/intermediates/multi-dex/$variant.buildType.name/maindexlist.txt")
        keepFile.withWriterAppend { w ->
            // Get a reader for the input file
            w.append('\n')
            new File("${projectDir}/multidex.keep").withReader { r ->
                // And write data from the input into the output
                w << r << '\n'
            }
            logger.info "Updated main dex keep file for ${keepFile.getAbsolutePath()}\n$keepFile.text"
        }
    }
}
tasks.whenTaskAdded { task ->
    android.applicationVariants.all { variant ->
        if (task.name == "create${variant.name.capitalize()}MainDexClassList") {
            task.finalizedBy "fix${variant.name.capitalize()}MainDexClassList"
        }
    }
}
</code>```

So the above worked for

compileSdkVersion 25
minSdkVersion 16
targetSdkVersion 25
multiDexEnabled true

I declared it in the app's gradle and not the main gradle.

Body:
The following code fixed my multidex issues for me. I got them from a group on engineer's blog post, thought I can't remember the original link, if anyone can find it, please link it in the comments and I will edit my answer to reflect that I got my solution from his blog post.

android.applicationVariants.all { variant ->
    task "fix${variant.name.capitalize()}MainDexClassList" << {
        logger.info "Fixing main dex keep file for $variant.name"
        File keepFile = new File("$buildDir/intermediates/multi-dex/$variant.buildType.name/maindexlist.txt")
        keepFile.withWriterAppend { w ->
            // Get a reader for the input file
            w.append('\n')
            new File("${projectDir}/multidex.keep").withReader { r ->
                // And write data from the input into the output
                w << r << '\n'
            }
            logger.info "Updated main dex keep file for ${keepFile.getAbsolutePath()}\n$keepFile.text"
        }
    }
}
tasks.whenTaskAdded { task ->
    android.applicationVariants.all { variant ->
        if (task.name == "create${variant.name.capitalize()}MainDexClassList") {
            task.finalizedBy "fix${variant.name.capitalize()}MainDexClassList"
        }
    }
}

So the above worked for

compileSdkVersion 25
minSdkVersion 16
targetSdkVersion 25
multiDexEnabled true

I declared it in the app's gradle and not the main gradle.


问:
passing parameter SSRS
I have the next report…

I wanted to add a parameter… Which would be user entered…  The thing is that, if the parameter is empty, I want it not to filter anything… and if populated, to filter by that…

Can this be achieved? I reckon that if empty will do

```<code>WHERE PARAMETER = ‘’
</code>```

and of course that’s not the intended behavior…

答:
You can have a dummy value in your selection list.

For example:

```<code>select
'All' as [Label],
null as [Value]

union all

select
    a.Name as [Label],
    a.Value as [Value]
from dbo.HereAreMyValues as [a]
</code>```

This will give you a selection option of "All" to show all (i.e. no filtering) in your parameter.

You can then reference this as..

```<code>from dbo.Data as [d]
where (d.Value = (@Parameter) or (@Parameter) is null)
</code>```

This will give you the data that either matches the parameter value, or all if the parameter value is null.

Title: passing parameter SSRS

Body:
I have the next report…

I wanted to add a parameter… Which would be user entered…  The thing is that, if the parameter is empty, I want it not to filter anything… and if populated, to filter by that…

Can this be achieved? I reckon that if empty will do

WHERE PARAMETER = ‘’

and of course that’s not the intended behavior…

Body:
You can have a dummy value in your selection list.

For example:

select
'All' as [Label],
null as [Value]

union all

select
    a.Name as [Label],
    a.Value as [Value]
from dbo.HereAreMyValues as [a]

This will give you a selection option of "All" to show all (i.e. no filtering) in your parameter.

You can then reference this as..

from dbo.Data as [d]
where (d.Value = (@Parameter) or (@Parameter) is null)

This will give you the data that either matches the parameter value, or all if the parameter value is null.


问:
How to set dynamic route in codeigniter from database?
In my routes.php file I have added the following code for routing:

```<code>$route['report/:num'] = "home/reportcard/$1";
</code>```

Here is my controller code:

```<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }
</code>```

Here is my model code:

```<code><?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>
</code>```

this is the code of view. I just print the array in my report_view for testing purpose:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>
</code>```

this is my home_view code:

```<code><div class="row">
                <ul class="home-grid">
                    <?php foreach ($query->result() as $row): ?>
                    <li>
                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report"><span class="glyphicon glyphicon-list-alt"></span> <br/>
                        <?=$row->item ?><br/>
                         <small>Click here for see report</small>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
</code>```

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

答:
change your root from $route['report/:num'] = "home/reportcard/$1";

to

```<code>$route['report/(:num)'] = "home/reportcard/$1";
</code>```

and

```<code><a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report">
</code>```

this line of code will create href="localhost/super_shop_register/report/Chips/1".
You need to remove <?=$row->item ?>/ from it.

Body:
In my routes.php file I have added the following code for routing:

$route['report/:num'] = "home/reportcard/$1";

Here is my controller code:

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }

Here is my model code:

<?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>

this is the code of view. I just print the array in my report_view for testing purpose:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>

this is my home_view code:

                    <?php foreach ($query->result() as $row): ?>

                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report">

                        <?=$row->item ?>

                         Click here for see report

                    <?php endforeach; ?>

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

Body:
change your root from $route['report/:num'] = "home/reportcard/$1";

to

$route['report/(:num)'] = "home/reportcard/$1";

and

<a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report">

this line of code will create href="localhost/super_shop_register/report/Chips/1".
You need to remove <?=$row->item ?>/ from it.


问:
I cannot get my traffic light sequence to work in html
In my a452 computing class, I am trying to change an image with a button to represent I traffic light sequence.

I can display my first picture but the pictures will not change. in my sequence I have the pictures of the traffic lights but they cannot be displayed.

when I run it the first picture is loaded but then it will not load any other images

In my a452 computing I am trying to change an image with a button to represent I traffic light sequence. I can display my first picture but the pictures will not change, please help. Here is my code:

<!DOCTYPE html>

          <input type="button" id="change" value="change lights" onclick=TL()>

```

答:
Case sensitive problem: document.getElementById('lights'); (notice the bold letter, capitalize 'b').

I'd recommend splitting your code in "steps" if you're new. I made some modifications, check it out, it works for me. I added console-printing to clarify.

```<code>    <script>
    var count = 0;
    function TL() {
      var TLassets = ["Red.png", "yellow.png", "Green.png"];
      count++
        if (count < 3) {
          console.log(count);
          console.log(TLassets[count])
          var edit_picture =  document.getElementById('lights');
          edit_picture.src = TLassets[count];
        } else {
          count = 0;
          console.log(count);
          console.log(TLassets[count])
          var edit_picture =  document.getElementById('lights');
          edit_picture.src = TLassets[count];
        }
      }
    </script>
</code>```

Body:
Case sensitive problem: document.getElementById('lights'); (notice the bold letter, capitalize 'b').

I'd recommend splitting your code in "steps" if you're new. I made some modifications, check it out, it works for me. I added console-printing to clarify.

    <script>
    var count = 0;
    function TL() {
      var TLassets = ["Red.png", "yellow.png", "Green.png"];
      count++
        if (count < 3) {
          console.log(count);
          console.log(TLassets[count])
          var edit_picture =  document.getElementById('lights');
          edit_picture.src = TLassets[count];
        } else {
          count = 0;
          console.log(count);
          console.log(TLassets[count])
          var edit_picture =  document.getElementById('lights');
          edit_picture.src = TLassets[count];
        }
      }
    </script>


问:
Sub selects within MySQL query
I am wanting to alias 3 variables in my query, total_time_taken and average and request_count.

The average is meant to calculate the total_time_taken / request_count to return average however it is giving me a syntax error

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, r' at line 4
</code>```

The query is below.

```<code>select
    *,
    COUNT(*) as request_count,
    select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, requests.assigned_at)) from requests) as total_time_taken,
    total_time_taken / request_count as average
from
    `requests`
where
    `deleted_at` is null
and
    `submitted_at` >= '2017-03-30 00:00:00'
and
    `requests`.`deleted_at` is null
group by
    `engineer_id`
limit 5
</code>```

答:
I don't see the point of the subqueries, why not just take the sum as you aggregate by each engineer?  Alse, you were doing SELECT * with GROUP BY, which usually doesn't work, and usually is wrong, because it would include non aggregate columns.  Instead, just select engineer_id or an aggregate of some other column.

```<code>SELECT
    engineer_id,
    COUNT(*) AS request_count,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) AS total_time_taken,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) /
    COUNT(*) AS average
FROM requests
WHERE deleted_at IS NULL AND
      submitted_at >= '2017-03-30 00:00:00' AND
      deleted_at IS NULL
GROUP BY engineer_id
LIMIT 5
</code>```

Title: Sub selects within MySQL query

Body:
I am wanting to alias 3 variables in my query, total_time_taken and average and request_count.

The average is meant to calculate the total_time_taken / request_count to return average however it is giving me a syntax error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, r' at line 4

The query is below.

select
    *,
    COUNT(*) as request_count,
    select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, requests.assigned_at)) from requests) as total_time_taken,
    total_time_taken / request_count as average
from
    `requests`
where
    `deleted_at` is null
and
    `submitted_at` >= '2017-03-30 00:00:00'
and
    `requests`.`deleted_at` is null
group by
    `engineer_id`
limit 5

Body:
I don't see the point of the subqueries, why not just take the sum as you aggregate by each engineer?  Alse, you were doing SELECT * with GROUP BY, which usually doesn't work, and usually is wrong, because it would include non aggregate columns.  Instead, just select engineer_id or an aggregate of some other column.

SELECT
    engineer_id,
    COUNT(*) AS request_count,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) AS total_time_taken,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) /
    COUNT(*) AS average
FROM requests
WHERE deleted_at IS NULL AND
      submitted_at >= '2017-03-30 00:00:00' AND
      deleted_at IS NULL
GROUP BY engineer_id
LIMIT 5


问:
Need to redirect subdomain that has the url as parameter
I'm wanting to redirect

http://m.example.com/?url=http://www.example.com/directory/page.html

to

http://www.example.com/directory/page.html (always the value of 'url=')

The are mobile versions of my site that I want to serve on my main site. Right now the search results contain my mobile pages. Until the main, responsive pages are crawled I want to force them to be viewed.

答:
As mentioned in the comments to the question your incoming url is invalid. The query parameter (the value) would have to be url encoded like that to be valid: http://m.example.com/?url=http%3A%2F%2Fwww.example.com%2Fdirectory%2Fpage.html. Though probably that invalid URL will work in most cases.

This should do what you are looking for:

```<code>RewriteMap unescape int:unescape
RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.*)url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)(&?.*)$
RewriteRule ^ http%2://%3/${unescape:%4}?%1%5 [R=301,END]
</code>```

Note that the RewriteMap directive can only be used inside the http servers host configuration, not in dynamic configuration files. If you need to use such a file (see general note below), you have to split the above into two separate sections:

Inside your http servers (virtual) host configuration:

```<code>RewriteMap unescape int:unescape
</code>```

Inside your dynamic configuration file:

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.*)url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)(&?.*)$
RewriteRule ^ http%2://%3/${unescape:%4}?%1%5 [R=301,END]
</code>```

If you do not want any http GET parameters to be handed over to the final redirection target, then the above can be simplified:

```<code>RewriteMap unescape int:unescape
RewriteEngine on
RewriteCond %{QUERY_STRING} url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)
RewriteRule ^ http%1://%2/${unescape:%3} [R=301,END,QSD]
</code>```

And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Body:
As mentioned in the comments to the question your incoming url is invalid. The query parameter (the value) would have to be url encoded like that to be valid: http://m.example.com/?url=http%3A%2F%2Fwww.example.com%2Fdirectory%2Fpage.html. Though probably that invalid URL will work in most cases.

This should do what you are looking for:

RewriteMap unescape int:unescape
RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.*)url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)(&?.*)$
RewriteRule ^ http%2://%3/${unescape:%4}?%1%5 [R=301,END]

Note that the RewriteMap directive can only be used inside the http servers host configuration, not in dynamic configuration files. If you need to use such a file (see general note below), you have to split the above into two separate sections:

Inside your http servers (virtual) host configuration:

RewriteMap unescape int:unescape

Inside your dynamic configuration file:

RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.*)url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)(&?.*)$
RewriteRule ^ http%2://%3/${unescape:%4}?%1%5 [R=301,END]

If you do not want any http GET parameters to be handed over to the final redirection target, then the above can be simplified:

RewriteMap unescape int:unescape
RewriteEngine on
RewriteCond %{QUERY_STRING} url=http(s?)%3A%2F%2F([^%]+)%2F([^&]+)
RewriteRule ^ http%1://%2/${unescape:%3} [R=301,END,QSD]

And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


问:
Switch button to turn on notifications
hope you could help me here!
I want to make a switch button that turns on a function of push daily push notification. how do I do that?

the switch button is on the Settings fragment

My MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    displayView(R.id.nav_home);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    if (getSupportFragmentManager().findFragmentById(R.id.content_main) instanceof Article) {
        ((Article) getSupportFragmentManager().findFragmentById(R.id.content_main)).handleOnBackPress();
        return;
    }

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        displayView(R.id.nav_home);
    } else {
        super.onBackPressed();

    }
}

private void displayView(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Article();
            break;
        case R.id.nav_Recipes:
            fragment = new RecipesMain();
            break;
        case R.id.nav_Converter:
            fragment = new Converter();
            break;
        case R.id.nav_Videos:
            fragment = new Videos();
            break;
        case R.id.nav_Tracking:
            fragment = new Tracking();
            break;
        case R.id.nav_TrainerMenu:
            fragment = new TrainerMenu();
            break;
        case R.id.nav_Settings:
            fragment = new Settings();
            break;
        case R.id.nav_About:
            showDialog();
            break;

    }

    if (fragment != null) {
        final Fragment finalFragment = fragment;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        .replace(R.id.content_main, finalFragment)
                        .commit();
            }
        }, 0);
            }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displayView(item.getItemId());
    return true;
}
private void showDialog()
{
    String text2 = "<font color=#6774bd>About SG50 App</font>";

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>App made by Matan Cohen , Please contact me for any questions.</font>";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Toast toast = Toast.makeText(getApplicationContext(), "תודה על שימוש", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

    builder.show();
 }

}
</code>```

fragment Settings.java the "editor.getBoolean" gives me cannot resolve error!! what can I do?:

```<code>public class Settings extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("הגדרות");

    Switch aSwitch = (Switch) getView().findViewById(R.id.dailyTipSwitch);
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("key", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("switchValue", aSwitch.isChecked());
    editor.apply();
    boolean showNotifications = editor.getBoolean("key",false);
            if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
            else {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,19);
                calendar.set(Calendar.MINUTE,27);
                Intent intent = new Intent(getActivity().getApplicationContext(),NotificationReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
            }

    }

}
</code>```

Notification_Reciever.java

```<code>public class NotificationReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    Intent repeatingIntent = new Intent(context,MainActivity.class);
    repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeatingIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new
            NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("בוקר טוב אלוף! תאכל ותשתה טוב!"))
            .setContentText(context.getString(R.string.NotificationText))
            .setContentTitle(context.getString(R.string.GoodMorningNotification))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    notificationManager.notify(100, mBuilder.build());
    }
}
</code>```

fragemnt_settings.XML:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingBottom="30dp"
android:paddingTop="30dp"
android:paddingRight="30dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="left" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right"
        android:text="@string/daily_tip"
        android:textSize="20sp"/>
</LinearLayout>

</LinearLayout>
</code>```

Thank you!! Hope you can help me!

THE editor.getBoolean GIVES ME CANNOT RESOLVE ERROR!!!
what Can I do???

答:
If understand correctly, the issue here is not about how to know if the switch is turned on or off, but about avoiding getting push notifications according to switch state.

You want to avoid getting the notification and NOT - get the notification and decide whether to present it or not.

So what you need is to save switch state as mentioned in other answers, but in addition - If the user switched the state to OFF you need to unregister the user from getting the notifications and vice versa, using the following:

Either delete the token from the server which holds the user's FCM token:

```<code>// Remove user from notification messages
InstanceID.getInstance(context).deleteInstanceID();

// Register user back to get notifications
FirebaseInstanceId.getInstance().getToken() // This will call the onTokenRefresh() method which will call your implementation that calls your FCM server and update the new user's token
</code>```

Or if this user is registered to a specific notification topic

```<code>// Unregister him from the topic
FirebaseMessaging.getInstance().unsubscribeToTopic("news");

// Register him back in case switch is on
FirebaseMessaging.getInstance().subscribeToTopic("news");
</code>```

Title: Switch button to turn on notifications

Body:
hope you could help me here!
I want to make a switch button that turns on a function of push daily push notification. how do I do that?

the switch button is on the Settings fragment

My MainActivity.java:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    displayView(R.id.nav_home);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    if (getSupportFragmentManager().findFragmentById(R.id.content_main) instanceof Article) {
        ((Article) getSupportFragmentManager().findFragmentById(R.id.content_main)).handleOnBackPress();
        return;
    }

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        displayView(R.id.nav_home);
    } else {
        super.onBackPressed();

    }
}

private void displayView(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Article();
            break;
        case R.id.nav_Recipes:
            fragment = new RecipesMain();
            break;
        case R.id.nav_Converter:
            fragment = new Converter();
            break;
        case R.id.nav_Videos:
            fragment = new Videos();
            break;
        case R.id.nav_Tracking:
            fragment = new Tracking();
            break;
        case R.id.nav_TrainerMenu:
            fragment = new TrainerMenu();
            break;
        case R.id.nav_Settings:
            fragment = new Settings();
            break;
        case R.id.nav_About:
            showDialog();
            break;

    }

    if (fragment != null) {
        final Fragment finalFragment = fragment;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        .replace(R.id.content_main, finalFragment)
                        .commit();
            }
        }, 0);
            }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displayView(item.getItemId());
    return true;
}
private void showDialog()
{
    String text2 = "About SG50 App";

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "App made by Matan Cohen , Please contact me for any questions.";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Toast toast = Toast.makeText(getApplicationContext(), "תודה על שימוש", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

    builder.show();
 }

}

fragment Settings.java the "editor.getBoolean" gives me cannot resolve error!! what can I do?:

public class Settings extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("הגדרות");

    Switch aSwitch = (Switch) getView().findViewById(R.id.dailyTipSwitch);
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("key", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("switchValue", aSwitch.isChecked());
    editor.apply();
    boolean showNotifications = editor.getBoolean("key",false);
            if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
            else {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,19);
                calendar.set(Calendar.MINUTE,27);
                Intent intent = new Intent(getActivity().getApplicationContext(),NotificationReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
            }

    }

}

Notification_Reciever.java

public class NotificationReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    Intent repeatingIntent = new Intent(context,MainActivity.class);
    repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeatingIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new
            NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("בוקר טוב אלוף! תאכל ותשתה טוב!"))
            .setContentText(context.getString(R.string.NotificationText))
            .setContentTitle(context.getString(R.string.GoodMorningNotification))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    notificationManager.notify(100, mBuilder.build());
    }
}

fragemnt_settings.XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingBottom="30dp"
android:paddingTop="30dp"
android:paddingRight="30dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="left" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right"
        android:text="@string/daily_tip"
        android:textSize="20sp"/>
</LinearLayout>

</LinearLayout>

Thank you!! Hope you can help me!

THE editor.getBoolean GIVES ME CANNOT RESOLVE ERROR!!!
what Can I do???

Body:
If understand correctly, the issue here is not about how to know if the switch is turned on or off, but about avoiding getting push notifications according to switch state.

You want to avoid getting the notification and NOT - get the notification and decide whether to present it or not.

So what you need is to save switch state as mentioned in other answers, but in addition - If the user switched the state to OFF you need to unregister the user from getting the notifications and vice versa, using the following:

Either delete the token from the server which holds the user's FCM token:

// Remove user from notification messages
InstanceID.getInstance(context).deleteInstanceID();

// Register user back to get notifications
FirebaseInstanceId.getInstance().getToken() // This will call the onTokenRefresh() method which will call your implementation that calls your FCM server and update the new user's token

Or if this user is registered to a specific notification topic

// Unregister him from the topic
FirebaseMessaging.getInstance().unsubscribeToTopic("news");

// Register him back in case switch is on
FirebaseMessaging.getInstance().subscribeToTopic("news");


问:
Generate coverage for other modules
My project structure is as follows: :app, :core. :app is the Android application project, and it depends on :core which has all the business logic.

I have Espresso tests for :app, and I am able to run and get coverage report thanks to all the questions and guides out there. But the coverage is only for code in :app.

How do I get coverage for all projects (:app and :core) resulting from my Espresso instrumentation tests? Is this even possible?

Any help is greatly appreciated.

答:
Even if you did not mention Jacoco in your question, it is listed in the tags, so I assume you want to create coverage reports by using it. The Gradle Jacoco plugin (apply plugin: 'jacoco') allows you to create custom tasks of the type JacocoReport.

Defining such a task, you can specify source and class directories as well as the execution data:

```<code>task jacocoTestReport(type: JacocoReport) {
    dependsOn // all your test tasks
    reports {
        xml.enabled = true
        html.enabled = true
    }
    sourceDirectories = // files() or fileTree() to your source files
    classDirectories = // files() or fileTree() to your class files
    executionData = // files() or fileTree() including all your test results
}
</code>```

For Espresso tests, the execution data should include all generated .ec files. You could define this task in the Gradle root project and link to both the files and the tasks of your subprojects.

There is an example for a custom Jacoco report task, even if it aims on creating an unified report for multiple test types, it can be transfered for this multi-project problem.

Title: Generate coverage for other modules

Body:
Even if you did not mention Jacoco in your question, it is listed in the tags, so I assume you want to create coverage reports by using it. The Gradle Jacoco plugin (apply plugin: 'jacoco') allows you to create custom tasks of the type JacocoReport.

Defining such a task, you can specify source and class directories as well as the execution data:

task jacocoTestReport(type: JacocoReport) {
    dependsOn // all your test tasks
    reports {
        xml.enabled = true
        html.enabled = true
    }
    sourceDirectories = // files() or fileTree() to your source files
    classDirectories = // files() or fileTree() to your class files
    executionData = // files() or fileTree() including all your test results
}

For Espresso tests, the execution data should include all generated .ec files. You could define this task in the Gradle root project and link to both the files and the tasks of your subprojects.

There is an example for a custom Jacoco report task, even if it aims on creating an unified report for multiple test types, it can be transfered for this multi-project problem.


问:
publish project to server through ftp
I am going to build my project using gulp and upload the built program to a testing server through ftp. Once testing pass, I need to upload the version to a production server. Everything is done primitively.

However, if the number of project increase, it will be quite difficult to handle all of them.

What I want to do is develop a simple program which allow me to transfer a folder of whole files to a server.

I want the program is decided in nodejs hence i can add my own security mechanism. It should be better if the program can merge with gulp.

Can someone give me some suggestions?

答:
I am going to build my project using gulp and upload the built program to a testing server through ftp. [...] I want the program is decided in nodejs hence i can add my own security mechanism.

First of all, if you're using ftp then you can forget about security mechanisms. The FTP protocol is inherently insecure and you should not use it for anything, especially for critical things like this.

You should be using scp, rsync or git for things like that instead, as is usually done.

Now, what you're trying to do here is reinventing a CI system when there are a lot of such systems readily available, from systems that you host yourself like Jenkins, to systems that are hosted for you like Travis or Circle. Some of them offer free service.

They can integrate well with Gulp, they can get all of your changes from GitHub or other git repo, test everything for you and even deploy the code to production servers when the tests pass.

Those are very complicated systems that are hard to do right and handling the source code is security critical. First I would evaluate the following tools and services and only if none of them suits your needs I would consider developing a custom tool for that.

Some tools and services that you can use:

Jenkins

Travis CI

Circle CI

Codeship

GitLab CI

More tools:

http://www.yegor256.com/2014/10/05/ten-hosted-continuous-integration-services.html

https://www.slant.co/topics/186/~best-hosted-continuous-integration-services

Title: publish project to server through ftp


问:
How can I move all files and directories from disk to the folder on this disk?
I have disk D with the files and directories. I want to move all files and directories including the root of disk D to the new folder saving the tree.

For example, I have file D:\1.txt. I want to move it to D:\new_folder\1.txt

The second example. I have file D:\1\1\1.txt. I want to move it to D:\new_folder\1\1\1.txt

As you can see, I want to move all contents of disk D to the folder  D:\new_folder\.

I tried robocopy, but it can't move from root of disk.

答:
not tested:

```<code>for /d %%# in (D:\*) do (
  xcopy "%%#" "D:\new_folder\%%~nx#" /i
)

for %%# in (D:\*) do (
  copy /Y "%%#" "D:\new_folder\"
)
</code>```

Again not tested (with powershell):

```<code>Get-ChildItem -Path "D:\*" | ForEach-Object {if((Get-Item $_) -is [System.IO.DirectoryInfo]){Copy-Item "$_.FullName" "D:\new_folder" -recurse } else {Copy-Item "$_.FullName" "D:\new_folder"}}
</code>```

Body:
not tested:

for /d %%# in (D:\*) do (
  xcopy "%%#" "D:\new_folder\%%~nx#" /i
)

for %%# in (D:\*) do (
  copy /Y "%%#" "D:\new_folder\"
)

Again not tested (with powershell):

Get-ChildItem -Path "D:\*" | ForEach-Object {if((Get-Item $_) -is [System.IO.DirectoryInfo]){Copy-Item "$_.FullName" "D:\new_folder" -recurse } else {Copy-Item "$_.FullName" "D:\new_folder"}}


问:
gridview asp.net
I have a gridview which was working fine with a small dataset in development. In production it has to bind to thousands of records, which is making it slower to load. Is there a way to improve performance, like retrieving the data during gridview pageindex changing?</p>

答:
Also chances are you only want to bind it once. So you should (if not already):

```<code>if(!IsPostback)
{
    DatabindGridLogicHere();
}
</code>```

This way your GridView will only have to hit the db the first time to get the data.

Title: gridview asp.net

Body:
Also chances are you only want to bind it once. So you should (if not already):

if(!IsPostback)
{
    DatabindGridLogicHere();
}

This way your GridView will only have to hit the db the first time to get the data.


问:
Display the selected item of a RadioButtonList in TextBox
I am new to ASP.NET. I am trying to display the text of a radio button in a text box when the radio button is selected. I have tried two different ways of doing it without success:

Attempt 1:

Code in my aspx file:

```<code><asp:RadioButtonList ID="radioList" runat="server">
<asp:ListItem Value="selection1" Text ="One"></asp:ListItem>
<asp:ListItem Value="selection2" Text="Two"></asp:ListItem>
</asp:RadioButtonList>
</code>```

And then my .cs code:

```<code>public void displayText(object sender, EventArgs e)
{
    var result = radioList.SelectedValue;
    output.Text = result.Text; /* Have also tried result.ToString() */
}
</code>```

Attempt 2:

Same aspx as above

.cs code:

```<code>public void displayText(object sender, EventArgs e)
{
    if (selection1.Checked)
    {
        output.Text = "One";
    }
}
</code>```

The first attempt doesn't give me any errors, but doesn't display the text. The second attempt gives me Error CS0103 The name 'selection1' does not exist in the current context    1_ASPTEST.aspx

I'm sure it's something simple that I'm just overlooking but I'm stumped. Thanks!

答:
You may use this too.

```<code> if (radioList.SelectedItem != null)
        {
             output.Text = radioList.SelectedItem.Text;
        }
</code>```

Hope!. It will help you

Body:
I am new to ASP.NET. I am trying to display the text of a radio button in a text box when the radio button is selected. I have tried two different ways of doing it without success:

Attempt 1:

Code in my aspx file:

<asp:RadioButtonList ID="radioList" runat="server">
<asp:ListItem Value="selection1" Text ="One"></asp:ListItem>
<asp:ListItem Value="selection2" Text="Two"></asp:ListItem>
</asp:RadioButtonList>

And then my .cs code:

public void displayText(object sender, EventArgs e)
{
    var result = radioList.SelectedValue;
    output.Text = result.Text; /* Have also tried result.ToString() */
}

Attempt 2:

Same aspx as above

.cs code:

public void displayText(object sender, EventArgs e)
{
    if (selection1.Checked)
    {
        output.Text = "One";
    }
}

The first attempt doesn't give me any errors, but doesn't display the text. The second attempt gives me Error CS0103 The name 'selection1' does not exist in the current context    1_ASPTEST.aspx

I'm sure it's something simple that I'm just overlooking but I'm stumped. Thanks!

Body:
You may use this too.

 if (radioList.SelectedItem != null)
        {
             output.Text = radioList.SelectedItem.Text;
        }

Hope!. It will help you


问:
Secure VBA Excel Addin Code
I have an Excel addin, developed in VBA, deployed on the network.

The addin reads from an Oracle database, and pastes tables  in a new worksheet, which will also contain a button (triangle shape) to refresh the table.

Everything works great, but I must protect code with password.

When i do, the following error appears on some machines:

Compile error in hidden module: Main.
  This error commonly occurs when code is incompatible with the version, platform, or architecture of this application.

Although it compiles perfectly when unlocked.

On other machines it requires VBA password on close, even though i have nothing of the sort defined under close event.

I am hoping to secure my code, without running into above problems.
Any suggestions are appreciated.

答:
I know of two situations in which this error occurs:

1: 32bit vs. 64bit issues (already mentioned in the comments). If you've developed a 32bit addin and try to deploy/use it within a 64bit Excel, then your quoted error message will appear.

2: Missing references.

I think the second option is more likely to be the cause of the problem, because usually all client PCs in a company will have the identical version of MS Office installed and this error occurs only on some machines.

So I suggest to check your references. In the VBA-Editor (Alt+F11) go to tools --> references and note down any ticked modules. Then compare this to a client where the error is occuring (go to client PC and repeat the procedure).

If the ticked modules don't match between development and client PC, this is most likely the cause of this issue. You might also encounter modules with a "MISSING" written in front of their name on the client PC. In this case, remove the tick from the missing module and try to execute your addin.

If it works flawlessly you should be good to go, if not you'll have to manually install the missing modules on the clients PC.

Hope this will help you.

Title: Secure VBA Excel Addin Code


问:
pip doesn't see setuptools
I am migrating from python2 to python3.

I created a virtualenv with python3 -m venv py3 and am trying to pip install -r requirements.txt but it says

```<code>Collecting mock==1.0.1 (from -r requirements.txt (line 8))
  Using cached mock-1.0.1.tar.gz
  setuptools must be installed to install from a source distribution
</code>```

I checked my virtualenv and it does have setuptools:

```<code>(py3) 1111:d3 1111$ ls py3/lib/python3.4/site-packages/
__pycache__         easy_install.py         pip-6.0.8.dist-info     setuptools
_markerlib          pip             pkg_resources           setuptools-12.0.5.dist-info
</code>```

but when I still try to reinstall setuptools it says

```<code>(py3) 1111:d3 1111$ pip install setuptools
Requirement already satisfied (use --upgrade to upgrade): setuptools in
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
</code>```

So I have 2 questions:

why doesn't it see setuptools in virtualenv folder?

why does it look in Python 2 folders instead of Python 3?

Thanks!

答:
This one worked for me:</p>

```<code>pip install --upgrade pip
pip install setuptools
</code>```

Title: pip doesn't see setuptools

Body:
I am migrating from python2 to python3.

I created a virtualenv with python3 -m venv py3 and am trying to pip install -r requirements.txt but it says

Collecting mock==1.0.1 (from -r requirements.txt (line 8))
  Using cached mock-1.0.1.tar.gz
  setuptools must be installed to install from a source distribution

I checked my virtualenv and it does have setuptools:

(py3) 1111:d3 1111$ ls py3/lib/python3.4/site-packages/
__pycache__         easy_install.py         pip-6.0.8.dist-info     setuptools
_markerlib          pip             pkg_resources           setuptools-12.0.5.dist-info

but when I still try to reinstall setuptools it says

(py3) 1111:d3 1111$ pip install setuptools
Requirement already satisfied (use --upgrade to upgrade): setuptools in
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python

So I have 2 questions:

why doesn't it see setuptools in virtualenv folder?

why does it look in Python 2 folders instead of Python 3?

Thanks!

Body:
This one worked for me:

pip install --upgrade pip
pip install setuptools


问:
return sample date between min date and max date in R in a dataframe
How to return sample date between min date and max date in R in a dataframe as an additional column?</p>

```<code>Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017
</code>```

答:
You can compute the number of days between the two dates:

```<code>days <- as.Date(data$MinEnrollmentDate, format="%d/%m/%Y") - as.Date(data$MaxEnrollmentDate, format="%d/%m/%Y")
</code>```

And then add to MinEnrollmentDate a random number between 1 and the number of days to the MaxEnrollmentDate with the function sample():

```<code>for(i in seq_along(days)) {
  data[i,4] <- as.character(as.Date(data$MinEnrollmentDate, format="%d/%m/%Y")[i] + sample(1:days[i],1))
}
</code>```

Body:
How to return sample date between min date and max date in R in a dataframe as an additional column?

Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017

Body:
You can compute the number of days between the two dates:

days <- as.Date(data$MinEnrollmentDate, format="%d/%m/%Y") - as.Date(data$MaxEnrollmentDate, format="%d/%m/%Y")

And then add to MinEnrollmentDate a random number between 1 and the number of days to the MaxEnrollmentDate with the function sample():

for(i in seq_along(days)) {
  data[i,4] <- as.character(as.Date(data$MinEnrollmentDate, format="%d/%m/%Y")[i] + sample(1:days[i],1))
}


问:
Shopping List not listing/saving more than 1 recipe
My Aim is

Create a shopping list which is pulling recipes from an API.

Take ingredients from one page to another.

Page to refresh/load data when more than 1 is added.

The issue I am having is

Only 1 set of ingredients load

The clear function will not allow anymore to be added.

Recipe Page

```<code>// Loading Recipes
/////////////////////////////////////////////////////////////////////

loadDetails1(id){
    this.apiAuthentication.loadDetails(id)
    .then(data => {
        this.api = data;
    });
}

// Add to Shopping List
/////////////////////////////////////////////////////////////////////

submit(api) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);

    this.storage.get('myData').then((api) => {

        // add one igredient to the ingredientLines object
        // if it's still a string use JSON.parse() on it
        this.storage.set('myData', api).then(result =>{
            toast.present();
            console.log(api);
        });
    });
}
</code>```

HTML

```<code><h1 (click)="submit(api?.ingredientLines)">Add to shopping list</h1>
<ul>
    <li *ngFor="let item of api?.ingredientLines"><span>{{item}}</span></li>
</ul>
</code>```

Shopping List Page

```<code>getData() {
  this.storage.get('myData').then((data => {
      this.api = data;
      console.log(data);

      setInterval(() => {
        console.log(data);
      },5000);
  }));
}
</code>```

HTML

```<code><ion-content padding>
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>

        <ion-list>
            <ion-item>
                <ul>
                    <li *ngFor="let item of api?.ingredientLines">
                        <ion-label>{{item}}</ion-label>
                        <ion-checkbox></ion-checkbox>
                    </li>
                </ul>
            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(item)">Remove</button>
    </ion-card>
</ion-content>
</code>```

Shopping list page looks like

Error shown in visual is https://www.youtube.com/watch?v=BDS_XTdw2S0
You can see that when I add an item to the shopping list it does not update until i close the app and restart it. Also there is only ever 1 item.

答:
I had to use a template to bind all of these together and create all instances as objects.

.html file

```<code><template ngFor let-api [ngForOf]="shoppingList">
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>
        <ion-list inset>
            <ion-item *ngFor="let ingredient of api.ingredientLines">
                <ion-label>{{ ingredient }}</ion-label>
                <ion-checkbox item-right></ion-checkbox>
            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(api)">Remove</button>
    </ion-card>
</template>
</code>```

and .ts file is

```<code>public submit(api: any) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);
    var thisRecipe = this.api;

    this.storage.get('shoppingList').then((shoppingList) => {
        if(!shoppingList){
            shoppingList = [];
        }

        shoppingList.push(thisRecipe);

        this.storage.set('shoppingList', shoppingList).then(result => {
            console.log("Added to Shopping List", result);
            toast.present();
        });
    });
}
</code>```

Body:
My Aim is

Create a shopping list which is pulling recipes from an API.

Take ingredients from one page to another.

Page to refresh/load data when more than 1 is added.

The issue I am having is

Only 1 set of ingredients load

The clear function will not allow anymore to be added.

Recipe Page

// Loading Recipes
/////////////////////////////////////////////////////////////////////

loadDetails1(id){
    this.apiAuthentication.loadDetails(id)
    .then(data => {
        this.api = data;
    });
}

// Add to Shopping List
/////////////////////////////////////////////////////////////////////

submit(api) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);

    this.storage.get('myData').then((api) => {

        // add one igredient to the ingredientLines object
        // if it's still a string use JSON.parse() on it
        this.storage.set('myData', api).then(result =>{
            toast.present();
            console.log(api);
        });
    });
}

HTML

Add to shopping list

{{item}}

Shopping List Page

getData() {
  this.storage.get('myData').then((data => {
      this.api = data;
      console.log(data);

      setInterval(() => {
        console.log(data);
      },5000);
  }));
}

HTML

<ion-content padding>
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>

        <ion-list>
            <ion-item>

                        <ion-label>{{item}}</ion-label>
                        <ion-checkbox></ion-checkbox>

            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(item)">Remove</button>
    </ion-card>
</ion-content>

Shopping list page looks like

Error shown in visual is https://www.youtube.com/watch?v=BDS_XTdw2S0
You can see that when I add an item to the shopping list it does not update until i close the app and restart it. Also there is only ever 1 item.

Body:
I had to use a template to bind all of these together and create all instances as objects.

.html file

<template ngFor let-api [ngForOf]="shoppingList">
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>
        <ion-list inset>
            <ion-item *ngFor="let ingredient of api.ingredientLines">
                <ion-label>{{ ingredient }}</ion-label>
                <ion-checkbox item-right></ion-checkbox>
            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(api)">Remove</button>
    </ion-card>
</template>

and .ts file is

public submit(api: any) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);
    var thisRecipe = this.api;

    this.storage.get('shoppingList').then((shoppingList) => {
        if(!shoppingList){
            shoppingList = [];
        }

        shoppingList.push(thisRecipe);

        this.storage.set('shoppingList', shoppingList).then(result => {
            console.log("Added to Shopping List", result);
            toast.present();
        });
    });
}