text:
Q: TotalUsers are making double making requests with  GA4 Query Explorer
when i request two dimensions together (appVersion and firstUserCampaignId)
totalUsers returns double values
when i request only one dimenstion, sum of totalUsers returns valid values
does it some bug in GA4?
{"dimensions":[{"name":"appVersion"},{"name":"date"},{"name":"firstUserCampaignId"},{"name":"platform"},{"name":"streamId"}],"metrics":[{"name":"newUsers"},{"name":"totalUsers"}],"dateRanges":[{"startDate":"2023-01-27","endDate":"2023-01-27"}]}
i expect that sum value of totalUsers  will equals with any set of parameters


text:
Q: C# "new" instance instantly disposed of? Relatively new to C#.
I've got a class (public class Functions) that has a public function that I want to be able to access from a different class without creating a new instance of the Functions.
I have a few lines of code very similar to the following:
this.txtENet2GatewayOct1.Text = (new Functions()).GetIPOctet(this.settings.eNet2DefaultGateway, 1);

What I'm curious about is: when I do a (new ClassIMade()).Function, is the "new" instance immediately disposed of (removed from memory).
I'm sure this probably isn't the "proper" way to do this, but for the purposes of this question I don't care.

A: It's not "immediately disposed of". It is eventually released by the garbage collector provided that there is nothing in your code that keeps the object alive.
Creating a new instance inline using new Functions() is nothing different from first instantiating the object and then call the method as far as the GC is concerned.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC4 RegisterGoogleClient to request additional permissions I am very new to MVC, really liking it just getting used to everything.
One thing i would like to implement is the google log in (done) with ability to use the response as a way to get to the calender and the contacts API.
I am trying to find something that would speak to providing an API key with the RegisterGoogleClient method found in the AuthConfi.cs file.
I have registered an app with google and have the key that would request permissions for the calender and contacts. just cant seem to find the missing link for including this key with the RegisterGoogleClien.
Ideally i will be able to get the key passed in, user will see request for permissions to the additional items and then the OAuth key provided will be usable with the GData NuGet packages.
Thanks in advance!
ps- i am guessing i need to use the overload that allows for passing in a dictionary but can not find any documentation on that as well, probably just looking in the wrong place but i have been looking for a few days.

A: At the moment I have the same problem as yours. I can authenticate the user (log in with google), but I cannot retrieve the user contacts. The access_token that is returned from gmail is not valid for accessing the user contacts. I need to authenticate the user, and in the same time to send my client_id and secret of the application that is registered at the google console. Then with that access_token probably I will be able to retrieve the user contacts.
RequestSettings r = new RequestSettings(app, access_token); // how to get the access_token ???
//if i have new RequestSettings(app, user_email, password); it works
ContactsRequest cRequest = new ContactsRequest(r);

Feed<Contact> feedContacts = cRequest.GetContacts(user.email);

List<string> list = new List<string>();
foreach (Contact gmailAddresses in feedContacts.Entries)
{
    // Looping to read email addresses
    foreach (EMail emailId in gmailAddresses.Emails)
    {
       list.Add(emailId.Address);
    }
}


text:
Q: unit test spring controller with WebTestClient and ControllerAdvice I'm trying to unit test my controller and the specific case which is : my service return a Mono.Empty, I throw a NotFoundException and I wan't to make sure I'm getting a 404 exception
here's my controller :
@GetMapping(path = "/{id}")
    public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException {

        return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));

    }

Here's my controller advice :
@ControllerAdvice
public class RestResponseEntityExceptionHandler {

    @ExceptionHandler(value = { NotFoundException.class })
    protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }

}

and my test :
@Before
    public void setup() {
        client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
    }
@Test
    public void assert_404() throws Exception {

        when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());

        WebTestClient.ResponseSpec response = client.get().uri("/api/object/id").exchange();
        response.expectStatus().isEqualTo(404);

    }

I'm getting a NotFoundException But a 500 error not a 404 which mean my advice hasn't been called
stack trace :
java.lang.AssertionError: Status expected:<404> but was:<500>

> GET /api/fragments/idFragment
> WebTestClient-Request-Id: [1]

No content

< 500 Internal Server Error
< Content-Type: [application/json;charset=UTF-8]

Content not available yet

any idea ?

A: I believe you can delete this controller advice and just have the following:
    @GetMapping(path = "/{id}")
    public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) {

        return this.myService.getObject(id, JsonNode.class)
                             .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));

    }

As for ResponseEntityExceptionHandler, this class is part of Spring MVC so I don't think you should use it in a WebFlux application.


text:
Q: Elliptic PDE Integral inequality Suppose $\zeta\in C_0^1(\Omega)$ and $u>0$ in $\overline{\Omega}$.  Suppose $\lambda|\xi|^2\leq a_{ij}(x)\xi_i\xi_j\leq\Lambda|\xi|^2$ for $x\in \Omega$ and $\xi\in\mathbb{R}^n$.
Apparently
$$
\int\frac{\zeta^2}{u^2}a_{ij}D_iuD_ju\leq 2\int\frac{\zeta}{u}a_{ij}D_iuD_j\zeta
$$
implies
$$
\int\zeta^2|D\log u|^2\leq C\int|D\zeta|^2
$$
for some constant dependent on $\Lambda/\lambda$.  However, I fail to see it.  Any hints/suggestions?

A: Use $i = j$. Your first inequality and Holder's inequality lead to
$$ \int \frac{\zeta^2}{u^2} a_{ii} (D_i u)^2 \le 2 \left(\int \frac{\zeta^2}{u^2} a_{ii} (D_i u)^2 \right)^{1/2} \left( \int a_{ii} (D_i \zeta)^2 \right)^{1/2}$$
so that
$$ \int \frac{\zeta^2}{u^2} a_{ii} (D_i u)^2 \le 2\int a_{ii} (D_i \zeta)^2.$$
Since $\lambda \le a_{ii}(x) \le \Lambda$ for each $i$ and $D_i \log u = \dfrac{D_i u}{u}$  you get
$$ \lambda \int \zeta^2(D_i \log u)^2 \le 2 \Lambda \int (D_i \zeta)^2.$$
Now sum over $i$.


text:
Q: Angular Disable Tab I wish to apply a class to a tab which will disable it.
For the the CSS I am using
.not-active {
    pointer-events: none;
    cursor: default;
}

Before seeing the tabbed page, the user is presented with several check boxes. If a check box is not checked, this tab will have the .not-active class applied to it.
For my tabs I have

At the moment I apply the tab-current class when isActiveTab returns true.
However I am a little unsure as what the best approach would be to add the .not-active class based on a checkbox not being selected.
Any guidance would be much appreciated.

A: I suggest to change the tip property with your checkboxes (for example tip.isDisabled). Then it will be really easy to disable tab in your onClickTab callback, you can do there something like this:
$scope.onClickTab = function(tab){
    if (tab.isDisabled) return;
    // do something here
}

How to change tip.isDisabled property? Just use appropriate ng-model for your checkbox:

            <input type=checkbox ng-model='tip.isDisabled'>

A: You can use the checkbox model as an expression inside the ng-class to apply not-active class conditionally. Like

Where checkboxmodel is the ng-model of your checkbox.


text:
Q: Executing program while camera capture Windows Phone 8 SDK I am working on a project which calls a function attached with a timer. However, when the camera capture is active, the function is not called. I suppose this happens since the camera capture task needs to complete before any other task is started. Is there any way to make the timer work even when the camera capture is working? Code snippets would be of great help.
Thank you.

A: If you use the CameraCaptureTask, the app is indeed suspended until the task has ended.
So if you need to have your app running while taking a photo, you should use the Windows.Phone.Media.Capture APIs. Here is a link on MSDN on Advanced photo capture for Windows Phone 8


text:
Q: Check if a list is sorted case insensitive For my intro to Java class I created a method that takes this list and outputs a new sorted list. Now I am trying to create a method that checks if this list is sorted or not (both are case insensitive). I tried to go the easy way and use this.equals(this.sorted()) but it's not working since when I am comparing a already sorted list is outputting false instead of true. I need some guidance. I can't use arrays or loops just recursion.
    import tester.Tester;

   // to represent a list of Strings
    interface ILoString {
        //prodces a new list, sorted in alphabetical order case insensitive
        ILoString sort();
        //helps sort() sort a list
        ILoString sortHelp(String acc);
        //determines whether this list is sorted in alphabetical order,
        //in a case-insensitive way.
        boolean isSorted();
    }
    // to represent an empty list of Strings
    class MtLoString implements ILoString {
        MtLoString(){}

       //prodces a new list, sorted in alphabetical order case insensitive
        public ILoString sort() {
          return this;
    }
        //helps sort() sort a list
        public ILoString sortHelp(String acc) {
          return new ConsLoString(acc, this);
        }

        //determines whether this list is sorted in alphabetical order,
        //in a case-insensitive way.
        public boolean isSorted() {
          return true;
        }
    }

    // to represent a nonempty list of Strings
    class ConsLoString implements ILoString {
        String first;
        ILoString rest;

        ConsLoString(String first, ILoString rest){
            this.first = first;
            this.rest = rest;
        }

        //determines whether this list is sorted in alphabetical order,
        //in a case-insensitive way.
        public boolean isSorted() {
          return this.equals(this.sort());
        }

        //prodces a new list, sorted in alphabetical order case insensitive
        public ILoString sort() {
          return this.rest.sort().sortHelp(this.first);
        }

        //helps to sort the names in this ConsLoString
        public ILoString sortHelp(String acc) {
            if ( acc.compareToIgnoreCase(this.first) < 0) {
              return new ConsLoString(acc, this);
            }
              else {
                return new ConsLoString(this.first, this.rest.sortHelp(acc));
              }

            }

    }

    // to represent examples for lists of strings
    class ExamplesStrings{

        ILoString mary = new ConsLoString("Mary ",
                        new ConsLoString("had ",
                            new ConsLoString("a ",
                                new ConsLoString("little ",
                                    new ConsLoString("lamb.", new MtLoString())))));
        ILoString marySorted = new ConsLoString("a ",
            new ConsLoString("had ",
                new ConsLoString("lamb.",
                    new ConsLoString("little ",
                        new ConsLoString("Mary ", new MtLoString())))));

     // test the method sort for the lists of Strings
        boolean testSort(Tester t){
            return
                t.checkExpect(this.mary.sort(),this.marySorted)&&
                t.checkExpect(this.marySorted.sort(),this.marySorted);
        }

        //test the method isSorted
        boolean testisSorted(Tester t){
          return
              t.checkExpect(this.mary.isSorted(),false)&&
              t.checkExpect(this.marySorted.isSorted(),true);
      }
    }

A: You could try just creating a new list, which is a sorted version of the list your checking. Then you check that sorted list against your original list. If they are equal, then your original list was sorted.
List<String> myStings = new ArrayList<>();
  myStings.add("Mary");
  myStings.add("had");
  myStings.add("a");
  myStings.add("little");
  myStings.add("lamb");

myStings = myStings.stream().map(x -> x.toLowerCase()).collect(Collectors.toList());
List<String> sortedList = myStings.stream().sorted().collect(Collectors.toList());

System.out.println("Unsorted list: " + myStings);
System.out.println("Sorted list: " + sortedList);
System.out.println("Was it a sorted list: " + myStings.equals(sortedList));

The list equals() method checks that both lists are of the same size and that all corresponding pairs of elements in the two lists are equal.
Oh, I've just added a step above to convert all the elements in your list to lowercase. Only difference it'll make in the example above is where the word "Mary" sits in your sorted list, but overall shouldn't make a difference to what you are trying to achieve.
UPDATE:
So the reason this method does not work specifically for your implementation is because you are not actually using Lists (or anything from java.util.Collections for that matter). You've created your own implementation of a linked list. Hence when you use the .equals() method your actually using the default implementation of this method found in java.lang.Object. The default implementation does not check what's in the Object, but rather it checks if the the Objects share the same memory address. Where yoursort() method is returning a sorted list, it's a different object sitting in a different address in memory, hence .equals() will report it as false;
What you need to do is actually check the variables in your object (not the memory address). In order to do so you will need to Override the default implementation of .equals() in your ConsLoString class, because you actually want to do comparisons on the variable first
So it'll look something like this...
@Override
public boolean equals(Object o) {
  ConsLoString toCompare = (ConsLoString) o;
  if(this.first == toCompare.first) {
    if (this.rest != null && toCompare.rest != null) {
      return this.rest.equals(toCompare.rest);
    } else {
      return Boolean.TRUE;
    }
  } else {
    return Boolean.FALSE;
  }
}


text:
Q: Binding several large matrices by column I truly know that 'large matrix issue' is a recurrent topic here, but I would like to explain minutely my specific problem regarding large matrices.
Strictly speaking, I want to cbind several large matrices with a specific name pattern in R. The below code shows my best try until this point.
First lets produce files to mimetize my real matrices:
# The df1
df1 <- '######## infx infx infx
######## infx infx infx
probeset_id sample1 sample2 sample3
PR01           1       2       0
PR02           -1      2       0
PR03            2      1       1
PR04           1       2       1
PR05           2       0       1'
df1 <- read.table(text=df1, header=T, skip=2)
write.table(df1, "df1.txt", col.names=T, row.names=F, quote=F, sep="\t")

# The df2
df2 <- '######## infx infx infx
######## infx infx infx
probeset_id sample4 sample5 sample6
PR01           2       2       1
PR02           2      -1       0
PR03            2      1       1
PR04           1       2       1
PR05           0       0       1'
df2 <- read.table(text=df2, header=T, skip=2)
write.table(df2, "df2.txt", col.names=T, row.names=F, quote=F, sep="\t")

# The dfn
dfn <- '######## infx infx infx
######## infx infx infx
probeset_id samplen1 samplen2 samplen3
PR01           2       -1       1
PR02           1      -1       0
PR03            2      1       1
PR04           1       2       -1
PR05           0       2       1'
dfn <- read.table(text=dfn, header=T, skip=2)
write.table(dfn, "dfn.txt", col.names=T, row.names=F, quote=F, sep="\t")

Then import it to R and write as my expected output file:
### Importing and excluding duplicated 'probeset_id' column
calls = list.files(pattern="*.txt")
library(data.table)
calls = lapply(calls, fread, header=T)
mycalls <- as.data.frame(calls)
probenc <- as.data.frame(mycalls[,1])
mycalls <- mycalls[, -grep("probe", colnames(mycalls))]
output <- cbind(probenc, mycalls)
names(output)[1] <- "probeset_id"
write.table(output, "output.txt", col.names=T, row.names=F, quote=F, sep="\t")

How the output looks like:
> head(output)
  probeset_id sample1 sample2 sample3 sample4 sample5 sample6 samplen1 samplen2 samplen3
1        PR01       1       2       0       2       2       1        2       -1        1
2        PR02      -1       2       0       2      -1       0        1       -1        0
3        PR03       2       1       1       2       1       1        2        1        1
4        PR04       1       2       1       1       2       1        1        2       -1
5        PR05       2       0       1       0       0       1        0        2        1

This code works perfectly for what I want to do, however, I face the known R memory limitation using my real data (more than 30 "df" objects with ~1.3GB or/and 600k rows by 100 columns each).
I read about a very interesting SQL approach (R: how to rbind two huge data-frames without running out of memory) but I am inexperienced in SQL and did not found a way to adaptate it to my case.
Cheers,

A: I had misunderstood the question previously; now the comment made it clear. What you need then is to work with a package like ff. This lets you work with files from your hard disk as opposed to loading them in RAM. This looks like a solution to your problem as you mention that RAM is not enough to load all the files in your system.
First of all load the files with read.table.ffdf and then use the following to cbind them together:
#load files in R
library(ff)

df1 <- read.table.ffdf('df1.txt', header=T, skip=2)
df2 <- read.table.ffdf('df2.txt', header=T, skip=2)
dfn <- read.table.ffdf('dfn.txt', header=T, skip=2)

And then merge like this:
mergedf <- do.call('ffdf', c(physical(df1), physical(df2), physical(dfn)))

Unfortunately, I cannot use your example as read.table.ffdf does not support the text argument, but the above should work. The ff package has its own (not very complex) syntax that you might need to familiarize yourself with as it works with files off of your hard disk. For example apply functions are done using the ffapply function in pretty much the same way as apply.
Have a look here, here and here for some basic tutorials on package ff.
You can also see the functions inside the package and use the in-built help to help yourself with ls(package:ff).


text:
Q: Basic JavaScript array from an array of ruby arrays containing floats I am trying to make a basic heatmap using Google Maps API - https://developers.google.com/maps/documentation/javascript/heatmaplayer
I have an array of arrays of map coordinates I am passing from my rails controller like so:
@coordinates = [[51.60382, 0.02785], [51.6038, 0.02785], [51.60401, 0.02799], [51.60389, 0.02789], [51.60389, 0.02789], [51.60389, 0.02789], [51.60389, 0.02789], [51.60389, 0.02789], [51.60385, 0.02785], [51.60385, 0.02785], [51.60386, 0.02785], [51.60386, 0.02785], [51.60387, 0.02783], [51.60387, 0.02781]]

For each of these arrays I want to create a Google maps LatLng JavaScript object like so:
    new google.maps.LatLng(37.782551, -122.445368),

I can get the array of coordinate arrays through to the view ok however am struggling to create an array of the objects that look like that above.
My most recent attempt:
   var coordinatesArray = <%= @coordinates %>;

      function getPoints() {
        function coordinatesArrayTwo () {
          var coordinatesArrayNew = coordinatesArray.map( c => new google.maps.LatLng(c[0], c[1]) );
          return coordinatesArrayNew;
        };

        return[coordinatesArrayTwo()]

The idea being to iterate through the array of arrays and create a new object inserting the array coordinates...
However this does not seem to work and I am having a hard time viewing what it is actually returning.
I have a feeling it is fairly basic but could anyone help with this?
Thanks

A: I think you have an issue right on this one: var coordinatesArray = <%= @coordinates %>;
I am suggesting to try this one. JSON.parse('<%= @coordinates %>')
or you have to try raw also, JSON.parse('<%= raw @coordinates %>')
var coordinatesArray = JSON.parse('<%= @coordinates %>')

// Sample below: from googleApi Docs.
var heatmapData = coordinatesArray.map( c => new google.maps.LatLng(c[0], c[1]) );
var sanFrancisco = new google.maps.LatLng(37.774546, -122.433523);

map = new google.maps.Map(document.getElementById('map'), {
  center: sanFrancisco,
  zoom: 13,
  mapTypeId: 'satellite'
});

var heatmap = new google.maps.visualization.HeatmapLayer({
  data: heatmapData
});
heatmap.setMap(map);

A: The solution borrows from both Raphael St & 7urkm3n repsonses...

*

*I needed to .to_json the ruby array like so:

 var coordinatesArray = <%= @coordinates.to_json %>;

*I needed to tweak the getPoints function like so:

   function getPoints() {
          var coordinatesArray = <%= @coordinates.to_json %>;
          return coordinatesArray.map( c => new google.maps.LatLng(c[0], c[1]) );
        };

This gives the following to produce the heatmap:
      let map, heatmap;

      function initMap() {
        function getPoints() {
          var coordinatesArray = <%= @coordinates.to_json %>;
          return coordinatesArray.map( c => new google.maps.LatLng(c[0], c[1]) );
        };

        map = new google.maps.Map(document.getElementById("map"), {
          zoom: 13,
          center: {
            lat: 51.603,
            lng: 0.0232
          },
          mapTypeId: "satellite"
        });
        heatmap = new google.maps.visualization.HeatmapLayer({
          data: getPoints(),
          map: map
        });
      }

      function toggleHeatmap() {
        heatmap.setMap(heatmap.getMap() ? null : map);
      }

      function changeGradient() {
        const gradient = [
          "rgba(0, 255, 255, 0)",
          "rgba(0, 255, 255, 1)",
          "rgba(0, 191, 255, 1)",
          "rgba(0, 127, 255, 1)",
          "rgba(0, 63, 255, 1)",
          "rgba(0, 0, 255, 1)",
          "rgba(0, 0, 223, 1)",
          "rgba(0, 0, 191, 1)",
          "rgba(0, 0, 159, 1)",
          "rgba(0, 0, 127, 1)",
          "rgba(63, 0, 91, 1)",
          "rgba(127, 0, 63, 1)",
          "rgba(191, 0, 31, 1)",
          "rgba(255, 0, 0, 1)"
        ];
        heatmap.set("gradient", heatmap.get("gradient") ? null : gradient);
      }

      function changeRadius() {
        heatmap.set("radius", heatmap.get("radius") ? null : 20);
      }

      function changeOpacity() {
        heatmap.set("opacity", heatmap.get("opacity") ? null : 0.2);
      } // Heatmap data: 500 Points

And it works!
Thanks all for the help.

A: I am not entirely sure if it is what you are asking for
function getPoints() {
   return coordinatesArray.map( c => new google.maps.LatLng(c[0], c[1]) );
  };
  new_array = getPoints()


text:
Q: How do I place a widget for Stack Overflow on my WordPress site? I want a Stack Overflow widget on my WordPress site.
How can I do that?

A: The official description is here: https://stackoverflow.com/users/flair

A: html: https://wordpress.stackexchange.com/users/flair


text:
Q: How can we have searched characters colored when we use searchview in recyclerview? I have a recyclerview and I want to search in it with help of searchview. I want my searched characters to be colored and be specific.
I am programming with Kotlin.

A: After a hard effort I found the answer myself. I use a function like this:
fun colorsearch(a:String,charText: String):SpannableStringBuilder{
    var l = 0
    var b:ArrayList<Int>
    b = ArrayList()
    var w = 0
    var i = 0
    if (charText!=""){
        label@ while (i < a.length) {
            var j=0
            while (j<charText.length){
                Log.v("abc", j.toString())
                if (i == a.length)
                    break@label
                while ((a[i] != charText[j])) {
                    if (j != 0) {
                        continue@label
                    }
                    i++
                    if (i == a.length)
                        break@label
                }
                i++
                j++
            }
            b.add(i)
            w++
            if (i == a.length)
                break@label
        }
    }

    val searchtitle = SpannableStringBuilder(a)
    while (l < w) {
        searchtitle.setSpan(
            ForegroundColorSpan(Color.RED),
            b[l] - charText.length, b[l],
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE
        )
        l++
    }
    return searchtitle
}

The "charText" in "a" will be Red.


text:
Q: Firemonkey TCameraComponent settings restoring problem I've problem with TCameraComponent (Delphi Rio 10.3.1), similar to this one:
Firemonkey TCameraComponent quality change when reactivated
but neither accepted answer nor comments suggestion work for me.
procedure TForm1.CameraOn;
begin
  Camera := TCameraComponent.Create(Self);
  Camera.Quality := TVideoCaptureQuality.LowQuality;
  Camera.OnSampleBufferReady := CameraSampleBufferReady;
  Camera.Active := True;
end;

procedure TForm1.CameraOff;
begin
  Camera.Active := False;
  Camera.OnSampleBufferReady := nil;
  //Self.RemoveComponent(Camera);
  //FreeAndNil(Camera);
  Camera.DisposeOf;
  Camera := nil;
end;

Setting quality to Low works only once. Then destroying and recreating TCameraComponent always restores quality settings to default (high). I'm quite aware of ARC issues with destroying objects, but none of methods I know work.


text:
Q: Help me with that CrossThread? This code is executed by many way. When it's executed by the form button it works (the button start a thread and in the loop it call this method = it works). BUT it doesn't work when I have a call to that method from my BackgroundWorker in the form.
With the following code:
private void resizeThreadSafe(int width, int height)
{
    if (this.form.InvokeRequired)
    {
        this.form.Invoke(new DelegateSize(resizeThreadSafe),
            new object[] { width, height });
    }
    this.form.Size = new Size(width, height); // problem occurs on this line
    this.form.Location = new Point(0, 0); // dummy coordinate
}

Then on the line containing this.form.Size = ... I get the following exception:
InvalidOperationException was unhandled
Cross-thread operation not valid: Control 'Form1' accessed from a thread other
than the thread it was created on.

Why?

A: You need to return at the end of the if block - otherwise you'll resize it in the right thread, and then do it in the wrong thread as well.
In other words (if you'd cut and paste the code instead of a picture, this would have been easier...)
private void resizeThreadSafe(int width, int height)
{
    if (this.form.InvokeRequired)
    {
        this.form.Invoke(new DelegateSize(resizeThreadSafe,
            new object[] { width, height });
        return;
    }
    this.form.Size = new Size(width, height);
    this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next
}

Alternatively just put the second half of the method in an "else" block.

A: You need write this:
if ( this.form.InvokeRequired ) {
    this.form.Invoke( ...... );
    return;
}
this.form.Size = new Sizte( ... );

OR
if ( this.form.InvokeRequired ) {
    this.form.Invoke( ...... );
}
else {
    this.form.Size = new Sizte( ... );
}

A: Depending on your coding style either use return right after the Invoke or put the actual action as an else block.


text:
Q: AS3: subtraction not exact i made an array stocking simple values (1,1,2,1...) that represent tiles for a small 2D game.
i want to stock a rotation (and extra) parameters in this array, so i added decimals to my values :
1.45, 1.90, 2.0, 1.90...
for example, 1.45 means that i want a grass tile (1), rotated by 45°.
to "parse" my decimals, i do:
arr[0] = 2.9;
rot = arr[0] - Math.floor(arr[0]);

i should get 0.9, but i get 0.89999 instead.
Any idea why this easy subtraction in AS3 is not correct? Or maybe should i create another array stocking these "extra" parameters?
Thanks for your lights

A: This is an inherent problem of floating point numbers. You could round the number to a given number of decimal places using rot = rot.toFixed(2), or you could just ignore the tiny differences- it would take a lot for them to add up significantly.
As an aside, you can use rot = arr[0] % 1 to get the portion after the decimal.
Storing rotation values using decimals doesn't seem optimal, especially since your way only allows rotation up to 100 degrees. Plus, what if you want to store more values than tile type and rotation? Using multiple arrays (or even an array of objects of a custom class) might be best.

A: Actionscript uses floating point.   Many decimal fractions are not exactly representable.
You could use another array to deal with the extra parameters, or multiply your values by some static value... like 1,000 ?   this would move the extra params unto whole units.  1000 lets you put any 0-359° value in place.  Although you'll have to do the extra parsing to evaluate a carry from subtraction or addition.
Maybe another array would be best... :)

A: You're subtracting Number objects, which in AS3 are floating point. Floating point numbers inherently have accuracy issues. Here is an explanation as to why.
Your easiest solution is to round your answer:
var arr:Array = [];
arr[0] = 2.9;
var rot:Number = Number(arr[0]) - Math.floor(arr[0]);
var rounded:Number = Number(rot.toFixed(1));


text:
Q: Batch file - would like to display a menu of folders in 3 columns 1-column code is below.  I'd like to expand "char" to 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz and then be able to display the options in 3 columns (21 items, 21 items, 20 items).  Folder names over a certain length would have to be truncated.  With 3 columns and potentially long folder names, long folder names would have to be truncated in the menu.
rem Set the number of lines per page, max 29
set "pageSize=29"
set "char=0123456789ACDEFGHIJKLMNOPQRSTUVWXYZ"

rem Load current directory contents
set "numNames=1"
for /D %%a in (*.) do (
   set /A numNames+=1
   set "name[!numNames!]=       %%a"
)

cd ..
set /A numPages=(numNames-1)/pageSize+1

rem Show directory contents, one page at a time
set start=2
:ShowPage
set /A page=start/pageSize+1, end=start+pageSize-1
if %end% gtr %numNames% set end=%numNames%
cls
cd %folder%
echo Page %page%/%numPages% of %CD%
echo/
set "base=1"
set /A lastOpt=pageSize+base, j=base
for /L %%i in (%start%,1,%end%) do (
   for %%j in (!j!) do echo     !char:~%%j,1! -  !name[%%i]!
   set /A j+=1
)

rem Assemble the get option message
set "mssg= (B - Back): "
if %end% lss %numNames% (
   if "%mssg%" equ " (B - Back): " (set "mssg= (") else set "mssg=%mssg%, "
   set "mssg=!mssg!Z=Next page"
)
if "%mssg%" neq " (B - Back): " set "mssg=%mssg%): "

:GetOption
choice /C 0123456789ACDEFGHIJKLMNOPQRSTUVWXYZB /N /M "Choice%mssg%"

I've found batch file solutions to browse files/folders with GUI, but I don't want to do a call to GUI (Explorer) because I'd like to keep everything on the keyboard (slows progress down to switch back and forth between mouse and keyboard all the time).

A: @ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem Set the number of lines per page, max 29
set /a pageSize=29
:: my pagewidth
SET /a pagewidth=120
SET "choicenames=z0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy"

:: remove variables starting #
FOR /F "delims==" %%e In ('set # 2^>Nul') DO SET "%%e="
FOR /L %%e IN (1,1,%pagewidth%) DO SET "#spaces=!#spaces! "

:: Read dirnames to #nn, count to #entries

FOR /d %%e IN ("%~1\*.") DO SET /a #entries+=1&SET "#!#entries!=%%e"
SET /a #entries+=1&SET "#!#entries!=z Quit."
SET /a #columns=(#entries + pagesize - 1) / pagesize
SET /a #rows=(#entries + #columns - 1)/#columns
SET /a #columnwidth=(pagewidth/#columns) - 3
SET "#choices=z"

FOR /L %%e IN (1,1,%#entries%) DO (
 rem column contents - max length + terminal spaces
 IF %%e neq %#entries% (
  SET "#%%e=!#%%e:~-%#columnwidth%!%#spaces%"
  SET "#%%e=!choicenames:~%%e,1! !#%%e:~0,%#columnwidth%!"
  SET "#choices=!#choices!!choicenames:~%%e,1!"
 )
)

FOR /L %%e IN (1,1,%#rows%) DO (
 SET /a cols=%%e + %#rows%
 SET /a #line=%%e + (%#rows% * 2^)
 SET "cols=!cols! !#line!"
 SET "#line=!#%%e!"
 FOR %%y IN (!cols!) DO IF DEFINED #%%y SET "#line=!#line! !#%%y!"
 ECHO !#line!
)

IF %#entries% gtr 36 (
 choice /cs /c %#choices%
) ELSE (
 choice /c %#choices%
)

IF ERRORLEVEL 2 (
 ECHO ERRORLEVEL is %ERRORLEVEL%
 SET /a #choices=%ERRORLEVEL%-1
 CALL SET "userchoice=%%#!#choices!%%"
 ECHO choice made : !userchoice:~2!
) ELSE ECHO QUIT!

GOTO :EOF

This should be a self-adjusting menu.
I chose to make the QUIT choice consistently z


text:
Q: How to detect a click on a form reset button from QtWebKit? Looking at the signals in the QtWebKit API, I failed to find anything that would seem to me to be what I am looking for.

*

*QWebView

*

*linkClicked() seems to be the closest, but a reset button is no link, and definitely does not point to an URL.

*QWebPage

*

*I considered the following signals (judging by their name), but according to their description none of them match my purpose either: contentsChanged(), contentsChanged(), contentsChanged(), selectionChanged().

*QWebFrame

*

*None of its signals matches my purpose.

*QWebElement

*

*Here I can see how to get an object representing the button(s), but it has no signals whatsoever.

I want to catch a click in a reset button in order to store the data in the form before it gets cleared, so it can be restored later.
For now, I did manage to retrieve the buttons as a QWebElementCollection of QWebElement objects, and I can modify them, but I do not know how to get them to send a signal upon click, or something similar.
// Get reset buttons.
QWebElementCollection inputResets = mainFrame()->documentElement().findAll("input[type=reset]");
inputResets += mainFrame()->documentElement().findAll("button[type=reset]");

// Change their text (just a test).
foreach(QWebElement element, inputResets)
{
    element.setPlainText("Worked!");
}

A: Well, I got it working with this, although I do not think it is the best approach:
bool EventFilter::eventFilter(QObject* object, QEvent* event)
{
    if (event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton)
        {
            QWebView *view = dynamic_cast<QWebView*>(object);

            QPoint pos = view->mapFromGlobal(mouseEvent->globalPos());

            QWebFrame *frame = view->page()->frameAt(mouseEvent->pos());
            if (frame != NULL)
            {
                // Get the existing reset buttons.
                QWebElementCollection inputResets = frame->documentElement().findAll("input[type=reset]");
                inputResets += frame->documentElement().findAll("button[type=reset]");

                // Check if any of them is at the clicked position.
                foreach(QWebElement element, inputResets)
                {
                    if (element.geometry().contains(pos))
                    {
                        qDebug() << "Clicked element tag:" << element.localName();

                        return QObject::eventFilter(object, event);
                    }
                }
            }
        }
    }

    return QObject::eventFilter(object, event);
}

A: You can probably accomplish this with Qt WebKit Bridge.


text:
Q: How to parse with Docker bash command a double quoted string multiline? I have something like this in my Docker compose file:
command: >
      bash -c "
        ...some statements here...
        gcloud ...some params... --ddl=\
         \"CREATE TABLE ....; \
          CREATE UNIQUE INDEX...; \
          CREATE UNIQUE INDEX...; \
          CREATE TABLE ...; \
          CREATE TABLE ...; \
          CREATE TABLE ...;\"
      "

the problem here seems that the backslash \ is not working properly within a string "..." where you can see some (truncated for readability) DDL statements. How can I fix that? I tried to replace the \ with \\ and \n\ but none has worked.

A: There is a website that illustrates the different ways to do multi-line strings in yaml, https://yaml-multiline.info, but unfortunately this special case isn't covered in their examples.
The problem you're running into is that in bash, within double quotes, we do not need do escape carriage returns. It's also easiest to remove the escaped line ending in --ddl=\ and move the next double-quote there, so that the quoted text begins at that point. Also, we need to strip the line-endings inside the yaml multi-line syntax using >-. So the result is:
command: >-
    bash -c "
      ...some statements here...
      gcloud ...some params... --ddl=\"
        CREATE TABLE ....;
        CREATE UNIQUE INDEX...;
        CREATE UNIQUE INDEX...;
        CREATE TABLE ...;
        CREATE TABLE ...;
        CREATE TABLE ...;\"
    "

Using dasel we can see that the block of text in the command is interpreted exactly as seen in the yaml:
$ dasel -f test-2.yaml --format '{{ .command }}'
bash -c "
  ...some statements here...
  gcloud ...some params... --ddl=\
   \"CREATE TABLE ....;
    CREATE UNIQUE INDEX...;
    CREATE UNIQUE INDEX...;
    CREATE TABLE ...;
    CREATE TABLE ...;
    CREATE TABLE ...;\"
"

If we copy the full quoted bash -c block and instead use echo, we can see the commands that bash will interpret:
$ echo "
  ...some statements here...
  gcloud ...some params... --ddl=\"
    CREATE TABLE ....;
    CREATE UNIQUE INDEX...;
    CREATE UNIQUE INDEX...;
    CREATE TABLE ...;
    CREATE TABLE ...;
    CREATE TABLE ...;\"
"

  ...some statements here...
  gcloud ...some params... --ddl="
    CREATE TABLE ....;
    CREATE UNIQUE INDEX...;
    CREATE UNIQUE INDEX...;
    CREATE TABLE ...;
    CREATE TABLE ...;
    CREATE TABLE ...;"

What is produced is valid shell syntax. Carriage returns inside of double-quotes do not need to be escaped, and the quoted --ddl= value will be sent across as a valid set of sql statements.


text:
Q: picking a random char from an array I was wondering if there is a way of randomly picking a character from the following array in C but only picking each character once....
const char characters[13][4] =
                    {   'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' ,
                        'J' , 'K' , 'L' ,'M' , 'N' , 'O' , 'P' , 'Q' , 'R' ,
                        'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y', 'Z',

                        'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' ,
                        'J' , 'K' , 'L' , 'M'  , 'N' ,'O' , 'P' , 'Q' , 'R' ,
                        'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y', 'Z'

                    };

A: When you pick a character, just remove it from the set:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char getRandomChar(char *set) {
    size_t len = strlen(set);
    if (len == 0) {
        /* We are all out of characters */
        return -1;
    }
    /* Select a character at random */
    int rv = rand() % len;
    char ret = set[rv];
    /* Remove the selected character from the set */
    set[rv] = set[len -1];
    set[len -1] = '\0';
    /* Return the character */
    return ret;
}

int main(void) {
    char set[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char randomChar;

    /* Intialize random number generator */
   srand((unsigned)time(NULL));

    while ((randomChar = getRandomChar(set)) != -1) {
        printf("Selected %c. Remaining: %s\n", randomChar, set);
    }
    return 0;
}

Note that the code can handle that the same character occurs more than one time. If you want each character to be drawn twice, use the starting set "AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ".

A: If you can modify the characters, then randomly pick a character, if it's not zero (or something) then you have the character and you get it and set the entry to zero (or something). If it is zero (or something) then loop and pick another character.
If you can't modify the original characters, have another "array" that contains a boolean value if a certain character has been picked or not. It should mirror the dimensions of the characters arrays and you check that if a character has been picked or not.


text:
Q: How can I access the Mac Native Dialog Box The application I'm using uploads a file with the Native Mac Dialog Box.  I can't seem to get Puppeteer to move around this box.  I have tried using process.on(dialog), page.keyboard.press & robotjs but none of those options seem to be able to access this dialog box.
process.on is never triggered
page.keyboard doesn't do anything and I figure because the box is not on the page
robotjs.. I'm not sure why that isn't working either.
Does anyone have any other suggestions or working solutions I can try?

page.on('dialog', async (dialog) => {
    await robot.keyTap('tab');
    await robot.typeString(filename);
    await robot.keyTap('tab');
    await robot.keyTap('tab');
    await robot.keyTap('down');
    await robot.keyTap('enter');
});

A: The only way to get around the dialog is by using the dialog argument. e.g.:
page.on('dialog', dialog => {
    dialog.accept();
    //if it's a prompt
    dialog.accept('Foo');
    //or
    dialog.dismiss();
});

A: This is not possible. This dialog cannot be accessed from within puppeteer.
Alternative Solution
Instead of clicking on the button that opens the file dialog, you need to use elementHandle.uploadFile to place the file into the form:
const fileInputField = await page.$('#SELECTOR-OF-FILE-INPUT');
await fileInputField.uploadFile('PATH/TO/YOUR.FILE');


text:
Q: Hosting Wordpress with docker on Azure I created an Azure deployment using Docker's "wordpress + mysql" template. I need to edit the wp-config.php file, but I can't find it anywhere on the file system. Can someone help point me to this?

A: The reason you are not seeing this file, is that it lives inside the docker container's file system.
Here are the steps you need to do to find this file:

*

*SSH into your VM running the Docker containers

*List all running containers: docker ps - get the CONTAINER ID of the container with NAME 'wordpress'

*Start a bash inside the wordpress container: docker exec -i -t 6095ee8642410f77ce8a5f9628b55e23a349e6f744111b2fa9abf1b9fe6b035f bash

*Presto - you now have a bash prompt inside your running docker container. Here you can list files with ls and find the wp-config.php file you are looking for.


text:
Q: React Redux - load response data before render Can someone please help me with this. I can see the response from api but when the page renders, response is too late to render. I could not find what I'm doing wrong. I would really appreciate if someone could explain. Thanks
Below is my reducer
    export default function reducer(state = {
  responseCode : {
  },
  fetching: false,
  fetched: false,
  error: null
}, action){
  switch(action.type){
    case 'FETCH_RESPONSECODE_PENDING' : {
      return { ...state, fetching: false}
      break;
    }
    case 'FETCH_RESPONSECODE_ERROR' : {
      return { ...state, fetching: false, error: action.payload }
    }
    case 'FETCH_RESPONSECODE_FULFILLED' : {
      return{
        ...state,
        fetching: false,
        fetched: true,
        responseCode: action.payload
      }
      break;
    }
  }
  return state;
}

//SearchResponseCode Component
    handleSearch(event){
    event.preventDefault();
  }

render(){
    return (
      <form>

          <input type="number" className="form-control" placeholder="e.g. main mailing response code or recruitment campaign code" ref="responseCode" />

          <button className="btn btn-default" onClick={this.handleSearch.bind(this)}>Search</button>

      </form>

    )
  }

//Main Component
import SearchResponseCode from './search-response-code'
import { connect } from 'react-redux'
import { fetchResponseCode } from '../../actions/responseCodeActions'

@connect((store)=>{
  return{
    responseCode: store.responseCode.responseCode
  };
})
  fetchResponseCode(){
    this.props.dispatch(fetchResponseCode(brandUrl, 2570010))
  }

  render(){
    const { responseCode } = this.props
    console.log(this.responseCode)
    return(
      <Tabs selectedIndex={0}>
        <TabList>
          <Tab>Search By Responce Code</Tab>
          <Tab>Search By Item Code</Tab>
          <Tab>Searh All</Tab>
        </TabList>
        <TabPanel>
          <SearchResponseCode fetchResponseCode={this.fetchResponseCode.bind(this)} />
        </TabPanel>
        <TabPanel>
          <SearchItemCode />
        </TabPanel>
        <TabPanel>
        </TabPanel>
      </Tabs>
    )
  }
}

//Action
import axios from 'axios'

export function fetchResponseCode(brandUrl, responseCode){
  let url = brandUrl + '/api/offer/' + responseCode;

  return function(dispatch){
    axios.get(url)
      .then((response) => {
        dispatch({
          type : 'FETCH_RESPONSECODE_FULFILLED',
          payload : response.data
        })
      })
      .catch((err) => {
        dispatch({
          type : 'FETCH_RESPONSECODE_ERROR',
          payload : err
        })
      })
  }
}

A: *

*why you want to hold the render until data comes .Thats wrong practice and makes your webapp slower.

*and beauty of react is as data comes it updates the part of the View and you can see the data.

*you can send data as prop to other component and place a check where you want to load your async data to avoid errors ,something like this -

//suppose you will get an address object from api ,which will contain city ,area ,street ,pin code etc
// address={} intially address is a blank object
render(){
    return(
        (typeof address.area!='undefined')?

{address.city}

{address.street}

{address.pin_code}

{address.area}

        :
loading....

    )
}

*

*follow this approach ,in this way user can see something in fraction of
seconds,instead of waiting for fulldata to come

*above is just one way ,if you could explain yourcode more ,i might able to help

A: Nothing will happen since you're not invoking anything inside your SearchResponseCode.handleSearch.
You'll need to call the fetchResponseCode inside that function.
//SearchResponseCode component
handleSearch(e) {
  e.preventDefault();
  const input = this.refs.responseCode.value; //you should avoid using ref="string"
  this.props.fetchResponseCode(input);
}

Of course you'll need to modify your fetchResponseCode method inside your main component to accept the parameter and pass it to the action to dispatch.
Hope this helps.

A: I know the question got answer but I came with a very nice solution which I want to share.I hope it might help many coders which are seeing my answer as the problem was frustrating to me as well but I concluded with a great way!
Do you know "optional chaining" if not see this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

for any data which is undefined on first render while using redux.

I will take the example of my friend @rajatGupta

//suppose you will get an address object from api ,which will contain city ,area ,street ,pin code etc
// address={} intially address is a blank object
render(){
    return(
        address?.area?

{address.city}

{address.street}

{address.pin_code}

{address.area}

        :
loading....

    )
}

Notice this portion only : address?.area
I used optional chaining if the data is undefined the app will not crash and if there comes some value in the "address.area", you can use it in the desired way.


text:
Q: Functions, limits and derivatives Let $f(x)$ be a real valued differentiable function on the real line $\mathbb{R}$ such that when
$\lim\limits_{x\to0} \frac{f(x)}{x^2}$ exists, and is finite. Prove that $f'(0) = 0$

A: Well,
$\lim\limits_{x\to 0} \frac{f(x)}{x^2}=l$ $\implies$ $\lim\limits_{x\to 0}f(x)=l\times\lim\limits_{x\to 0} x^2$ $\implies$ $\lim\limits_{x\to0}f(x)=0$.
and according to the ability of the differentiation : $\lim\limits_{x\to0}f(x)=f(0)=0$
Hence, $f'(0)=0.$
Notice :
$f'(0)=\lim\limits_{x\to0}\frac{f(x)-f(0)}{x}=\lim\limits_{x\to0}\frac{f(x)}{x}=\lim\limits_{x\to0}\frac{x\times f(x)}{x^2}=\lim\limits_{x\to0}x\times \lim\limits_{x\to0}\frac{f(x)}{x^2}=0\times l=0$


text:
Q: Is my router's IP address really public? I have a common home network consisting of a wireless router with many devices connected to it. I understand that because of NAT, all devices attached to the router connect to the outside of it via its IP address, with varying NAT ports.
Is the router's IP address really public? Or is there another level of NAT in my ISP's network? Is there a way to determine this?

A: *

*Connect to your router's admin interface, and check the "public" or "WAN" IP address.

*Then connect to a site like https://whatismyipaddress.com/ to check what IP address is visible from the Internet.

If both match, your router's IP is indeed public, and there is no other level of NAT.
If the two addresses don't match, then there is another level of NAT done by your ISP, something called "Carrier-Grade NAT" (CGNAT).
Whether CGNAT is used depends a lot on ISPs. Mobile/wireless ISPs use it a lot. Fixed-line (DSL, Cable, etc.) ISPs use it less, but this can vary a lot from country to country and ISP to ISP.

A: Yes, your IP is public. Most ISPs that I've seen, the IP address rotates rarely. In other words, your IP is public, every website you visit can see it, and it almost never changes.
You can check your IP address by googling "What is my IP" or https://whatismyipaddress.com/. You can see, there, what every other website sees.
Your phone number is also public. Most people you call can see your number. Anyone can call your number.

A: A router has multiple IPs. Its public IP is, of course, public. That is the address that you give to any website you connect to so the server knows where to send a reply. A router also has a gateway IP, which is typically the address on your LAN which other devices behind the router see. This IP is private in that it does not exist on the public internet, but it is not secret (most people use the same range).

My question is, is the router's IP really public?

It is public, but you don't have to worry about it. Knowledge of an IP address is typically not a problem unless you need anonymity. You don't have to worry about being hacked or tracked down based on IP. I explained in another answer why there's no need to worry about having a public IP address. If the address wasn't public, then you wouldn't be able to hear a response from any site you connect to!

Or is there another level of NAT in my ISP's network?

Some ISPs have another level of NAT called Carrier-Grade NAT, or CGN. If your public address as seen by the router (not by websites that check your IP) is in the range of 100.64.0.0/10 (see RFC 6598), then you are most definitely using CGN. If you have any doubts, call your ISP and ask them.

A: Command traceroute (tracert on Windows) may help.
Run traceroute www.google.com, if you get
1 192.168.x.1 (your router's LAN IP)
2 100.x.x.x (ISP's NAT)
3 x.x.x.x (some public IP)
4 x.x.x.x (some public IP)
......

If ISP has another level of NAT, it ususally gives you an IP 100.x.x.x (100.64.0.0/10)


text:
Q: Can Typescript generic types be reused in multiple places? I have some code with a complex set of generics that I need to use in multiple places. Is there a way to reuse the same generics in multiple places? Or some other good way to simplify the type definitions in this example:
type OSD<T, V> = { [K in keyof T]?: V };

export interface CommandProps<
    ReqQ extends OSD<ReqQ, string> | undefined,
    ReqH extends OSD<ReqH, string> | undefined,
    ReqB extends OSD<ReqB, unknown> | undefined,
    ResH extends OSD<ResH, string> | undefined,
    ResB extends OSD<ResB, unknown> | undefined,
> {
    queryParametersSchema: ReqQ extends undefined ? undefined : Schema;
    requestHeadersSchema: ReqH extends undefined ? undefined : Schema;
    requestBodySchema: ReqB extends undefined ? undefined : Schema;
    responseHeadersSchema: ResH extends undefined ? undefined : Schema;
    responseBodySchema: ResB extends undefined ? undefined : Schema;
}

export default class Command<
    ReqQ extends OSD<ReqQ, string> | undefined,
    ReqH extends OSD<ReqH, string> | undefined,
    ReqB extends OSD<ReqB, unknown> | undefined,
    ResH extends OSD<ResH, string> | undefined,
    ResB extends OSD<ResB, unknown> | undefined,
> {
    readonly queryParametersSchema: ReqQ extends undefined ? undefined : Schema;
    readonly requestHeadersSchema: ReqH extends undefined ? undefined : Schema;
    readonly requestBodySchema: ReqB extends undefined ? undefined : Schema;
    readonly responseHeadersSchema: ResH extends undefined ? undefined : Schema;
    readonly responseBodySchema: ResB extends undefined ? undefined : Schema;

    constructor(props: CommandProps<ReqQ, ReqH, ReqB, ResH, ResB>, queryParameters: ReqQ, requestHeaders: ReqH, requestBody: ReqB) {
        this.queryParametersSchema = props.queryParametersSchema;
        this.requestHeadersSchema = props.requestHeadersSchema;
        this.requestBodySchema = props.requestBodySchema;
        this.responseHeadersSchema = props.responseHeadersSchema;
        this.responseBodySchema = props.responseBodySchema;
    }

    // ... Other methods that use all of these fields
}

Playground example


text:
Q: Laravel Vuejs and Typescript -> npm run watch throws exception my setup in short:
laravel 8
typescript
vuejs
tsconfig.js
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "include": [
        "resources/js/**/*",
    ]
}

webpack.mix.js
const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .js('resources/js/pages/user/configuration/configuration.js', 'public/js/pages/user/configuration')
    .postCss('resources/css/app.css', 'public/css')
    .postCss('node_modules/animate.css/animate.min.css', 'public/css')
    .sass('resources/sass/toolbox.scss', 'public/css')
    .vue()
    .webpackConfig({
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    loader: 'ts-loader',
                    options: { appendTsSuffixTo: [/\.vue$/] },
                    exclude: /node_modules/,
                }
            ]
        },
        resolve: {
            extensions: ["*", ".js", ".jsx", ".vue", ".ts", ".tsx"]
        }
    });

ConfigurationPage.vue
<template>
    <div class="col col-12 col-xl-6 d-flex tb-m-b-25">
        {{ greeting }}
    </div>
</template>

<script lang="ts">

import { ref } from 'vue'

export default {
    setup() {
        const greeting= ref('hello');

        return {
            greeting
        }
    }
}
</script>

<style></style>

DevDependencies in my package.json:
  "devDependencies": {
    "@vue/compiler-sfc": "^3.0.11",
    "axios": "^0.21.1",
    "cross-env": "^7.0",
    "laravel-mix": "^6.0",
    "lodash": "^4.17.21",
    "postcss": "^8.3.0",
    "resolve-url-loader": "^3.1.0",
    "sass": "^1.29.0",
    "sass-loader": "^8.0.2",
    "ts-loader": "^9.2.2",
    "typescript": "^4.3.2",
    "vue-loader": "^16.2.0",
    "vue-template-compiler": "^2.6.13"
  },

file/folder structur
resources
 | js
 | | pages
 | | | user
 | | | | configuration
 | | | | | - configuration.js
 | | | | | - ConfigurationPage.vue
 | - app.js
 | - init.ts

The init.ts is empty. If i don't have at least one .ts file in my resources folder, the ts-loader throws an exception, says it cant find something to compile. I was reading, it's common to use an empty typescript file.
The Problem
Every time i make a change in ConfigurationPage.vue i got this execption in npm run watch-poll:
✖ Mix
  Compiled with some errors in 510.02ms
ERROR in /var/www/resources/js/init.ts
2:7-13
[tsl] ERROR in /var/www/resources/js/init.ts(2,8)
      TS2339: Property '__file' does not exist on type '{}'.
webpack compiled with 1 error

I dont get it, the init.ts is empty. It makes no sense to me.

A: You are using an app.js file as the entry-file. Changing this to app.ts resolved this issue.
also in webpack.mix.js
.vue() replace to
.vue({ version: 3 })


text:
Q: java.lang.RuntimeException: An error occured while executing doInBackground() URI i am new to android programming
i am trying to write code for a app
i am trying to use URI
but it keeps giving the following error
looking for help
java file
package com.example.ayushspc.digilocker;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class GetRegDetails extends AppCompatActivity {
    Register register = new Register();
    EditText ET_MOBILE, ET_EMAIL;
    String json_string;
    JSONArray jsonArray;
    JSONObject jsonObject;
    String name, branch, email, mobile, enroll, OTP;
    OTPGenerator otpGenerator;
    Sendsms sendsms;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        otpGenerator = new OTPGenerator();
        sendsms = new Sendsms();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_reg_details);

        enroll = register.enroll;
        json_string = getIntent().getExtras().getString("jsonresult");

        try {
            jsonObject = new JSONObject(json_string);
            jsonArray = jsonObject.getJSONArray("server_response");
            int count = 0;
            while (count < jsonArray.length()) {
                JSONObject JO = jsonArray.getJSONObject(count);
                name = JO.getString("name");
                branch = JO.getString("branch");
                count++;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        TextView tv_name = (TextView) findViewById(R.id.ver_name);
        TextView tv_branch = (TextView) findViewById(R.id.ver_branch);
        tv_name.setText(name);
        tv_name.setVisibility(View.VISIBLE);
        tv_branch.setText(branch);
        tv_branch.setVisibility(View.VISIBLE);

    }

    public void verifyDetails(View view) {
        ET_MOBILE = (EditText) findViewById(R.id.ver_mobile);
        ET_EMAIL = (EditText) findViewById(R.id.ver_email);
        mobile = ET_MOBILE.getText().toString();
        email = ET_EMAIL.getText().toString();
        OTP = otpGenerator.generator();
        String number = mobile.toString();
        // sendsms.message(number, OTP);//add enrollment number to message;pass mesage as an argument
        Toast.makeText(getApplicationContext(), mobile + " " + OTP, Toast.LENGTH_SHORT).show();
        new BackgroundTask().execute(enroll, mobile, email, OTP);
        Toast.makeText(getApplicationContext(), OTP, Toast.LENGTH_LONG).show();

    }

    class BackgroundTask extends AsyncTask<String, Void, String> {
        String otp_url = "http://www.digiloc.esy.es/otp_verification.php";

        @Override
        protected String doInBackground(String... params) {
            String enrollment, mobile, email, otp;
            enrollment = params[0];
            mobile = params[1];
            email = params[2];
            otp = params[3];

            try {
                URL url = new URL(otp_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String data = URLEncoder.encode("enroll", "UTF-8") + "=" + URLEncoder.encode(enrollment, "UTF-8") + "&" +
                        URLEncoder.encode("mobile", "UTF-8") + "=" + URLEncoder.encode(mobile, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                        URLEncoder.encode("otp", "UTF-8") + "=" + URLEncoder.encode(otp, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

Log file
02-06 22:12:05.140  11850-12852/com.example.ayushspc.digilocker E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.NullPointerException
            at libcore.net.UriCodec.encode(UriCodec.java:132)
            at java.net.URLEncoder.encode(URLEncoder.java:57)
            at com.example.ayushspc.digilocker.GetRegDetails$BackgroundTask.doInBackground(GetRegDetails.java:102)
            at com.example.ayushspc.digilocker.GetRegDetails$BackgroundTask.doInBackground(GetRegDetails.java:84)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
02-06 22:12:05.400  11850-11850/com.example.ayushspc.digilocker E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)

can someone possibly point out the cause of error
 and also a way to solve it

A: enroll = register.enroll;

register.enroll returns null. Show Register class or try to find a problem by yourself.


text:
Q: Get GetInvocationList of a public static event via reflection I have a class which contains public static event, and I need to find out if it has handler attached to it or not. I know that I can use GetInvocationList() (if event is not static then I can find it by GetField() method) but the issue is that the event is static and I cannot seem to get a value by using reflection.
public class Business
{
  public static event EventHandler MyEvent;
}

I need to get event handlers of this event but from another class:
public class MyClass
{
  public void Test()
  {
    FieldInfo fieldInfo = typeof(Business).GetField("MyEvent", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
    // fieldInfo is null!!
    Delegate del = (Delegate)fieldInfo.GetValue(null);
    var list = del.GetInvocationList();
  }
}

I cannot get it to work to have fieldInfo returned with value instead of null!

A: Since Business is your own class using reflection seems unncessary, that is why I would suggest just doing a simple method to get the information needed.
eg.
public class Program
{
    public static void Main()
    {
        Business.MyEvent += MyFancyEventListener;
        var xyz = Business.MyEventsInvocationList();
        foreach (var x in xyz)
            Console.WriteLine(x);
    }

    private static void MyFancyEventListener(object sender, EventArgs args)
    {

    }
}

public class Business
{
    public static event EventHandler MyEvent;

    //add this method to your class
    public static IEnumerable<Delegate> MyEventsInvocationList() => MyEvent.GetInvocationList();
}


text:
Q: Will using aarch64-none instead of aarch64-elf yield any benefit in Bare Metal? I am following along an Rpi 3 bare metal tutorial.  I've spent a good amount of time on bare metal with the Rpi A+ and Zero using Dave Welche's excellent repo and other source as well.
The great thing about this Rpi 3 tutorial is
1) it's 64 bit
2) it's multi core

With my surface level understanding, I know that aarch64-elf will build a "binary" that's loadable by an OS that uses the ELF file format, such as any Unix based (Linux, OSX).
Whereas the aarch64-none is meant for bare metal, meaning it won't create any OS loader info into the resulting binary.
What's confusing is that Rpi 3 tutorial build their tool chain as aarch64-elf.
If you look at line 40 of the make file, he still ends up doing an objcopy which I think will strip away any ELF related info anyhow, correct?
So my question: is it worth it to go through and change their Makefiles to aarch64-none in every single example? They also didn't do a good job of making that a param unfortunately!
Is there any added benefit when in bare metal to aarch64-none? I am still going to have to do the objcopy anyways, correct?

A: I am answering your questions in a different order because some answers have direct implications for others.1) I am still going to have to do the objcopy?
Yes.
2) Is there any added benefit when in bare metal to aarch64-none?
None I would be aware of.  ARM Trusted Firmware and u-boot are compiling fine with aarch64-elf for example.
3) Is it worth it to go through and change their Makefiles to aarch64-none in every single example?
I would say it is not. I would rather suggest to download and install the Linaro aarch64-elf toolchain from here:
Download gcc-linaro-7.2.1-2017.11-i686_aarch64-elf.tar.xz if your compiling system is running a 32 bits version of Linux, and gcc-linaro-7.2.1-2017.11-x86_64_aarch64-elf.tar.xz if it is running a 64 bits one.
Installation procedure (x86_64 Linux):
mkdir -p /opt/linaro
wget https://releases.linaro.org/components/toolchain/binaries/latest/aarch64-elf/gcc-linaro-7.2.1-2017.11-x86_64_aarch64-elf.tar.xz
tar Jxf gcc-linaro-7.2.1-2017.11-x86_64_aarch64-elf.tar.xz -C /opt/linaro
export PATH=/opt/linaro/gcc-linaro-7.2.1-2017.11-x86_64_aarch64-elf/bin:$PATH

aarch64-elf-gcc  --version
aarch64-elf-gcc (Linaro GCC 7.2-2017.11) 7.2.1 20171011
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


text:
Q: How to add color to bash output of `git diff --name-status` by file status? I would like to style the bash output for git diff --name-status so that the files with status D, M, and A are different colors.
To style general git bash I use the color options in .gitconfig.
# .gitconfig
[color]
  branch = auto
  diff = auto
  status = auto
[color "branch"]
  current = yellow reverse
  local = yellow
  remote = green
[color "diff"]
  meta = yellow bold
  frag = magenta bold
  old = red bold
  new = green bold
[color "status"]
  added = yellow
  changed = green
  untracked = cyan

To style an output for a command like git log I can use --pretty=format in an alias like below:
# .gitconfig
[alias]
  log = log --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'

However, I have been unsuccessful using --pretty=format for git diff --name-status.
The output I would like to style is currently not styled and looks like:
$ git diff <branch> --name-status
M       .gitignore
M       README.md
A       diagnostic.js
D       diagnostic.md

Is there a way to style the output git diff --name-status by status type?

A: I'm not sure you can colorize the output of --name-status without entirely reproducing its output with --pretty=format:...
But if you want file names with colors summarizing changes, the --stats flag can be passed to many commands, including git diff <branch --stat and git log --stat.
It shows file names, with a colorized +++-- suffix, e.g.
$ git diff master --stat
 lib/thing.go      |  5 +++--
 lib/thing_test.go | 23 +++++++++++++++++++++++
 2 files changed, 28 insertions(+), 2 deletion(-)

and the +s and -s will colorize according to your git config

A: If you really really need colour in your life this might work:
# pick your colours
Red='\033[0;31m'; Colour_Off='\033[0m'; Cyan='\033[0;36m';

# find another branch (you could enter <branch>)
BRANCH=$(git br|grep -v '*');

# take the output of git diff and pain the first column red and the reset cyan.
git diff $BRANCH --name-status|awk "{print \"$Red\" \$1 \"\t\" \"$Cyan\" \$2 \"$Colour_Off\"}"

You could create an alias for this in bash or a paint.sh


text:
Q: compact(): Undefined variable: operator I'm getting the following error
  (1/1) ErrorException
  compact(): Undefined variable: operator

This is my line of code
$postsCat = Post::whereHas('Cat', function($query) use ($sreachWord) {
    return $query->whereRaw('name REGEXP"'.sql_text_to_regx($sreachWord).'"');
})->orderBy('top','desc')
->orderBy('updated_at','desc')
->paginate(30);

Why is this happening? Is it because of my PHP version (7.3) or something else?

A: Please refer to this
https://github.com/laravel/framework/issues/26936
The version of Laravel would need to be updated.

A: There are 2 fixes for this issue

*

*Downgrade your php to 7.2

*run "composer update" as in latest Laravel this issue has been resolved.

A: Go to your project in
vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php

On line number 1337, you can found below code inside the addWhereExistsQuery method
$this->wheres[] = compact('type', 'operator', 'query', 'boolean');

You just remove the 'operator' parameter.
And I hope it will work fine.

A: Instead of passing the variable to the compact() method, you'll passe it the name of the variable as a string without the dollar symbol.
$postsCats = Post::all(); // example

return view('posts.index', compact('postsCats'));

A: If you are not able to upgrade your Laravel, you just could change your Query to RAW query, it worked for me.

A:   $posts = Post::latest()->get();
            return view('author.post.index', compact('posts'));

A: Latest PHP version doesn't allow use of undefined variables. Instead of removing the latest version, another option is to switch between versions. Install earlier version say PHP7.2 as outlined here. Then set this as the preferred version by running sudo update-alternatives --set php /usr/bin/php7.2 on your Ubuntu terminal. Then run composer update


text:
Q: Angular passing css to child component - best practice I wonder what is a good practice of styling elements inside of child components from parent component level. I generally do it in 2 different aproaches:
1.Using /deep/ Plunker
Benefits:

*

*Less code

*We use only css to style elements

Disadvantages:

*

*We cannot use properties from typescript like in a 2nd approach

*We break component hermetization

2.Using input in child component Plunker
Benefits:

*

*We can use properties from typescript

*We don't break component hermetization

Disadvantages:

*

*More code and complicated - the deeper child, the more passes

*We sometimes don't need logic - but we are forced to write in .ts instead of using pure css mechanism

As you can see I have found pros and cons for both ways. I feel like answer might be "It depends" or maybe I miss another approach.


text:
Q: Plotting [x,y] using matplotlib I am trying to plot a scatter plot for knn using the below code, its giving following error:

TypeError: zip argument #1 must support iteration

l = [[[0.676, 1.064], [0.828, 1.038], [0.913, 0.82], [0.857, 0.948], [0.723, 1.064], [0.792, 0.888], [0.881, 1.036], [0.872, 0.893], [0.748, 0.965], [0.837, 0.883], [0.841, 0.925], [0.805, 0.875], [0.87, 1.068], [0.831, 0.859]], [[0.764, 0.899], [0.774, 0.875], [0.573, 0.896], [0.728, 0.916], [0.795, 0.724], [0.736, 0.845], [0.753, 0.837], [0.842, 0.778], [0.54, 0.841]], [[0.245, 0.243], [0.322, 0.219], [0.334, 0.159], [0.211, 0.136], [0.161, 0.305], [0.174, 0.079], [0.057, 0.073], [0.321, 0.139], [0.225, 0.208], [0.253, 0.18], [0.37, 0.068], [0.435, 0.222], [0.258, 0.091], [0.421, -0.095], [0.354, 0.056], [0.253, 0.137], [0.214, 0.194], [0.289, 0.012], [0.229, 0.142], [0.469, 0.319], [0.248, 0.332], [0.372, 0.381], [0.328, 0.243], [0.318, 0.257], [0.389, 0.1], [0.146, 0.152], [0.351, 0.165], [0.453, 0.124], [0.375, 0.078], [0.156, 0.027], [0.156, 0.19], [0.285, -0.107], [0.298, 0.069], [0.269, 0.124], [0.239, 0.082], [0.388, 0.132], [0.324, 0.015], [0.32, 0.013], [0.22, 0.201]], [[0.366, 0.772], [0.225, 0.757], [0.246, 0.498], [0.266, 0.828], [-0.028, 0.868], [0.162, 0.536], [0.224, 0.552], [0.206, 0.876], [0.125, 0.679], [0.105, 0.593], [0.219, 0.639], [0.106, 0.675], [0.216, 0.666], [0.227, 0.651], [0.297, 0.447], [0.18, 0.695], [0.051, 0.577], [0.227, 0.682], [0.265, 0.699], [0.121, 0.643], [0.062, 0.652], [0.278, 0.696], [0.173, 0.698], [0.27, 0.745], [0.207, 0.658], [0.324, 0.635], [0.076, 0.756], [0.142, 0.541], [0.073, 0.601], [0.104, 0.682], [0.086, 0.747], [0.091, 0.687], [0.091, 0.765], [0.187, 0.564], [0.233, 0.958], [0.217, 0.52], [0.274, 0.804], [0.357, 0.828]]]

plt.scatter(*zip(*l), c='r', s=100)

A: You data are in a list of lists of lists and trying to get a scatterplot out of them may require that you flatten the main list into a list of lists; thereby reducing the dimensions to 2D. While the following is not the only way to get a scatterplot out of your data, it still remains a decent starting point:
import matplotlib.pyplot as plt
from functools import reduce

plt.scatter(*zip(*reduce(lambda x,y: x+y, l)), c='r', s=100)
plt.show()

There are endless other ways to reduce the dimensions of l. This one just happens to be neat to me.
I hope this helps.


text:
Q: Getting url from Database and putting as an image for UITableView All,
I need to assign a picture to a UITableView. Each row has a different picture. The data for each row comes from a database and a row on that database has an ID, the ID in another database is linked and that has a URL in that table for the image.
So within cellforRowAtIndexPath we have :
NSDictionary *postValues = @{@"myParam": apt[@"barID"]};
    // Do any additional setup after loading the view, typically from a nib.
    self.client = [MSClient clientWithApplicationURLString:@"https://outnight-mobile.azure-mobile.net/" applicationKey:@"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:@"photos"
                  body:postValues
            HTTPMethod:@"POST"
            parameters:nil
               headers:nil
            completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
                if (error) {
                    NSLog(@"Error %@", error );
                } else
                {
                    NSString *string = [NSString stringWithFormat:@"%@", [result objectForKey:@"rows"]];
                    NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
                    NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:@"(" withString:@""];
                    NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                    NSString *newStr = [completion substringFromIndex:1];
                    NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
                    NSLog(@"%@", finalstring);
                    [cell.imageView setImageWithURL:[NSURL URLWithString:finalstring] placeholderImage:[UIImage imageNamed:@"greybox40.png"]];

                }
            }];

That brings in the url from the table, which was JSON and I removed all the tags to get a string thats just http://blag.com/bah.jpg' This is the easy bit.
I am using SBWebImage for putting the image in the uitableview async which is fine too. What is the  best way of putting the images on each row from the url. is it best with a SWITCH statement ? Is it best with an array of URL's and then displaying them. Is it best to move the database connectivity from cellforIndexRowPath? Can anyone advice please ?

A: first of all create a custom view cell for the uitableview. And then add subviews like images, labels to the custom cell.Get the data from the database to an array of images, arrays of ID'sIn the tableview delegate methods at cellforrowatindex use the code.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    static NSString *CellIdentifier = @"Cell";
    if(tableView == myTableView){
        FirstViewCustomCell *cell = (FirstViewCustomCell *)[myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            [[NSBundle mainBundle] loadNibNamed:@"FirstViewCustomCell" owner:self
                                        options:nil];
            cell = customCell;
            customCell = nil;
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
      //Get the data from the database.
      cell.customimage.image = [imagesarr objectatIndex:indexpath.row];
      cell.textlabel.text = [arrayofID objectatIndex:indexpath.row];
}

A: Parse the data seperately..in an method and then
Store images in an array..As you want top three images..
If you are saving the urls of image in an object and then array..Use below code
    for(int i=0;i<3;i++)
    {
    ImagesObject *Obj=[imagesArray objectAtIndex:i];

            [cell.userProfilePicImage setImageWithURL:[NSURL URLWithString:Obj.imageURLString]
                                     placeholderImage:[UIImage imageNamed:@"greybox40.png"]
                                            completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
             {
                 if (!error && image)
                 {

                 }
             }];
        }

        (or) if you are not saving in an object then use below code.

for(int i=0;i<3;i++)
    {

        NSString *imageURLString=[imagesArray objectAtIndex:i];

                [cell.userProfilePicImage setImageWithURL:[NSURL URLWithString:imageURLString]
                                         placeholderImage:[UIImage imageNamed:@"greybox40.png"]
                                                completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
                 {
                     if (!error && image)
                     {

                     }
                 }];
}

Hope it helps you...


text:
Q: flutter setup on android studio I'm facing problem in flutter setup on android studio. how to resolve this problem ?
anyone have faced this problem plz help me out.
Exception in thread "main" java.util.zip.ZipException: zip END header not found
    at java.base/java.util.zip.ZipFile$Source.zerror(ZipFile.java:1581)
    at java.base/java.util.zip.ZipFile$Source.findEND(ZipFile.java:1476)
    at java.base/java.util.zip.ZipFile$Source.initCEN(ZipFile.java:1483)
    at java.base/java.util.zip.ZipFile$Source.<init>(ZipFile.java:1288)
    at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1251)
    at java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:732)
    at java.base/java.util.zip.ZipFile$CleanableResource.get(ZipFile.java:849)
    at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:247)
    at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:177)
    at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:191)
    at org.gradle.wrapper.Install.unzip(Install.java:214)
    at org.gradle.wrapper.Install.access$600(Install.java:27)
    at org.gradle.wrapper.Install$1.call(Install.java:74)
    at org.gradle.wrapper.Install$1.call(Install.java:48)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
    at org.gradle.wrapper.Insta`enter code here`ll.createDist(Install.java:48)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Exception: Gradle task assembleDebug failed with exit code 1

A: Check if your 'JAVA_HOME' path variable is set and you have installed Java correctly.

A: I recently faced this kind of issue. All I did was delete the .gradle folder from C:\Users<youraccount> . Try rerunning after deleting that and it will build it again.
After that maybe you will face issues in your app/gradle file in android folder in the project. If you open that, there may be errors of GradleException which you have to replace with FilenotFoundException
Also, do run flutter doctor to know about any issues present in your setup.
Please do let me know if it works for you.


text:
Q: WXgrid drag and drop event - how to calculate scrolled position over classes I'm stuck trying to get the unscrolled position when I try and implement a drag ond drop function onto a subgrid in a panel. I can get the unscrolled from within the class (see onMouseOver) but not across classes when I try the drag and drop which returns
    File "dnd2.py", line 11, in OnDropFiles
    x, y = self.grid.CalcUnscrolledPosition(x, y)
AttributeError: 'EditDialog' object has no attribute 'CalcUnscrolledPosition'

Here's the cut down runable version that shows the issue:
import  wx
import  wx.grid as gridlib

class GridFileDropTarget(wx.FileDropTarget):
    def __init__(self, grid):
        wx.FileDropTarget.__init__(self)
        self.grid = grid

    def OnDropFiles(self, x, y, filenames):
        # the x,y coordinates here are Unscrolled coordinates.  Change to scrolled coordinates.
        x, y = self.grid.CalcUnscrolledPosition(x, y)
        # now we need to get the row and column from the grid
        col = self.grid.XToCol(x)
        row = self.grid.YToRow(y)
        if row > -1 and col > -1:
            self.grid.SetCellValue(row, col, filenames[0])
            self.grid.AutoSizeColumn(col)
            self.grid.Refresh()

class EditDialog(wx.Dialog):
    #----------------------------------------------------------------------
    def __init__(self, *args, **kw):
        super(EditDialog, self).__init__(*args, **kw)

        self.InitUI()
        self.SetTitle("Edit Entry")

    def InitUI(self):
        wx.Dialog.__init__ (self, None, id = wx.ID_ANY, title = u"Edit Entry", pos = wx.DefaultPosition, style = wx.DEFAULT_DIALOG_STYLE )
        self.panel = wx.Panel(self, wx.ID_ANY)

        self.myGrid = gridlib.Grid(self.panel)
        self.myGrid.CreateGrid(15, 5)
        #bind mouse voer tool tip for drag and drop
        self.myGrid.GetGridWindow().Bind(wx.EVT_MOTION, self.onMouseOver)

        #set up drag n drop
        self.moveTo = None
        dropTarget = GridFileDropTarget(self)
        self.myGrid.SetDropTarget(dropTarget)
        self.myGrid.EnableDragRowSize()
        self.myGrid.EnableDragColSize()

        #define sizers
        topSizer = wx.BoxSizer(wx.VERTICAL)
        Gridsizer = wx.BoxSizer(wx.VERTICAL)
        Gridsizer.Add(self.myGrid)
        topSizer.Add(Gridsizer, 0 , wx.ALL|wx.EXPAND)
        self.panel.SetSizer(topSizer)
        topSizer.Fit(self)

    def onMouseOver(self, event):
        x, y = self.myGrid.CalcUnscrolledPosition(event.GetX(),event.GetY())
        coords = self.myGrid.XYToCell(x, y)
        col = coords[1]
        row = coords[0]

        if col == 2 or col == 3:
            msg = "Drag and Drop files here"
            self.myGrid.GetGridWindow().SetToolTip(msg)
        else:
            self.myGrid.GetGridWindow().SetToolTip('')

if __name__ == '__main__':
    import sys
    app = wx.App()
    dlg = EditDialog()
    res = dlg.ShowModal()
    app.MainLoop()

I've tried various ways to address the self.grid.CalcUnScrolled but to no avail  - it is because of the way I have everything lumped under def InitUI rather than in a separate function that I could call in the self.grid...
thanks for any pointers

A: In case anyone else stumbles here, here's the fix (passing parent):
class GridFileDropTarget(wx.FileDropTarget):
    def __init__(self, parent, grid, *args, **kwargs):
        wx.FileDropTarget.__init__(self, *args, **kwargs)
        self.grid = grid
        self.parent = parent

    def OnDropFiles(self, x, y, filenames):
        # the x,y coordinates here are Unscrolled coordinates.  Change to scrolled coordinates.
        x, y = self.grid.CalcUnscrolledPosition(x, y)
        # now we need to get the row and column from the grid
        col = self.grid.XToCol(x)
        row = self.grid.YToRow(y)
        if row > -1 and col > -1:
            self.grid.SetCellValue(row, col, filenames[0])
            self.grid.AutoSizeColumn(col)
            self.grid.Refresh()
            return(1)
        else :
            return(0)

and call as:
        dropTarget = GridFileDropTarget(self, self.myGrid)   #link the 2 classes


text:
Q: getDisplayMetrics().heightPixels isn't accurate I have the following code:
protected void onCreate(Bundle savedInstanceState) {
//...
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
screenW = getResources().getDisplayMetrics().widthPixels;
screenH = getResources().getDisplayMetrics().heightPixels;
//...
}

getDisplayMetrics() gives for a 1024x600 screen screenW=1024 and screenH=552
This is exactly what I need, it gives only the screen excluding the status bar.
But for some screens it gives the width and height of the screen including the status bar.(like screenW=1024 and screenH=600) I've tried the screens in GenyMotion and getDisplayMetrics() returned for some screens the width and the height including the statusbar and for other screens excluding the statusbar.
For Samsung Galaxy S4, which has a 1080x1920 screen, it returned screenW=1920 and screenH=1080. (Here I'm aware that the display is rotated) For a tablet with a 1024x768 screen it returned screenW=1024 and screenH=720.
There are a lot of functions like
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    getWindowManager().getDefaultDisplay().getRectSize(rectTemp);
    getWindowManager().getDefaultDisplay().getSize(p);

but all of them give for some screens the screen size including the status bar and for others excluding the status bar.
But I've found that
getWindowsManager().getDefaultDisplay().getRealmetrics(metrics)

always gives the size including the statusbar.
So, what do you suggest for getting the width and the height of the screen excluding the statusbar?

A: If you are always getting the height of the screen including the status bar, and you want it without the status bar height, you could simply calculate the status bar height and subtract from it. To get the status bar height, you can use the following code.
public int getStatusBarHeight() {
    int statusBarHeight = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }
    return statusBarHeight;
}


text:
Q: How to not push closed branches I have created three branches by mistake.
I closed them by command hg commit --close-branch -m "Closing this head".
Then I switched to  another branch MVDM-9.
I want to push my changes to a remote repository, but I get this error.

hg push
  pushing to ssh://hg@bitbucket.org/Predictix/mvideo-modeler
  searching for changes
  abort: push creates new remote branches: MVDM-57C, MVDM-57T, MVDM-60!
  (use 'hg push --new-branch' to create new remote branches)

MVDM-57C, MVDM-57T, MVDM-60 are the branches which I closed.
How do I resolve the problem?

A: You have a couple of options here.
First option (safe)
You can just push the revisions you want to push rather than pushing everything.  You just use
hg push -r <revision_number>

substituting <revision_number> with the latest revision number that you want to push, and it will then only push that revision and the revisions that went into it.
Second option (dangerous)
If you have never pushed, pulled or copied the branches that you closed to anywhere else and you don't want to keep them for the history and will never use them then you can strip the changes.
Make sure you take a backup clone of your repository before you start doing this because you could easily destroy your existing copy.
You will need to enabled the strip extension first if it's not already enabled, and then the usage is
hg strip -r <revision_number>

This will delete <revision_number> and all its children from the repository, so you need to be careful what revision you select to delete.
If you've got TortoiseHg installed you can do this via the Workbench UI and you can do it a revision at a time until you've got what you want.
You can always use option 1 first, and then after you've pushed the revisions you want up to the remote repo you can strip the unwanted branches from your local copy.


text:
Q: NodeJS CSurf: ForbiddenError: invalid csrf token Using Angular and Nodejs as backend. csurf middleware throws Forbidden error, even if see the same _csrf token in the request cookie. My URL is: https://192.168.0.100.xip.io:64726/
Error log:
method is GET url is /
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
method is POST url is /api/login/verify
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
ForbiddenError: invalid csrf token
   at csrf (/Users/admin/nodejs/google-signin-server/node_modules/csurf/index.js:112:19)
   at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
   at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
   at urlencodedParser (/Users/admin/nodejs/google-signin-server/node_modules/body-parser/lib/types/urlencoded.js:100:7)
   at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
   at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
   at Route.dispatch (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:112:3)
   at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
   at /Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:281:22
   at Function.process_params (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:335:12)

Nodejs:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
const bodyParser = require('body-parser')

const helmet = require("helmet");
// var session = require('express-session')
const uuid    = require('uuid/v4');
const app = express()
const parseForm = bodyParser.urlencoded({ extended: false });
const csrfProtection = csrf({cookie:true,secure:true,httpOnly:false})
app.use(cookieParser())

app.use((req, res, next) => {
  const { method, url } = req;

  console.log(" method is "+ method + " url is " + url)
   logger.info('cookie', req.cookies)
next()

})
app.get('/', csrfProtection, function(req, res) {
  console.log('app // get called')
  // Pass the Csrf Token
  tokenVal =  req.csrfToken();
  res.json({csrfToken: tokenVal });
  res.sendFile('index.html');

});

app.post('/api/login/verify',parseForm, csrfProtection,(req, res) => {
  verify(req.body.idToken)
    .then((result) => {
      let id = result['sub']
      logger.info('id=', id)
      res.send({
           'payload': result
         })

             }).catch(logger.error)
});


text:
Q: Programming Principles: Assignement vs Conditions I did some research but couldn't find the answer I was looking for so I figured I'd address this issue here. I guess it's better to demonstrate it using examples, so consider the following snippets of code:
int delta = 0;
if (some_condition)
    delta = 42;

x1 = regular_value1 + delta;
x2 = regular_value2 + delta;
// ...
// where delta is used a lot of times
// basically - if (some_condition == true) => add delta to all variables
// if FALSE - add 0 (thus, effectively not changing anything)

versus
int delta = 42;

if (some_condition)
{
    x1 = regular_value1 + delta;
    x2 = regular_value2 + delta;
    // ...
}
else
{
    x1 = regular_value1;
    x2 = regular_value2;
    // ...
}

For example, a very simple real-world scenario would be: Let's say I'm creating a windows form that might contain an image on the left and might not. If there's no image - create all the rest of form controls on the left, and if there's an image, shift all other controls to the right of the image (add delta to every control's X location).
I'm programming a C# XNA game (therefore performance is somewhat relevant, but OOP principles shouldn't be omitted by any means), thus my question is - which code would run faster provided that "some_condition" would be TRUE 50% of time? As well as, which code block is easier to maintain/read?
I'm aware that this isn't a huge issue, but I'm just trying to get into a habit of writing "the best" code possible. Any input and even personal experiences would be appreciated.
Thanks.

A: The latter might be slightly faster, or they may both be optimized to the same thing. That doesn't matter, you can always change it later if you find that it becomes an issue (which this particular case certainly won't - this is just general advice). But the former, I find at least, is easier to read and maintain. If you wanted to change regular_value1 or regular_value2, you only have to change it in one place, not two. Go for that.

A: This is certainly a trivial case, and both might indeed optomize to the same code.  I'd suggest using whichever is easiest to understand--a decision that ought to be based on more of the program than you've shown here.
But the second solution is apt to be faster, particularly if "delta" is turned into a constant.  If "some_condition" is false, no adds need to be done, and an optmizer might be able to come up with some way to speed the actual assignments, so I see a performance edge there.  I think it's best to write the fastest code you can if you don't hurt maintainability.  Even with something with a much bigger performance difference than this, you are realistically never going to come back later looking for ways to speed it up.  You may as well code for performance now and forget about it.  Keep this up over time and your code will run faster at no cost to you.
Maybe someday profiling will point to this code as being the slowest point in your program.  But most likely you--and others--will just accept the fact that the code runs at a certain speed and use it accordingly.  The fact that it could be speeded up and used in new places--say between keystrokes--without annoying the user will never be thought of.
The difference in performance here is minor and the code will probably never be used in speed-critical conditions anyway, but I do think coding for speed is a good idea.  It doesn't really take any time once you get into the habit, and you know what your code can do if tweaked because its already tweaked and doing it.
(It's been my experience that fast code and readable code are much the same thing.  If a human can understand the code easily then so can the optimizer, and these days the optimizer is king.  On those rare occasions where I have to choose, I do go for clarity rather than speed unless I know everything depends on the code being fast.  Then I document like crazy to atone.)

A: This is a bit of a subjective question, but one the things that affects readability (and also importantly maintainability) is how much code is repeated.  In this case the first option results in less code to maintain and read through (less redundancy) and would be my preferred method

A: As pointed out by @minitech, the second approach can and will certainly cause problems in maintainability (points to ponder: how long is the life cycle of the application? Is the code you are writing going to be reused or consumed by others?) and readability. Given, that you have already considered these factors, I would recommend that you decide and set some performance numbers that your application should conform to.
Once the performance requirements have been clearly established, then you can decide on which approach to follow. OOP principles and readability are every programmers dream, but remember that once you ship the application to the customer, it does not matter which approach you had followed, the only thing that matters is your application runs as expected (from the point of view of both functionality and performance).
You will need to gauge with the stakeholders on the implications of writing the 'best' vs actual performance impact that the 'best' code might cause.