text:
Q: Insert number as folderID I'm getting a new little problem with API Rest Python between Django and LogicalDOC.
I'm creating a folder inside LogicalDOC, then I would like to save my pdf file inside this new folder taking the folderId.
But, when it seems work because the syntax is good from my point of view : none pdf file appears.
I create a folder, I pick up his ID number : 348930 for example with the command data["id"] and I insert str(data["id"]) in FolderId when I want to save my pdf file in the new folder.
The new folder is created and worked well, but the pdf file is not save inside. Something wrong ?
This is my script :
@login_required
def BirthCertificate_PDF(request, id) :

    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    data = {"birthcertificate" : birthcertificate}

    template = get_template('BC_raw.html')
    html  = template.render(Context(data))

    filename_directory = str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday)
    filename = 'Acte_Naissance_' + filename_directory + '.pdf'
    path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename

    file = open(path, "w+b")
    pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8')

    file.seek(0)
    pdf = file.read()
    if pdf :

        payload = '{{ "name":"{0}", "parentId":3309569 }}'.format(filename_directory) #Fix parent folder

        url = 'http://localhost:8080/services/rest/folder/create'
        headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
        resp = requests.post(url, data=payload, headers=headers, auth=('admin', 'admin'))
        rbody = resp.content
        data = json.loads(rbody)

        print data["id"] #Get ID from the new folder

        payload = '{{ "language":"fr","fileName":"{0}","FolderId":'+str(data["id"]) +'}}'.format(filename)  #save pdf file inside the new folder thanks to his ID
        upfile = path
        files = {
        'document': (None, payload, 'application/json'),
        'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream')
        }
        url = 'http://localhost:8080/services/rest/document/create'
        headers = {'Content-Type': 'multipart/form-data'}
        r = requests.post(url, files=files, headers=headers, auth=('admin', 'admin'))

        context = {"birthcertificate":birthcertificate,
                   "path":path}

        return render(request, 'BC_PDF.html', context)
    file.close()

    return HttpResponse(pdf, 'application/pdf')

This is a screen capture which shows that folderID should be : 3538970
This number is also given by : data["id"]

A: As I said in my comment you don't need to use string concatenation to pass FolderId as payload, just use second argument of format method:
d = '{{ "language":"fr","fileName":"{0}","FolderId":"{1}"}}'.format(filename, str(data["id"]))


text:
Q: Block an element by name only on a specific website using uBlock (or Adblock Plus) A website I have visited has a very large div at the top, normally containing ads.  uBlock has stopped the ads from appearing, but because they were within an otherwise innocuous div, the huge empty space is still showing.  When using the element picker, I can effectively block the div by name.  However, the name is simply leaderboard which seems like it might be common enough to show up on other websites, so I want to limit it to the specific domain.
The originally generated filter rule is ###leaderboard, and it does work.  Following the filter rules suggested here, I thought to be able to block it on this site only by modifying it like so example.com##leaderboard but this fails to block anything.  I've tried a few variations on that as well, but still found nothing useful.  I have also tried all the variations in Adblock Plus, just to make sure it wasn't a quirk in uBlock's implementation of the Adblock filter rules.  Is there any way to do this?

A: The filter example.com##leaderboard would hide an element <leaderboard> on the domain example.com which is not useful since there is no such element. What you want instead is the filter example.com###leaderboard because ## is separating the domain example.com and the CSS selector #leaderboard.
Note that the documentation you're referring to is incomplete and out-of-date. You can find the official filter syntax documentation at adblockplus.org/filters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: have deleted the shared memory but get shm ipc_id error I have the code
shmid = shmget(IPC_CREAT, size, IPC_CREAT|0666) ;
if ( shmid < 0 )
{
        perror("get shm ipc_id error") ;
        return -1 ;
}
shmaddr = (unsigned int*)shmat(shmid, 0, 0 ) ;

create a shared memory and do something
int the bottom
  shmdt( shmaddr ) ;
  shmctl(shmid, IPC_RMID, NULL) ;

to delete the share memory.
First time to execute the program, it works fine.
But if I execute the second time, it printf
get shm ipc_id error: Invalid argument

and I cannot figure out why it happen?
I have deleted and detach the shared memory, why it still happen?
And how to prevent it?

A: According to man shmget:
ERRORS
       On failure, errno is set to one of the following:

       EINVAL A new segment was to be created and size < SHMMIN or size > SHMMAX, or  no  new  segment
              was  to  be created, a segment with given key existed, but size is greater than the size
              of that segment.

With ipcs, you can check if the delete succeeded or not.


text:
Q: What is a 32 x 8 Multiplier and Thumb Instruction Decoder in ARM7TDMI? I'm a college student and only have a very basic knowledge of digital electronics and micro controllers. Recently I got interested in arm micro controllers and just stared to learn about them. While reading arm7tdmi technical reference manual I came across a block diagram of arm7tdmi in which I saw two blocks named "32x8 multiplier" and "Instruction pipeline, Read data register, Thumb instruction decoder".

I have following questions/doubts:

*

*What is the meaning of "32x8" in the 32x8 multiplier?

*What is the function of the 32x8 multiplier?

*What is the function of the Thumb instruction decoder and how does it work?

*What is the data flow logic (through which buses will data come into the destination register) of load instruction?

A: *

*32x8 means it can multiply a 32-bit number with an 8-bit number.

*It multiplies numbers. It takes in two numbers and returns the result of a multiplication operation.

*The CPU can be in ARM mode where it fetches ARM instructions for execution, or the CPU can be in Thumb mode where it fetches Thumb instructions for execution. The CPU can only work with ARM instruction set so the Thumb instructions need to be converted to ARM instructions for execution. The block decodes the fetched Thumb instructions into ARM instructions that can be executed.

*There is only one input bus for anything, the RDATA bus.


text:
Q: How to Solve Proguard Issue - ArrayIndexOutOfBoundsException? I'm trying to Generate APK for my App. But After Building the compiler throws an
java.lang.ArrayIndexOutOfBoundsException.
I know what this Error means programatically. But If I disable the minifyEnabled to False. Then the APK is generated & the app works Fine.
I saw a similar question here & tried desugaring to false.
But Still it throws Process 'command 'C:\Program Files\Android\Android Studio\jre\bin\java.exe'' finished with non-zero exit value 1
How Can I Solve this issue ?

A: The fix for me was to add the following to my proguard-rules.pro file:
-keepnames class com.google.android.gms.** {*;}

Something in Google Play Services plugin was causing this error for me.
If that doesn't fix it for you, you could also keepnames for anything outside of your app package by adding the following to your proguard-rules.pro file:
-keepnames class !com.yourpackage.app.** { *; }

You might also be able to use this to troubleshoot some more to figure out which class is causing the problem.


text:
Q: When developing a maven project with intellj idea, the module display is sorted I want to display it on the left in the order of modules in the pom.xml file, as follows:

I know "sort by type",but this is not what I want:

A: There is no way to sort module like this,
refer to the following link: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206256729-Can-I-sort-modules-according-to-the-maven-pom-xml-
The Project view shows the physical structure of your project on disk, not logical structure according to some
criteria


text:
Q: λ: folktale data.task - apply an unknown number of Tasks I am wanting to convert a list of id's into a list of Tasks, and run them concurrently, similar to Promise.all. I am aware of applicatives, but I want to apply an unknown number of tasks so I don't believe that will be the best approach.
Say I have a Task that contains an array of Task's.
Task.of([Task.of(1), Task.of(2)])

Is there anyway to fold the tasks down into a single task that will run them all, or is there a better way that I can handle the data transformation.
The snippet has data.Task included that you can copy if you want to provide an example.
http://folktalegithubio.readthedocs.io/en/latest/api/data/task/

// Task([Task])
Task.of([0, 1, 2])
  .map(t => t.map(Task.of))
  .fork(console.error, console.log)
<script src="https://codepen.io/synthet1c/pen/bWOZEM.js"></script>

A: control.async.parallel is exactly what you are looking for.

I am aware of applicatives, but I want to apply an unknown number of tasks so I don't believe that will be the best approach.

That shouldn't hold you back, arrays are traversable and sequenceA would do exactly what you wanted (though quite inefficiently). If it was implemented in folktale, which doesn't feature lists or even a control.applicative.
control.monad.sequence should have been working the same as the applicative sequence, but unnecessarily uses chain instead of ap. And data.task is problematic anyway in that ap is not derivable from chain with the same semantics.


text:
Q: How to make stream simpler than current stream Currently my code is this long. I know it's possible to make this much shorter but can't seem to figure it out.
Employee[] fullTimeEmployees = employees.stream().filter((Employee e) -> {
            for (Project project : e.getAssignedProjects()) {
                int hoursWorked = project.getCommittedHoursPerDay().get(e);
                if (hoursWorked >= 8)
                    return true ;
            }
            return false ;
        }).toArray(Employee[] :: new);

        System.out.println(Arrays.toString(fullTimeEmployees));

I've tried using flatmap but didn't succes with it.
My code with flatmap was:
List<Project> test = employees.stream().flatMap(employee -> employee.getAssignedProjects().stream()
           .filter(project -> project.getCommittedHoursPerDay().get(employee) >= 8))
           .collect(Collectors.toList());

Would appreciate any help!
edit:
This is the for loop that I tried to make a stream of:
        for (Employee employee : employees) {
            for (Project project : employee.getAssignedProjects()) {
                int hoursWorked = project.getCommittedHoursPerDay().get(employee);
                if (hoursWorked >= 8)
                    if (!fullTimeEmployees.contains(employee))
                        fullTimeEmployees.add(employee);
            }
        }

A: The following filter is simpler. There's no need to use flatMap. Just use anyMatch on the Stream of an Employee's assigned projects.
Employee[] fullTimeEmployees =
    employees.stream()
             .filter(e -> e.getAssignedProjects()
                           .stream()
                           .anyMatch(p -> p.getCommittedHoursPerDay().get(e) >= 8))
             .toArray(Employee[] :: new);


text:
Q: How to reset path.expand on tilde On Windows, in my RProfile.site, I used to set:
Sys.setenv(R_USER="/my/desired/path/to/tilde")

However, this does not create the same effect on Ubuntu. Any ideas on how I can achieve the same effect? Such that when I type ~ in a path it expands to R_USER?
Here's an example. On Windows, after setting R_USER, in my scripts I would use the following:
read.csv("~/Project")

Where "~" expanded to /some/path/to/projects/

A: Define HOME="/my/projects/folder", preferably for R only, in .Renviron
Functionality for changing the method of ~ path expansion on windows does not exist in the same fashion as Windows as it does in Ubuntu/Linux*


text:
Q: Connecting frontend to backend in MERN stack application I am working on an Exercise tracker application using MERN stack. I am facing an error and I am not being able to render it.
create-user.componet.js file:-
import React, { Component } from 'react';
const axios=require('axios');

 class CreateUser extends Component {
    constructor(props)
    {
        super(props);

        this.onChangeUsername=this.onChangeUsername.bind(this);//even binding
        this.onSubmit = this.onSubmit.bind(this);//event binding

        this.state={
            username: '',

        }
    }
    onChangeUsername(e) {
        this.setState({
          username: e.target.value
        })
      }
      onSubmit(e){
        e.preventDefault() //prevents from default process and implements the lined following

        const user={
            username: this.state.username

        };
        console.log(user)

        //connecting the front end to the backend. On submit the username will be stored in the backend.This is done by using axios
        axios.post('http://localhost:3000/users/add',user)//accesses the route mentioned in user.js and hence connecting to the backend
        .then(res=> {
            console.log(res)
            console.log(res.data)});

        this.setState({
          username: ''
      })
    }
    render() {
        return (

Create New User

                <form onSubmit={this.onSubmit}>

                    Username:
                <input  type="text"
                         required
                         className="form-control"
                         value={this.state.username}
                         onChange={this.onChangeUsername}/>

                        <input type="submit" value="Create User" className="btn btn-primary">
                        </input>

                </form>

        )
    }
}

export default CreateUser

route fie:-
    const router=require('express').Router();
let User=require('../models/user.model')

router.route('/').get((req,res) => {
    User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error:'+err))

});
router.post('/add', function(req, res)  {
    const username = req.body.username;

    const newUser = new User({username});

    newUser.save()
      .then(() => res.json('User added!'))
      .catch(err => res.status(400).json('Error: ' + err));
  });
module.exports=router;

error:
POST http://localhost:3000/users/add 404 (Not Found)
On implementing the application the above error is being showed, whereas the api is working fine when tested in insomnia(tool).
Could someone help to render this issue?

A: I think you are targeting the wrong route,
in your server you have
router.post('/add', function(req, res)

But in the client you target
axios.post('http://localhost:3000/users/add',user)

Try changing it to
axios.post('http://localhost:3000/add',user)

Or try changing the server to
router.post('/users/add', function(req, res)


text:
Q: What would be the Mean Squared error of the Uncorrected Sample Variance? I am trying to compute the MSE of $\hat{\sigma}^2$, where $\hat{\sigma}^2= \frac{1}{N} \sum_{i=1}^N (x_i - \mu)^2$ for i.i.d samples $\{x_i\}_{i=1}^N$ normally distributed. I get the following calculation:
$$
\begin{align}
\text{MSE} \, (\hat{\sigma}^2) &= \text{Var}(\hat{\sigma}^2) + \text{Bias}^2(\hat{\sigma}^2)\\
&= \mathbb{E}[\hat{\sigma}^4] + \mathbb{E} [\hat{\sigma}^2]^2 + \mathbb{E}[\hat{\sigma}^2] - \sigma^2
\end{align}
$$
I am stuck here on how to calculate $\mathbb{E}[\hat{\sigma}^4]$ ?
Any help or direction is appreciated a lot. Thanks!


text:
Q: How can I match multi-line patterns in the command line with perl-style regex? I regularly use regex to transform text.
To transform, giant text files from the command line, perl lets me do this:
perl -pe < in.txt > out.txt

But this is inherently on a line-by-line basis. Occasionally, I want to match on multi-line things.
How can I do this in the command-line?

A: To slurp a file instead of doing line by line processing, use the -0777 switch:
perl -0777 -pe 's/.../.../g' in.txt > out.txt

As documented in perlrun #Command Switches:

The special value -00 will cause Perl to slurp files in paragraph mode. Any value -0400 or above will cause Perl to slurp files whole, but by convention the value -0777 is the one normally used for this purpose.

Obviously, for large files this may not work well, in which case you'll need to code some type of buffer to do this replacement.  We can't advise any better though without real information about your intent.

A: Grepping across line boundaries
So you want to grep across lines boundaries...
You quite possibly already have pcregrep installed. As you may know, PCRE stands for Perl-Compatible Regular Expressions, and the library is definitely Perl-style, though not identical to Perl.
To match across multiple lines, you have to turn on the multi-line mode -M, which is not the same as (?m)
Running pcregrep -M "(?s)^b.*\d+" text.txt
On this text file:
a
b
c11

The output will be
b
c11

whereas grep would return empty.
Excerpt from the doc:

-M, --multiline Allow patterns to match more than one line. When this  option is given, patterns may usefully contain literal newline char-
  acters and internal occurrences of ^ and  $  characters.  The output
  for  a  successful match may consist of more than one line, the last
  of which is the one in which the match  ended. If the matched string
  ends with a newline sequence the output ends at the end of that line.
When this option is set, the PCRE library is called in  "mul- tiline"
  mode.   There is a limit to the number of lines that can be matched,
  imposed by the way that pcregrep buffers  the input  file as it scans
  it. However, pcregrep ensures that at least 8K characters or the rest
  of the document (whichever is the  shorter)  are  available for
  forward matching, and simi- larly the previous 8K characters (or all
  the previous charac- ters,  if  fewer  than 8K) are guaranteed to be
  available for lookbehind assertions. This option does not work  when
  input is read line by line (see --line-buffered.)


text:
Q: ForEach method with an error `The compiler is unable to type-check this expression in reasonable time;` I'm currently developing an application using SwiftUI.
I'm having an error The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
There are some articles about the same error and I tried to solve this, but I can't do it in my case...
would someone mind advising me on how to solve this?

Here is the code:
EDITED
import SwiftUI

struct InfoView: View {

    @EnvironmentObject var appState: AppState

    var body: some View {

    Button(action: {
                appState.makeGetCallInfo()
            }) {
                Text("Hit API")
            }

        ForEach(appState.arrayInfos ?? []){ info in

            VStack{
                Group{
                  Text(String(info.id))
                  Text(String(info.no_1))
                  Text(String(info.no_2))
                  Text(info.name_1)
                  Text(info.name_2 ?? "")
                  Text(info.name_3)
                  Text(info.name_4 ?? "")
                  Text(String(info.no_3 ?? 0))
                  Text(info.name_5 ?? "")
                  Text(String(info.no_4 ?? 0))
                }
                Group{
                  Text(String(info.no_5 ?? 0))
                  Text(info.name_6 ?? "")
                  Text(String(info.no_7))
                  Text(String(info.no_8))
                  Text(info.name_7 ?? "")
                  Text(info.name_8)
                  Text(info.memo ?? "")
                  Text(info.created_at)
                  Text(info.updated_at)
                  Text(String(info.userId))
                }
                  Divider()
                      .padding()
            }
        }
    }
}

If I reduce the number of subviews in VStack like below, it works well. the error disappears
import SwiftUI

struct InfoView: View {

    @EnvironmentObject var appState: AppState

    var body: some View {
        ForEach(appState.arrayInfos ?? []){ info in

            VStack{
                Group{
                  Text(String(info.id))
                  Text(String(info.no_1))
                  Text(String(info.no_2))
                  Text(info.name_1)
                  Text(info.name_2 ?? "")
                  Text(info.name_3)
                  Text(info.name_4 ?? "")
                  Text(String(info.no_3 ?? 0))
                  Text(info.name_5 ?? "")
                  Text(String(info.no_4 ?? 0))
                }
                  Divider()
                      .padding()
            }
        }
    }
}

AppState.swift
import SwiftUI
import Foundation
import Combine

class AppState: ObservableObject {

    @Published var arrayInfos:[Infos]?

    func makeGetCallInfo() {
        // Set up the URL request
        let endpoint: String = "https://sample.com/api/info/?user=1"

        guard let url = URL(string: endpoint) else {
            print("Error: cannot create URL")
            return
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.addValue("token xxxxxxxxxxxxxxxxxxx", forHTTPHeaderField: "authorization")
        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            // check for any errors
            guard error == nil else {
                print("error calling GET")
                print(error!)
                return
            }
            // make sure we got data
            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            // parse the result as JSON, since that's what the API provides
            DispatchQueue.main.async {

                do{ self.arrayInfos = try JSONDecoder().decode([Infos].self, from: responseData)
                }catch{
                    print("Error: did not decode")
                    return
                }
            }
        }
        task.resume()
    }

JsonModel.swift
import Foundation

struct Infos: Codable,Identifiable {
    var id: Int
    var no_1: Int
    var no_2: Int
    var name_1: String
    var name_2: String?
    var name_3: String
    var name_4: String?
    var no_3: Int?
    var name_5: String?
    var no_4: Int?

    var no_5: Int?
    var name_6: String?
    var no_7: Int
    var no_8: Int
    var name_7: String?
    var name_8: String
    var memo: String?
    var created_at: String
    var updated_at: String
    var userId: Int
}

Xcode: Version 12.0.1

A: Your VStack contains too many subviews, it is allowed maximum 10. So group them by less amount, like below
VStack{
  Group {
    Text(String(info.id))
    Text(String(info.no_1))
    Text(String(info.no_2))
    Text(info.name_1)
    Text(info.name_2 ?? "")
    Text(info.name_3)
    Text(info.name_4 ?? "")
    Text(String(info.no_3 ?? 0))
    Text(info.name_5 ?? "")
    Text(String(info.no_4 ?? 0))
  }
  Group {
    Text(String(info.no_5 ?? 0))
    Text(info.name_6 ?? "")
    Text(String(info.no_7))
    Text(String(info.no_8))
    Text(info.name_7 ?? "")
    Text(info.name_8)
    Text(info.memo ?? "")
    Text(info.created_at)
    Text(info.updated_at)
    Text(String(info.userId))
  }
    Divider()
        .padding()
}

Note: it is preferable to separate such big containers into dedicated view and just create it here.

A: Break it down into smaller views. For example, make every Group a separate sub View.
Pass the info object from your loop into the subview


text:
Q: some folder is not in the git index, and not appears under git status, not shows up in the ignore file, how could I add it to index? I have three folders protected/ themes/ public/
but only protected/ is showing up in git ls-files
I tried git add public/, nothing happen, git status still shows me "nothing to commit, working directory clean". I confirmed these two folders are not ignored.
Nothing shows up when I do git ls-files --others --exclude-standard
What's wrong? How can I add these two folders to index or re-index the whole repo?

A: You can't add directories to a git repository, only files. As far as git is concerned directories only exist as components of a file's path.
See also How can I add an empty directory to a Git repository?


text:
Q: Django form data is passing in html table I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table.
Without the fetch API submit, everything is working fine as per my need.
I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong.
views.py
def home(request):
    context={}

    if request.method=="POST":

        options_value=request.POST['options_value']

        value=request.POST['value']

        print(options_value,value)

        context={"options_value":options_value, "value":value}

  return render(request, 'index.html',context)

index.html
<form method="POST" action="" id="form">

      {% csrf_token %}

          <select

            class="form-select"

            aria-label="Default select example"

            name="options_value"

            id="options_value"

          >

            <option disabled hidden selected>---Select---</option>

            <option value="1">Profile UID</option>

            <option value="2">Employee ID</option>

            <option value="3">Email ID</option>

            <option value="4">LAN ID</option>

          </select>

          <input

            type="text"

            class="form-control"

            type="text"

            placeholder="Enter Value"

            name="value"

            id="value"

          />

          <input

            class="btn btn-primary"

            type="submit"

            value="Submit"

            style="background-color: #3a0ca3"

          />

    </form>

              ProfileUID :

              {{options_value}}

              First Nane :

              {{value}}

A: Things in the POST array are indexed by the name, not the id.  You need
options_value = request.POST['options_value']

not dropdown_val.

A: It seems like you are never rendering the response. A quick fix would be to simply overwrite the html from javascript whenever you receive the response after making a POST request:
      .then(response => response.text())
      .then(data => {
       console.log('Success:', data);
       document.write(data);
       })
       .catch(error => {
       console.error('Error:', error);
       });


text:
Q: Issue with __nextSuper Moving from Ember 1.5.1 to 1.6.0, I've run into an issue with __nextSuper (which has been changing in the last few versions). You can see the offending code here.
And here's the relevant Ember code:
function wrap(func, superFunc) {
  function superWrapper() {
    var ret, sup = this.__nextSuper; // THIS LINE
    this.__nextSuper = superFunc;
    ret = apply(this, func, arguments);
    this.__nextSuper = sup;
    return ret;
  }

  superWrapper.wrappedFunction = func;
  superWrapper.wrappedFunction.__ember_arity__ = func.length;
  superWrapper.__ember_observes__ = func.__ember_observes__;
  superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__;
  superWrapper.__ember_listens__ = func.__ember_listens__;

  return superWrapper;
};

What happens is, at some point, the superWrapper function gets called with window as the this value. So when I reach the line marked above, this.__nextSuper comes out to be undefined. But rather than sup simply being undefined, it throws the following error:
TypeError: Cannot read property '__nextSuper' of undefined

The thing is, when I pause in the debugger, this is defined (it's the window object). And when I paste var ret, sup = this.__nextSuper; into the console, it works as expected. And, if I go up the stack frame and check the this value, it's exactly what I expect. So I have no idea why superWrapper suddenly has a bad this value.
Finally, the most interesting part, this only happens in the browser; it works fine in PhantomJS. The changelog didn't seem to list anything to do with __nextSuper as a breaking bugfix, but obviously something has changed. How can I solve this issue?

A: Ember 1.6 looks to have a requirement on super method being called from the scope of the object hosting the super method (probably a bug, but I'm not positive).  In your case you'd want to keep track of the scope, then call the super method using it:
(scope is the object that houses isEqual)
 var scope = meta.isEqual ? meta : this.get('store').attributeTypeFor(meta.type);
 if (scope.isEqual(server, value)) { ...

instead of (scope is window and explodes in 1.6+)
 var isEqual = meta.isEqual || this.get('store').attributeTypeFor(meta.type).isEqual;
 if (isEqual(server, value)) { ...

Here's a super simple example showing the problem (1.6+): http://emberjs.jsbin.com/yelesahe/1/edit
And working in 1.5.1: http://emberjs.jsbin.com/zedevudo/1/edit
Issue: https://github.com/emberjs/ember.js/issues/5198


text:
Q: User account does not exist in GCP IAM, however still the scheduled queries created by the user executing I have couple of scheduled queries in GCP which are created by the user A. The user A has left the company, her account is not found from the GCP IAM but available in the x-domain.co directory. I see the queries are everyday running successfully!
Is this a normal behaviour?
I followed the below question already, as per this it is not possible!
Would removing user who created a scheduled query on BigQuery break said query?

A: Answer:
Even though the users may not be in the result of the below command,
gcloud projects get-iam-policy <project_id> \
--flatten="bindings[].members" \
--format="value(bindings.members)" \
--sort-by=bindings.members | uniq

When the users are part of some Groups in GCP IAM & Admin, and if that Group has sufficient resource access roles assigned, it allows them to create and schedule the big queries in GCP.


text:
Q: How to add timer to change image for selected item in ListPicker what would be the steps to add timer to change selected item's image in listpicker. Any suggestions? FYI, have never used ListPicker before. So i am finding it kind of hard to understand where to start and what to do.

A: You will need an ObservableCollection of your ImageSources and a DispatcherTimer to fire the events every TimeSpan of your choosing.
Here's some code to help you get started.  You can modify it to do exactly what you want.  It basically contains a ListPicker that has a collection of images as its ItemTemplate.  Every one second the DispatchTimer fires and switches the selectedItem's Image between the 2 default images that are created in about every single WP8.0 application.
Make it a habit to use ObervableCollection when you want to display something to the user instead of a List, it will make your WP8 development life a lot easier.

XAML
    <toolkit:ListPicker x:Name="my_listpicker" SelectionChanged="my_listpicker_SelectionChanged_1" Background="Black">
        <toolkit:ListPicker.HeaderTemplate>
            <DataTemplate/>
        </toolkit:ListPicker.HeaderTemplate>
        <toolkit:ListPicker.ItemTemplate>
            <DataTemplate>
                <StackPanel Background="Black">
                    <Image Source="{Binding ImageSource}" Height="200"></Image>
                </StackPanel>
            </DataTemplate>
        </toolkit:ListPicker.ItemTemplate>
    </toolkit:ListPicker>

C# Namespaces
using System.ComponentModel;                        // ObservableCollection
using System.Collections.ObjectModel;               // INotifyPropertyChanged
using System.Windows.Threading;                     // Dispatch Timer

C# Model of your Images (pretty basic, but pay attention to the INotifyPropertyChanged
public class MyBindingImage : INotifyPropertyChanged
{
    public MyBindingImage() { }
    public MyBindingImage(string source)
    {
        this.ImageSource = source;

    }

    // Create the OnPropertyChanged method to raise the event
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    string image_source;
    public String ImageSource {
        get { return image_source; }
        set
        {
            image_source = value;
            OnPropertyChanged("ImageSource");
        }
    }
}

C# (Create the Timer and ObservableCollection and Set the ItemSource)
DispatcherTimer timer;
// Constructor
public MainPage()
{
    // create our dispatch timer
    timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromMilliseconds(2000);
    timer.Tick += OnTimerTick;

    InitializeComponent();

    // create our list picker elements
    ObservableCollection<MyBindingImage> my_image_list = new ObservableCollection<MyBindingImage>();
    my_image_list.Add(new MyBindingImage("Assets/ApplicationIcon.png"));
    my_image_list.Add(new MyBindingImage("Assets/AlignmentGrid.png"));
    my_listpicker.ItemsSource = my_image_list;

}

C# Events (For the Timer & ListPicker SelectionChange)
// each time the selection has changd: stop the timer, then start it again
private void my_listpicker_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    if (timer != null)
    {
        timer.Stop();
        timer.Start();
    }
}

// if the timer is on, cycle the images of the selected item
private void OnTimerTick(object sender, EventArgs e)
{
    try
    {
        MyBindingImage item = (MyBindingImage) my_listpicker.SelectedItem;

        // cycle the selected image between to different images
        if (item.ImageSource == "Assets/AlignmentGrid.png")
        {
            item.ImageSource = "Assets/ApplicationIcon.png";
        }
        else
        {
            item.ImageSource = "Assets/AlignmentGrid.png";
        }
    }
    catch (Exception ex)
    {
        string error_message = ex.Message;
    }
}

[APPLICATION SCREENSHOT]


text:
Q: Keep a service running even if app is closed I am implementing Service for receiving push notifications in Android device. The notifications are successfully received when app is in foreground. When app is closed and its instance is cleared from task manager, notifications are not received.
I want to keep the service running at all the times and it should not stop even if the app is cleared from the task manager.
I start the service from my activity in a button click. When i click the button my service starts and it gives me Toast  notification every one minute but if I press the back button then also my service is running but , as soon as i clear my app from the recent activity list which is shown on long press of home button my service is stoped and if again  i start my app and check the status of the service but its not running.
I want my service to run even if my app is closed.
This is my activity class
package com.example.hello;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    Button btnSer;
    int Pointer=0;
    ListView lv;
    ArrayList<String> alist=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSer=(Button) findViewById(R.id.btnstart);
        btnSer.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                //start  the service when the button is clicked
                Log.e("","status of service : "+isMyServiceRunning(MyService.class));
                //if(!isMyServiceRunning(MyService.class))
                    startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

    }

    //check if the service is running
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

This is my Service class.
 package com.example.hello;

import java.util.Calendar;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

    private Handler handlerList = new Handler();
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        Toast.makeText(getApplicationContext(), "On start command called", Toast.LENGTH_LONG).show();
         return Service.START_STICKY;
    }
    public void updateLists(){
        handlerList.postDelayed(mUpdateListTask, 1000*60);
    }
    private Runnable mUpdateListTask = new Runnable() {
        public void run() {  //will make a toast notification every 1 minute.
            Calendar cal = Calendar.getInstance();

            Log.e("","Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":");
            Toast.makeText(getApplicationContext(), "Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":", Toast.LENGTH_LONG).show();
           handlerList.postDelayed(this, 1000*60);
        }};
    @Override
    public void onCreate() {

        updateLists();
        Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
        Log.d("", "onCreate in service");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d("", "onStart in service");
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d("", "onDestroy in service");
    }
}

also added the permission in manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />

A: Start it as foreground service in the activity use startforeground(intent name) and return it as sticky in the service onstartCommand() method.


text:
Q: How does predict.cv.glmnet() calculate the link value for binomial models? I'm thinking this is a coding error on my part, but I can't figure out what I'm doing wrong. I'm trying to create marginal effects plots for x when x+x^2 are in a binomial glmnet model. When I made predictions using predict.cv.glmnet() on a new dataset it almost seemed as if the the signs of the model coefficients were switched. So I've been comparing predictions when hardcoding the model formula vs. the predict function. I'm getting different predictions on the new data but not the training data and I'm not sure why.
#############example############
library(tidyverse)
library(glmnet)
data(BinomialExample)
#head(x)
#head(y)

#training data
squareit<-function(x){x^2}
x%>%
  as.data.frame()%>%
  dplyr::select(V11, V23, V30)%>%#select three variables
  mutate_all(list(SQ = squareit))%>%#square them
  as.matrix()%>%{.->>x1}#back to matrix
# x1[1:5,]
#             V11         V23        V30    V11_SQ       V23_SQ    V30_SQ
# [1,]  0.5706039  0.01473546  0.9080937 0.3255888 0.0002171337 0.8246342
# [2,]  0.4138668 -0.81898245 -2.0492817 0.1712857 0.6707322586 4.1995554
# [3,] -0.4876853  0.03927982 -1.2089006 0.2378369 0.0015429039 1.4614407
# [4,]  0.4644753 -0.98728378  1.7796744 0.2157373 0.9747292699 3.1672408
# [5,] -0.5239595 -0.13288456 -1.1970731 0.2745336 0.0176583076 1.4329841

#example model + coefficients
set.seed(4484)
final.glmnet<-cv.glmnet(x1, y, type.measure="auc",alpha=1,family="binomial")
coef(final.glmnet,s="lambda.min")#print model coefficients
# (Intercept)  0.4097381
# V11         -0.4487949
# V23          0.3322128
# V30         -0.2924600
# V11_SQ      -0.3334376
# V23_SQ      -0.2867963
# V30_SQ       0.3864748

#get model formula - I'm sure there is a better way
mc<-data.frame(as.matrix(coef(final.glmnet,s="lambda.min")))%>%
  rownames_to_column(.,var="rowname")%>%mutate(rowname=recode(rowname,`(Intercept)`="1"))
paste("(",mc$rowname,"*",mc$X1,")",sep="",collapse = "+")
#model formula
# (1*0.409738094215867)+(V11*-0.44879489356345)+(V23*0.332212780157358)+
# (V30*-0.292459974168585)+(V11_SQ*-0.333437624504966)+
# (V23_SQ*-0.286796292157334)+(V30_SQ*0.386474813542322)

#####predict on training data -- same predictions!
#1 predict using predict.cv.glmnet()
pred_cv.glmnet<-predict(final.glmnet, s=final.glmnet$lambda.min, newx=x1[1:5,], type='link')
round(pred_cv.glmnet,3)
#2 predict using model formula
pred.model.formula<-data.frame(x1[1:5,])%>%
  mutate(link=(1*0.409738094215867)+(V11*-0.44879489356345)+
           (V23*0.332212780157358)+(V30*-0.292459974168585)+
           (V11_SQ*-0.333437624504966)+(V23_SQ*-0.286796292157334)+
           (V30_SQ*0.386474813542322))%>%
  dplyr::select(link)
round(pred.model.formula,3)
# 1         0.103
# 2         1.925
# 3         1.480
# 4         0.225
# 5         1.408

#new data - set up for maringal effects plot
colnames(x1)
test<-data.frame(V23=seq(min(x1[,2]),max(x1[,2]),0.1))%>%#let V23 vary from min-max by .1
  mutate(V23_SQ=V23^2, V11=0, V11_SQ=0, V30=0, V30_SQ=0)%>%#square V23 and set others to 0
as.matrix()
test[1:5,]
# > test[1:5,]
#           V23   V23_SQ V11 V11_SQ V30 V30_SQ
# [1,] -2.071573 4.291414   0      0   0      0
# [2,] -1.971573 3.887100   0      0   0      0
# [3,] -1.871573 3.502785   0      0   0      0
# [4,] -1.771573 3.138470   0      0   0      0
# [5,] -1.671573 2.794156   0      0   0      0

#####predict on new data -- different predictions!
#1 predict using predict.cv.glmnet()
pred_cv.glmnet<-predict(final.glmnet, s=final.glmnet$lambda.min, newx=test[1:5,], type='link')
round(pred_cv.glmnet,3)
# [1,] 2.765
# [2,] 2.586
# [3,] 2.413
# [4,] 2.247
# [5,] 2.088

#2 predict using model formula
pred.model.formula<-data.frame(test[1:5,])%>%
  mutate(link.longhand=(1*0.409738094215867)+(V11*-0.44879489356345)+
           (V23*0.332212780157358)+(V30*-0.292459974168585)+
           (V11_SQ*-0.333437624504966)+(V23_SQ*-0.286796292157334)+
           (V30_SQ*0.386474813542322))%>%
  dplyr::select(link.longhand)
round(pred.model.formula,3)
# 1        -1.509
# 2        -1.360
# 3        -1.217
# 4        -1.079
# 5        -0.947

A: Your understanding of how the calculation works appears to be correct. However, the predict function requires the newx matrix to have the same dimensions as the original (i.e. columns need to be in the same order). When the columns are mixed up the predict function results will go haywire, as you see in your example.
If you add a quick adjustment to put your test matrix in the same order as your x1 matrix (handy shortcut is to just use the dimnames from your original matrix in a dplyr::select like line 3 below)...
test <- data.frame(V23 = seq(min(x1[, 2]), max(x1[, 2]), 0.1)) %>% #let V23 vary from min-max by .1
    mutate(V23_SQ = V23^2, V11 = 0, V11_SQ = 0, V30 = 0, V30_SQ = 0) %>% #square V23 and set others to 0
    select(dimnames(x1)[[2]]) %>% #use the dimnames from x1 to select test in proper order!
    as.matrix()

...you will find that you get the proper results which align as expected.
#1 predict using predict.cv.glmnet()
pred_cv.glmnet <- predict(final.glmnet, s = 'lambda.min', newx = test[1:5,], type = 'link')
round(pred_cv.glmnet,3)
# [1,] -1.509
# [2,] -1.360
# [3,] -1.217
# [4,] -1.079
# [5,] -0.947

#2 predict using model formula
pred.model.formula <- data.frame(test[1:5,]) %>%
    mutate(link.longhand = ((1 * 0.409738094215867) +
               (V11 * -0.44879489356345) +
               (V23 * 0.332212780157358) +
               (V30 * -0.292459974168585) +
               (V11_SQ * -0.333437624504966) +
               (V23_SQ * -0.286796292157334) +
               (V30_SQ * 0.386474813542322))) %>%
    dplyr::select(link.longhand)
round(pred.model.formula, 3)
# link.longhand
# 1        -1.509
# 2        -1.360
# 3        -1.217
# 4        -1.079
# 5        -0.947


text:
Q: Adding a custom singleton that is unique for each request I've been struggling to figure out the dependency pattern that comes with asp net core. Here is what I'm trying to achieve.
_ViewImports.cshtml
...
@inject AdminBuilder AdminBuilder
...

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHttpContextIshSingleton<AdminBuilder>();
    ...
}

AnyCSHtmlFile.cshtml
@AdminBuilder.AddStuff()
@AdminBuilder.EnableStuff()
@AdminBuilder.DoStuff()
// It'll then populate the AdminBuilder instance, which needs to be a unique instance for each visit.

Layout.cshtml
Here I'll render the AdminBuilder at the bottom from a partial .cshtml file, based on what's been added while rendering the page.

A: Use services.AddScoped<AdminBuilder>().
You can read more about the built in lifetimes in the official docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1#service-lifetimes


text:
Q: angular 2 ngIf Unexpected token # Hi everyone i'm study angular2 now im workind with *ngIf and i have this code

 0 ; then #coursesList else #noCourses'>

<ng-template #coursesList>

List of courses

</ng-template>
<ng-template #noCourses>

No courses yet

</ng-template>

And this is my component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    title = 'app hello';

    courses=[];
}

My problem is when i run the web site i have this error:
Uncaught Error: Template parse errors:
Parser Error: Unexpected token # at column 27 in [courses.length > 0 ; then
#coursesList else #noCourses] in ng:///AppModule/AppComponent.html@1:5 ("

Angular

]*ngIf='courses.length > 0 ; then #coursesList else
#noCourses'>

"): ng:///AppModule/AppComponent.html@1:5

I don't understand why i'm follow a guide in don't want use copy paste because i need know why is happen this

A: You need to remove the # in front of coursesList and noCourses. # is used only on the ng-template tag.

 0 ; then coursesList else noCourses'>


text:
Q: How to redirect http url to https for django application served by Apache What I want to achieve is when I browse for http://example.com:8080 it gets redirected to https://example.com:8080.
My web application is written in Django, and I have the following line in my settings:
SECURE_SSL_REDIRECT = True

The httpd configuration for example.com looks like this:
LISTEN 8080
<VirtualHost *:8080>
  ServerName example.com

  SSLEngine on
  SSLCertificateFile /path_to_cer
  SSLCertificateKeyFile /path_to_key
  SSLCertificateChainFile /path_to_iterm.cer

  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

  Alias /static /path_to_mysite/static
  <Directory /path_to_mysite/static>
      Require all granted
  </Directory>

  <Directory /path_to_mysite_wsgi_dir>
      <Files wsgi.py>
          Require all granted
      </Files>
  </Directory>

  WSGIDaemonProcess mysite python-path=/path_to_mysite:/path_to_mysite_python_packages display-name=%{GROUP}
  WSGIProcessGroup mysite
  WSGIApplicationGroup %{GLOBAL}
  WSGIScriptAlias / /path_to_mysite_wsgi.py
</VirtualHost>

with these configurations when I browse http://example.com, I will get the following error:
Bad Request
Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.

any thoughts?

A: You can redirect traffic from 8080 to https:
<VirtualHost *:8080>
  ServerName example.com
  RewriteEngine on
  RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

Then enable ssl on port 443, which is the default port for https requests:
<VirtualHost *:443>
  ServerName example.com

  SSLEngine on
  SSLCertificateFile /path_to_cer
  SSLCertificateKeyFile /path_to_key
  SSLCertificateChainFile /path_to_iterm.cer

  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

  Alias /static /path_to_mysite/static
  <Directory /path_to_mysite/static>
      Require all granted
  </Directory>

  <Directory /path_to_mysite_wsgi_dir>
      <Files wsgi.py>
          Require all granted
      </Files>
  </Directory>

  WSGIDaemonProcess mysite python-path=/path_to_mysite:/path_to_mysite_python_packages display-name=%{GROUP}
  WSGIProcessGroup mysite
  WSGIApplicationGroup %{GLOBAL}
  WSGIScriptAlias / /path_to_mysite_wsgi.py
</VirtualHost>


text:
Q: How to modify JSON response array to add new keys in NodeJS? I have a NodeJS function which is returning the following JSON array. It has all errors of type 1:
const data1 =
[
  {
    "ErrorType": "Error-1A",
    "Error": "wrong ip address for 1A",
    "SERVER_COUNT": 9
  },
  {
    "ErrorType": "Error-1B",
    "Error": "password incorrect for 1B",
    "SERVER_COUNT": 2
  },
....
]

I have another JSON array for all errors of type 2:
const data2 =
[
  {
    "ErrorType": "Error-2A",
    "Error": "wrong data for 2A",
    "SERVER_COUNT": 8
  },
  {
    "ErrorType": "Error-2B",
    "Error": "password incorrect for 2B",
    "SERVER_COUNT": 3
  },
....
]

I have another JSON array for all errors of type 3:
const data3 =
[
  {
    "ErrorType": "Error-3A",
    "Error": "wrong data for 3A",
    "SERVER_COUNT": 1
  },
  {
    "ErrorType": "Error-3B",
    "Error": "password incorrect for 3C",
    "SERVER_COUNT": 5
  },
....
]

I want to combine the 3 JSON arrays data1, data2, data3 and the final JSON object should look as below:
{
  "details1": {
   "9": {
    "ErrorType": "Error-1A",
    "Error": "wrong ip address for 1A"
   },
      "2": {
    "ErrorType": "Error-1B",
    "Error": "password incorrect for 1B"
   }
},
  "details2": {
   "8": {
    "ErrorType": "Error-2A",
    "Error": "wrong ip address for 2A"
   },
      "3": {
    "ErrorType": "Error-2B",
    "Error": "password incorrect for 2B"
   }
},
  "details3": {
   "1": {
    "ErrorType": "Error-3A",
    "Error": "wrong ip address for 3A"
   },
      "5": {
    "ErrorType": "Error-3B",
    "Error": "password incorrect for 3B"
   }
}
}

Please note that I want to add 3 new keys - details1, details2 and details3 - in the final response.
I also want to take out the SERVER_COUNT value and make it as a key.
I have added the following code but not sure to update it so as to get the final desired json
let finalData = Object.assign({}, ...data1.map(({
  SERVER_COUNT,
  ...rest
}) => ({
  [SERVER_COUNT]: rest
})));

Note: There are only 3 main keys and those are hard-coded details1 , details2, details13

A: You can put all your data arrays into one array called all_data, which you can then use .map() on to form an array of [detailsN, object] entries. Here detailsN represents your key for your outer object and the object represents the object for each detail key. Once you have mapped your all_data to entries, you can use Object.fromEntries() to convert it into an object.
The object component for the entires can be formed by mapping the data from each data array into [SERVER_COUNT, obj] entries, which you can then called Object.fromEntries() to convert the array of mapped entries into an object.

const data1 = [ { "ErrorType": "Error-1A", "Error": "wrong ip address for 1A", "SERVER_COUNT": 9 }, { "ErrorType": "Error-1B", "Error": "password incorrect for 1B", "SERVER_COUNT": 2 }, ];
const data2 = [ { "ErrorType": "Error-2A", "Error": "wrong data for 2A", "SERVER_COUNT": 8 }, { "ErrorType": "Error-2B", "Error": "password incorrect for 2B", "SERVER_COUNT": 3 }, ];
const data3 = [ { "ErrorType": "Error-3A", "Error": "wrong data for 3A", "SERVER_COUNT": 1 }, { "ErrorType": "Error-3B", "Error": "password incorrect for 3C", "SERVER_COUNT": 5 }, ];

const keys = ["details1", "details2", "details3"];
const all_data = [data1, data2, data3];
const res = Object.fromEntries(all_data.map((data, i) => [
  keys[i],
  Object.fromEntries(data.map(({SERVER_COUNT, ...r}) => [SERVER_COUNT, r]))
]));
console.log(res);

A: Loop over the array elements, turning each of them into an object property using the SERVER_COUNT property as the key.

function dataToDetails (data) {
  let result = {};
  data.forEach(({ErrorType, Error, SERVER_COUNT}) => result[SERVER_COUNT] = {ErrorType, Error});
  return result;
}

const data1 =
[
  {
    "ErrorType": "Error-1A",
    "Error": "wrong ip address for 1A",
    "SERVER_COUNT": 9
  },
  {
    "ErrorType": "Error-1B",
    "Error": "password incorrect for 1B",
    "SERVER_COUNT": 2
  },

];

const data2 =
[
  {
    "ErrorType": "Error-2A",
    "Error": "wrong data for 2A",
    "SERVER_COUNT": 8
  },
  {
    "ErrorType": "Error-2B",
    "Error": "password incorrect for 2B",
    "SERVER_COUNT": 3
  },

];

const data3 =
[
  {
    "ErrorType": "Error-3A",
    "Error": "wrong data for 3A",
    "SERVER_COUNT": 1
  },
  {
    "ErrorType": "Error-3B",
    "Error": "password incorrect for 3C",
    "SERVER_COUNT": 5
  },

];

let finalData = {
  details1: dataToDetails(data1),
  details2: dataToDetails(data2),
  details3: dataToDetails(data3)
};

console.log(finalData);

A: JS pseudokode:.

*

*Parse all joson to objects

*Object.assigne or {...obj1, ...objt2};

*transform object to json

const data1 =
[
  {
    "ErrorType": "Error-1A",
    "Error": "wrong ip address for 1A",
    "SERVER_COUNT": 9
  },
  {
    "ErrorType": "Error-1B",
    "Error": "password incorrect for 1B",
    "SERVER_COUNT": 2
  }
]

const data2 =
[
  {
    "ErrorType": "Error-2A",
    "Error": "wrong data for 2A",
    "SERVER_COUNT": 8
  },
  {
    "ErrorType": "Error-2B",
    "Error": "password incorrect for 2B",
    "SERVER_COUNT": 3
  }
]

const data3 =
[
  {
    "ErrorType": "Error-3A",
    "Error": "wrong data for 3A",
    "SERVER_COUNT": 1
  },
  {
    "ErrorType": "Error-3B",
    "Error": "password incorrect for 3C",
    "SERVER_COUNT": 5
  }
]

console.log([data1, data2, data3].reduce((acc, cur, i) => Object.assign(acc, {["detailist" + i]: {...cur}}), {}))

JS BIN

A: If you have an object structure like myObj={} you can add keys or properties like:
myObj.myKeyOrProperty = 'The data here';

// or

myObj.['myKeyOrProperty'] = 'The data here';

you need to serialize or deserialize to or from JSON to do that in request / response.
If you have a JSON response like an array of objects use:
array.push(myAwesomeObj-A);
array.push(myAwesomeObj-B);
array.push(myAwesomeObj-C);
etc...

When you have the desired data structure emit the response as:
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"myDataKey": ---your data must be here in a JSON string format---
}


text:
Q: How to use no_proxy on Linux machines - wildcards, leading dots I am puzzled by the no_proxy environment variable on Linux.
There are many instructions on the internet that show leading dots for example .localdomain.com https://stackoverflow.com/a/19719875/202576
export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"

This example is used in relation to using wget. I can't however confirm that this works. For example on Ubuntu 18.04 I have remove the leading dot to get it to work. Note I am using a sub domain for example wget mysite.localdomain.com.
export no_proxy="localhost,127.0.0.1,localaddress,localdomain.com"

When I use a curl it will work with a leading dot.
So it seems that the way no_proxy should be configured depends on the tool? It is different for curl and wget.
Is there a convention for no_proxy that will work for all tools?
I suppose writing out each and every full domain name will work.

A: There is no standard, that I'm aware of, so what you need to set/use depends on the implementation of the tool you use. Curl will work with a leading dot as it strips it whereas wget won't work (doesn't strip it).
Read some detailed analysis at https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/:
Excerpt from that article:

However, if there is a leading . in the no_proxy setting, the behavior
varies. For example, curl and wget behave differently. curl will
always strip the leading . and match against a domain suffix. This
call bypasses the proxy:
$ env https_proxy=http://non.existent/ no_proxy=.gitlab.com curl https://gitlab.com
You are being  href="https://about.gitlab.com/">redirected.

However, wget does not strip the leading . and performs an exact
string match against a hostname. As a result, wget attempts to use a
proxy if a top-level domain is used:
$ env https_proxy=http://non.existent/ no_proxy=.gitlab.com wget https://gitlab.com
Resolving non.existent (non.existent)... failed: Name or service not known.
wget: unable to resolve host address 'non.existent' ```


text:
Q: textarea post into mysql not working I have a textarea in a form that im trying to POST into a mysql database.  However, when i insert the values, i get about 5 lines in the database. 4 of them have no information or minimal information and one of the lines is how i want it.  How can i get rid of the other four lines? thanks.
EDIT:  actually none of the lines have all the right info in the right spots and i have double checked the inset statement to make sure everything lines up.
the code:
<form method='POST' action="index.php">
<textarea id ='answerbox' autocomplete='off' cols="80" rows="5" name='answer'></textarea>
<input type='submit' value='submit'>

<?php
    include 'connect.php';
    $date=date("Y-m-d");
    $time=time();
            $answer=['answer'];
    $user=$_SESSION['username'];
    $id=$_GET['id'];
    $put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
    ?>

A: Your textarea is named as "answer" while its ID is "answerbox".  You should be able to retrieve its value through $_POST['answer'];

A:

Try:
<?php
    if($_POST['answer'] != '')
    {
       include 'connect.php';
       $date=date("Y-m-d");
       $time=time();

       $answer= $_POST['answer'];
       $user=$_SESSION['username'];
       $id=$_GET['id'];
       $put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
    }
    ?>


text:
Q: Clear all bookmarks from Intellij Currently, I can add bookmarks on Itellij by the shortcut key ctrl+f11. For removing that bookmark, I need to go to that line and press the same shortcut key. Now I want to delete all bookmarks at once without removing them one by one.
How do I remove all bookmarks from Intellij? Is there any shortcut?

A: I got the answer here:

Shift+F11 (Show bookmarks), select all bookmarks with Shift, hit Delete.


text:
Q: fill UIBezierPath but keep path clear Can't find solution for fill closed UIBezierPath with some color and some width, but keep the path line transparent.
[[UIColor clearColor] setStroke] does not work.

What i have:

What i want:

Shared line of two rectangles have same coordinates, that's why i need some shift when i draw them.

A: If what you are trying to do is erase everything within the thick outline of a path, use CGContextReplacePathWithStrokedPath to convert the stroke to a path. Then fill it with a clear blend mode, thus erasing the drawing along the thick path. Alternatively, just stroke the path, again using a clear blend mode.
In this drawing, the thick yellow ellipse is not stroked or filled yellow; the ellipse is clear, and the yellow is the view behind, seen through the red rectangle. In other words, the ellipse erases an elliptical shape through the red rectangle.

Here's the code that drew the ellipse:
    CGContextAddEllipseInRect(con, CGRectMake(100,100,200,50))
    CGContextSetLineWidth(con, 10)
    CGContextSetBlendMode(con, kCGBlendModeClear)
    CGContextReplacePathWithStrokedPath(con)
    CGContextFillPath(con)

Or you could do it this way:
    CGContextAddEllipseInRect(con, CGRectMake(100,100,200,50))
    CGContextSetLineWidth(con, 10)
    CGContextSetBlendMode(con, kCGBlendModeClear)
    CGContextStrokePath(con)

A: stroking with [UIColor clearColor] is not the same thing as taking an eraser to the fill you've already done, it is just drawing over it with a pen with transparent ink.
You could make a second path with pathByStrokingPath and then use an EOClip to 'mask' this area from your fill, or you can just stroke your path with whatever backgroundColor is behind...


text:
Q: Public classes in custom framework In my custom framework, if i want to expose some classes/methods to swift or objective-c, i have to declare them as public, but with this method the classes and methods are exposed in the framework header.
Is there a way to prevent to expose the methods to framework header?

A: If your framework is written in Swift, then use Access Levels - public, open, internal, file-private or private - documentation. You probably want to use internal
If your framework is written in Objective-C, you can use forward declaration. Instead of writing
// ClassA.h

#import "ClassB.h"

@interface ClassA : NSObject

- (void)doSomethingWithClassB:(ClassB*)obj;

@end

Write
// ClassA.h

@class ClassB;

@interface ClassA : NSObject

- (void)doSomethingWithClassB:(ClassB*)obj;

@end

// ClassA.m

#import "ClassB.h"

If your ClassA doesn't inherit from ClassB, you can forward declare ClassB in you ClassA header - in the header you're not calling any methods from ClassB, you just use a pointer to it, so the compiler doesn't need to know the full signature of ClassB. Instead, you promise that you will include the full definition of ClassB before actually trying to use it.


text:
Q: diaplying a specific number the result of a diference between 2 numbers minus a certain percentage First i want to say i have  zero knowledge of js or any coding so i am just trying here.
I have a script that tells me, in console log, the simulated result of a battle between 2 opponents. But now the system has changed and  i receive points based on the HP left, after the battle ends, in increments of 10% of the hp lost. So if i have 100 hp and i lose 10,  90 hp gets me 25 points , 91 still 25 points ,  89 -24 points ...etc lower with each 10% lost.
So i have tried to write the code below (admitting idk if i wrote it correctly)
matchRating = playerHP - opponentHP;
 if (matchRating >= playerHP - 10%) {
    matchRating = '25';
    }
else if (matchRating >= playerHP - 20%) {
    matchRating = '24';
    }
else if (matchRating >= playerHP - 30%) {
    matchRating = '23';
    }
else if (matchRating >= playerHP - 40%) {
    matchRating = '22';
    }
else if (matchRating >= playerHP - 50%) {
    matchRating = '21';
    }
else if (matchRating >= playerHP - 60%) {
    matchRating = '20';
    }
else if (matchRating >= playerHP - 70%) {
    matchRating = '19';
    }
else if (matchRating >= playerHP - 80%) {
    matchRating = '18' ;
    }
else if (matchRating >= playerHP - 90%) {
    matchRating = '17';
    }

i get an Parsing error  unexpected token. and it doe not work

A: Okay, so first of all, let's map HP to points:
`90-100` HP == `25` points
`80-90` HP == `24` points
`70-80` HP == `23` points
`60-70` HP == `22` points
`50-60` HP == `21` points
`40-50` HP == `20` points
`30-40` HP == `19` points
`20-30` HP == `18` points
`10-20` HP == `17` points
`0-10` HP == `16` points (but this you don't stated) ...

So result is that you start at 16 points and multiply it by HP / 10 because 10 HP will icrease the points by 1
So the formula should be
var matchRating = playerHP - opponentHP;
var points = 16 + Math.floor(matchRating / 10)


text:
Q: Getting ERROR: script returned exit code 1 while testing Getting below build output- I need to know the reason behind FAILURE (all required packages were pre-installed)
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /opt/bitnami/jenkins/jenkins_home/workspace/testing-xx
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ npm -s run test
Test Suites: 4 passed, 4 total
Tests:       20 passed, 20 total
Snapshots:   1 obsolete, 3 passed, 3 total
Time:        6.88s
Ran all test suites.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE

Please help me understand the reason and resolution (I have removed few outputs to shorten)


text:
Q: Perform a where() on ALL columns in a model (Laravel) I'd like to do a where() on ALL columns within my model, for example in ANY column I'd like to find the string "123", not just for a single column ALL columns (without chaining a whereOr()
For example, the database has
| Title | Body1 | Body2| Body3|
My Model    foo      foo    123
and then do a where() on all columns.
Thank you in advance

A: I think if you aren't going to chain where(), this is the best way to do this.
    $columns = ['Title','Body1','Body2','Body3'];
    $query = ModelName::select('*');
    foreach($columns as $column)
    {
     $query->orWhere($column, '=', '123');
   }
   $models = $query->get();

This may save like a small but considerable chunk of time as compared to chaining a bunch of where() statements in your code.
Hope this helped !!!


text: Q: How to create DirectX shader from intermediate language I need to be able to create a shader from a disassembled cso file created with fxc targeting vs_4_0. Is there a way under DirectX11 to use IL text to create a vertex shader?


text:
Q: Merge nested array of objects in JavaScript I have an array of objects with a nested array of objects like:
var cars = [
  {
    Plate: '112211',
    Details:
      [
        {
          Desc: 'Blah11 Blah Blah',
        Miles: '111',
        Color: 'blue'
        },
        {
          Desc: 'Blah B22lah Blah',
        Miles: '222',
        Color: 'green'
        },
      ],
      Make:'Honda'
  },
      Plate: '223322',
    Details:
      [
        {
          Desc: 'Blah Blah B33lah',
        Miles: '333',
        Color: 'yellow'
        },
        {
          Desc: 'Blah B44lah Blah',
        Miles: '444',
        Color: 'red'
        }
      ],
      Make:'GMC'
  },
      Plate: '334433',
    Details:
      [
        {
          Desc: 'Bl55ah Blah Blah',
        Miles: '555',
        Color: 'blue'
        },
        {
          Desc: 'Blah B66lah Blah',
        Miles: '666',
        Color: 'pink'
        },
      ],
      Make:'Ford'
  }
]

I am trying to find a way to turn it into a new array that flattens or merges the nested array. The goal would be to have something like:
[
  {
    Plate: '112211',
    Desc: 'Blah11 Blah Blah',
    Miles: '111',
    Color: 'blue',
    Make:'Honda'
  },
  {
    Plate: '112211',
    Desc: 'Blah B22lah Blah',
    Miles: '222',
    Color: 'green',
    Make: 'Honda'
    },
    {
    Plate: '223322',
    Desc: 'Blah Blah B333lah',
    Miles: '333',
    Color: 'yellow'
    Make: 'GMC'
    },
    {
    Plate: '223322',
    Desc: 'Blah Bl444ah B33lah',
    Miles: '444',
    Color: 'red',
    Make: 'GMC'
    },
    {
    Plate: '334433',
    Desc: 'Bl555ah Blah B33lah',
    Miles: '555',
    Color: 'blue',
    Make: 'Ford'
    },
    {
    Plate: '334433',
    Desc: 'Blah Bl666ah B33lah',
    Miles: '666',
    Color: 'pink',
    Make: 'Ford'
    },
]

lodash _.flatten and _.flattenDeep didn't do anything. I have also tried doing a _.chain and flatten to build a new array, but that come up empty
var actions = _.chain(cars).flatten("Details");

        for (i = 0; i < cars.length; i++) {
            actions.each(function(action) {
                list.push(cars[i].Plate);
                list.push(action);
                list.push(cars[i].Make);

A: Here is the code

function merge(collection) {
  return _(collection).map(function(obj) {
      return _(obj)
        .pickBy(_.isArray)
        .values()
        .flatten()
        .map(function(dest) {
          return _.merge(dest, _.omitBy(obj, _.isArray));
        })
        .value();
    })
    .flatten()
    .value();
}

var cars = [{
  Plate: '112211',
  Details: [{
    Desc: 'Blah11 Blah Blah',
    Miles: '111',
    Color: 'blue'
  }, {
    Desc: 'Blah B22lah Blah',
    Miles: '222',
    Color: 'green'
  }],
  Make: 'Honda'
}, {
  Plate: '223322',
  Details: [{
    Desc: 'Blah Blah B33lah',
    Miles: '333',
    Color: 'yellow'
  }, {
    Desc: 'Blah B44lah Blah',
    Miles: '444',
    Color: 'red'
  }],
  Make: 'GMC'
}, {
  Plate: '334433',
  Details: [{
    Desc: 'Bl55ah Blah Blah',
    Miles: '555',
    Color: 'blue'
  }, {
    Desc: 'Blah B66lah Blah',
    Miles: '666',
    Color: 'pink'
  }],
  Make: 'Ford'
}];

var result = merge(cars);
document.querySelector('#result').innerHTML = JSON.stringify(result, null, 2);

A: There may be a better way to do this, but this gets the job done:

var cars = [
  {
    Plate: '112211',
    Details:
      [
        {
          Desc: 'Blah11 Blah Blah',
        Miles: '111',
        Color: 'blue'
        },
        {
          Desc: 'Blah B22lah Blah',
        Miles: '222',
        Color: 'green'
        },
      ],
      Make:'Honda'
  },
  {
      Plate: '223322',
    Details:
      [
        {
          Desc: 'Blah Blah B33lah',
        Miles: '333',
        Color: 'yellow'
        },
        {
          Desc: 'Blah B44lah Blah',
        Miles: '444',
        Color: 'red'
        }
      ],
      Make:'GMC'
  },
  {
      Plate: '334433',
    Details:
      [
        {
          Desc: 'Bl55ah Blah Blah',
        Miles: '555',
        Color: 'blue'
        },
        {
          Desc: 'Blah B66lah Blah',
        Miles: '666',
        Color: 'pink'
        },
      ],
      Make:'Ford'
  }
];

var details = [];
_.each(cars, function(car) {
  var keys = _.keys(car);
  _.each(car.Details, function(dtl) {
    _.each(keys, function(key) {
      if (key !== 'Details') {
        dtl[key] = car[key];
      }
    });
    details.push(dtl);
  });
});

console.log(details);

document.querySelector('#details').innerHTML = JSON.stringify(details);
document.querySelector('#numDetails').innerHTML = details.length;

I am sure there's a cleaner way (using _.filter or some such) to remove 'Details' from the keys, but it's sleepy where I am ;).

A: If flattening won't work, you can just reduce. Here I construct each of the cars given using the params in details so they can remain monomorphic while they're being flattened and beyond, if you choose.
Ideally the way you have your state set up shouldn't have to have separate keys under the details one. It's simpler to avoid nesting them or keep them on objects that really use them, if that's the case.

function flattenCarList(prevCars, car) {
  var Details = car.Details;
  delete car.Details;

  var carProto = Object.create(car.prototype || null)
  var keys = Object.keys(Details);
  for (var i = 0; i < keys.length; i++) {
    Details[i] = carProto[i] = keys[i];
  }

  var carSet = [];
  for (var i = 0; i < Details.length; i++) {
    carSet.push(new Details[i]);
  }

  return prevCars.concat(carSet);
}

var cars = [{
  Make: 'Edzel',
  Plate: 123456,
  Details: {
    Desc: 'Don\'t ask',
    Miles: 32,
    Colour: 'Sickly Green'
  }
}];

// Now let's really get to the point.
cars.reduce(flattenCarList);

document.getElementById('status').innerHTML += 'RESULTS:
' + JSON.stringify(cars);


text:
Q: Is there any Windows Message for detecting network cable is plugged or unplugged? I made some MFC program using multiple Network Interface Cables.
This program show current usable NICs.
I just want how i can get notify when the network cable is plugged or unplugged.
It must be run on windows XP.


text:
Q: Hadoop - datanode not running in slave Im trying to setup a cluster hadoop environment but unable to start the data node in the slave.
Here is my logs from the master node -
hduser@vagrant:/usr/local/hadoop/sbin$ bash start-dfs.sh15/12/29 20:04:32 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Starting namenodes on [master]
master: namenode running as process 5633. Stop it first.
slave: starting datanode, logging to /usr/local/hadoop/logs/hadoop-hduser-datanode-vagrant.out
master: datanode running as process 3362. Stop it first.
localhost: datanode running as process 3362. Stop it first.
Starting secondary namenodes [0.0.0.0]
0.0.0.0: secondarynamenode running as process 3527. Stop it first.
15/12/29 20:04:42 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
hduser@vagrant:/usr/local/hadoop/sbin$
hduser@vagrant:/usr/local/hadoop/sbin$ jps
3527 SecondaryNameNode
3362 DataNode
5633 NameNode
6765 Jps

From the logs above it looks like it started but here is the slave node jps command -
hduser@vagrant:/usr/local/hadoop/logs$ jps
3135 Jps

Don't see the datanode running.

A: It looks like you did not put your slave address in /etc/hosts. Check it out. If It is OK, check the slave's logs then.


text:
Q: Accessing a Property of an odt File? I asked lately how i can access the meta data of a odt file and the most recomended way to do this was using the apache tika library.
I tried finding out how i can use this Libraries in Detail.
Reading through all this stuff I find that this tika service is pretty hard (at least for someone that is new to Programming like me)
So my question is if maybe someone has a link to a side where there is like a step by step tutorial on how to use it or maybe as a different method to do this. I realy dont want you to do my work but i am working so long on this now and did not get this far so i think its time to ask for help here. :(
I want to acces and set only one property of my file which is the "DocumentID".
Thank you for helping and sorry for my maybe bad english but it is not my foreign language.


text:
Q: Improve design movement on Snake game I am trying to improve my game development design and for now I have something like this:
class Movement {
private:
  Body b;
public:
  move_up() {
    // catch the body head
    // add one snake character above head
    // catch the body tail
    // remove the tail character
  }
  move_down(){
    // catch the body head
    // add one snake character below head
    // catch the body tail
    // remove the tail character
  }
  move_left(){
    // catch the body head
    // add one snake character on left side of head
    // catch the body tail
    // remove the tail character
  }
  move_right(){
    // catch the body head
    // add one snake character on right side of head
    // catch the body tail
    // remove the tail character
  }
}

It is pretty ugly to see repetead pseudocode inside each move method. I would like to make this more generic but I don't know how to do it in C++. Any suggestions?

A: For a snake game, you probably want to handle this in two separate pieces.
One piece responds to keyboard input. All it does is record a new direction of travel based on the input key.
The other piece runs at predefined intervals. It:

*

*checks for collision

*

*and ends game if there is one

*adds a character to the head of the snake in the current direction of travel

*removes a character from the tail

*

*(provided the snake didn't just eat a power button)

*updates the score

*and probably a few more things that don't occur to me right now

In particular, however, we don't want any of the second list to wait for input from the user. The second part just runs continuously, so the snake keeps moving even in the absence of input from the user.

A: I've made Snake before, these are the steps used in my program to make Snake happen;

*

*When the direction of the snake is changed, it must check it wasn't going in the 180°-rotated direction before, otherwise the current direction may not change.

*The methods you described in your post must only contain what's needed to add one dot/pixel/character to the snake, next to the current position of the snake.

*You need a list of all dots of the snake (containing x,y values).

*On every move, you must, first of all make sure you're not crashing into yourself or into a wall, else you should die first.

*On every move, if a move was succesfull, you must check if your current position (last move) contains food on that same position, if yes, add a score to the score variable and make sure you don't remove the oldest (x,y) of the snake's list.
If not, you must remove that one.


text:
Q: Can we access STDClass object with bracket notation in Lumen laravel freamwork code snippet as below:
$userinfo = DB::table('userinfo')
            ->select('addressid', 'extradetailid', 'mobileno')
            ->where('mobileno', $detail['mobileno'])
            ->get()
            ->toArray();

$users = DB::table('user')
            ->select('name', 'age', 'contact', 'addressid','extradetailid')
            ->where(function ($qb1) use ($userinfo) {
                $qb1->whereIn('addressid', array_column($userinfo, 'addressid'))
                    ->orWhereIn('extradetailid', array_column($userinfo, 'extradetailid'));
            })
            ->orderBy('sort', 'ASC')
            ->get()
            ->toArray();

 foreach ($users as $user) {
        if ($user['addressid'] != null) { // getting error here Cannot use object of type stdClass as array

        }
}

My PHP version is 7.3
I am using the AMPP apache server.
I want to use an object with the bracket notation. Is there any way to do that in the PHP lumen laravel framework?

A: Before looping $users variable first try to convert it to array. Check if this works:
$users = json_decode(json_encode($users), true);


text:
Q: Setting mean value for Poisson subsampling I'm running a machine learning algorithm in federated settings  where participants collaboratively build a model by participating in the training rounds.
At each training round, I need to sample a fixed number of participants, say 100 out of a total population of 500 to participate in the training.
The selection of participants should be based on poisson subsampling such that each participants is drawn with subsampling probability of 100/500.
I perform poisson subsampling with randomly selected lambda from the range [0,500], and keep subsampling with random lambda values until the 100 participants are drawn.
A small python snippet below
sampled_ids = []
participants_size = 100
population_size = 500

while len(sampled_ids) < participants_size:

  lambda_value = np.random.random_integers(low=0, high=population_size, size=1)

  subsampling = np.random.poisson(lam=lambda_value, size=participants_size)

  for i in range(len(subsampling)):
           if len(sampled_ids) < participants_size:
                    sampled_ids.append(instance)

Is there any better strategy for setting the lambda other than random selection so the 100 participants are drawn with probability p = participants_size/population_size ?


text:
Q: SOAP request sent from SUDS has '\n' in xml tags I am using SUDS to call a SOAP web service. How ever the when I see the XML sent by SUDS, lines breaks '\n' characters are added to xml tags.
I am assuming \n in xml does not make an issue. But is there a way I can remove \n from the xml generated by SUDS.
sample given below:
<ns0:Body><ns1:getMemberEligibility><ns1:memberEligibilityRequest>\n                <clientId>1</clientId>\n                <ns7:customerId>732</ns7:customerId>\n                <ns7:firstName>PPP</ns7:firstName>\n                <ns7:groupExternalId>0001</ns7:groupExternalId>\n                <ns7:lastName>MMM</ns7:lastName>\n                <ns7:birthDate>1950-03-21</ns7:birthDate>\n                <ns7:memberId>19500123MMMPPP</ns7:memberId>\n                <ns7:relationship>\n                    01\n                </ns7:relationship>\n</ns1:memberEligibilityRequest></ns1:getMemberEligibility></ns0:Body>


text:
Q: Implicit declaration of function of a declared prototype I have this error code:

helpers.c:56:13: warning: implicit declaration of function 'swap' is invalid in
C99 [-Wimplicit-function-declaration]
swap(height, width, image, i, j);
^
helpers.c:62:6: error: conflicting types for 'swap'
void swap(int height, int width, RGBTRIPLE image[height][width], int row...
^
helpers.c:56:13: note: previous implicit declaration is here
swap(height, width, image, i, j);
^
helpers.c:75:31: warning: implicit declaration of function 'value' is invalid in
C99 [-Wimplicit-function-declaration]
image_new[i][j] = value(height, width, image, i, j);
^
helpers.c:75:29: error: assigning to 'RGBTRIPLE' from incompatible type 'int'
image_new[i][j] = value(height, width, image, i, j);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
helpers.c:87:11: error: conflicting types for 'value'
RGBTRIPLE value(int height, int width, RGBTRIPLE image[height][width], i...
^
helpers.c:75:31: note: previous implicit declaration is here
image_new[i][j] = value(height, width, image, i, j);
^

I understand that implicit declaration of function is linked with not having a function prototype but in my case i do have one.
helpers.c
#include "helpers.h"
#include <math.h>
#include <cs50.h>

// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width]){
    int average = 0;
    RGBTRIPLE dot;

    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            dot = image[i][j];
            average = round((dot.rgbtRed + dot.rgbtGreen + dot.rgbtBlue) / 3.0);

            image[i][j].rgbtRed = average;
            image[i][j].rgbtGreen = average;
            image[i][j].rgbtBlue = average;
        }
    }
    return;
}

int max(int value){
    if(value > 255){
        return 255;
    }
    else{
        return value;
    }
}

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width]){

    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            RGBTRIPLE dot = image[i][j];
            image[i][j].rgbtRed = max(round(0.393 * dot.rgbtRed + 0.769 * dot.rgbtGreen + 0.189 * dot.rgbtBlue));
            image[i][j].rgbtGreen = max(round(0.349 * dot.rgbtRed + 0.686 * dot.rgbtGreen + 0.168 * dot.rgbtBlue));
            image[i][j].rgbtBlue = max(round(0.272 * dot.rgbtRed + 0.534 * dot.rgbtGreen + 0.131 * dot.rgbtBlue));
        }
    }
    return;
}

// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width]){
    int n;

    if(width % 2 != 0){
        n = 1;
    }

    for(int i = 0; i < height; i++){
        for(int j = 0, k = (width - n) / 2; j < k; j++){
            swap(height, width, image, i, j);
        }
    }
    return;
}

void swap(int height, int width, RGBTRIPLE image[height][width], int row, int pix){

    RGBTRIPLE temp = image[row][pix];
    image[row][pix] = image[row][width - pix];
    image[row][width - pix] = temp;
}

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width]){
    RGBTRIPLE image_new[height][width];

    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            image_new[i][j] = value(height, width, image, i, j);
        }
    }

    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            image[i][j] = image_new[i][j];
        }
    }
    return;
}

RGBTRIPLE value(int height, int width, RGBTRIPLE image[height][width], int x, int y){
    int count = 0;
    int red = 0;
    int blue = 0;
    int green = 0;
    RGBTRIPLE dot;

    for(int i = -1; i <= 1; i++){
        for(int j = -1; j <= 1; j++){
            int length = i + x;
            int spread = j + y;

            if((length >= 0) && (length < height) && (spread >= 0) && (spread < width)){
                red += image[length][spread].rgbtRed;
                blue += image[length][spread].rgbtBlue;
                green += image[length][spread].rgbtGreen;
                count++;
            }
        }
    }

    dot.rgbtRed = round((float)red / count);
    dot.rgbtBlue = round((float)blue / count);
    dot.rgbtGreen = round((float)green / count);

    return dot;
}

helpers.h
#include "bmp.h"

// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width]);

// Check if color value is within limit
int max(int value);

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width]);

// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width]);

// Swapping pixel
void swap(int height, int width, RGBTRIPLE image[height][width], int row, int pix);

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width]);

RGBTRIPLE value(int height, int width, RGBTRIPLE image[height][width], int x, int y);

bmp.h
    // BMP-related data types based on Microsoft's own

#include <stdint.h>

/**
 * Common Data Types
 *
 * The data types in this section are essentially aliases for C/C++
 * primitive data types.
 *
 * Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx.
 * See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
 */
typedef uint8_t  BYTE;
typedef uint32_t DWORD;
typedef int32_t  LONG;
typedef uint16_t WORD;

/**
 * BITMAPFILEHEADER
 *
 * The BITMAPFILEHEADER structure contains information about the type, size,
 * and layout of a file that contains a DIB [device-independent bitmap].
 *
 * Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx.
 */
typedef struct
{
    WORD   bfType;
    DWORD  bfSize;
    WORD   bfReserved1;
    WORD   bfReserved2;
    DWORD  bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;

/**
 * BITMAPINFOHEADER
 *
 * The BITMAPINFOHEADER structure contains information about the
 * dimensions and color format of a DIB [device-independent bitmap].
 *
 * Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx.
 */
typedef struct
{
    DWORD  biSize;
    LONG   biWidth;
    LONG   biHeight;
    WORD   biPlanes;
    WORD   biBitCount;
    DWORD  biCompression;
    DWORD  biSizeImage;
    LONG   biXPelsPerMeter;
    LONG   biYPelsPerMeter;
    DWORD  biClrUsed;
    DWORD  biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;

/**
 * RGBTRIPLE
 *
 * This structure describes a color consisting of relative intensities of
 * red, green, and blue.
 *
 * Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx.
 */
typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

I can not think of any way of why this would be wrong.
The code compiles perfectly fine when I do it but on the CS50 compiler, I get those error codes. I tried using my code and saw that the image outcome were coming out right. So I am confused to why am i receiving those errors.
Edit 1:
Deleting the return statement in void type functions still does not remove the error.
Edit 2: Link to entire code on a online ide
Edit 4: clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -Qunused-arguments -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow -o filter filter.c helpers.c
I am compiling the only two files i can compile which is filter.c and helpers.c

A: As I looked through the code, I noticed in void reflected() and void blur(), I have two custom functions inside of it that were declared after it resulting in the compiler to assume that the custom functions 'don't exist'.
To fix the problem, move the custom function before the function it is called in to avoid the errors. In this case, swap() should be declared or put before void reflected() and same case with RGBTRIPLE value() and `void blur()


text:
Q: RxJava+Retrofit+Gson JsonSyntaxException on server error response I have REST POST call create order as Observable<OrderResponse>, when order create call is successful everything is fine, but then server returns error I get com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ because Gson does not know how to handle json that have different fields than my response model
Server error response:
[{
    "code": 99,
    "message": "Please check your request"
}]

OrderResponse
data class OrderResponse(

    @Expose
    var orderId: String,

    @Expose
    var redirectUrl: String,

    @Expose
    var validUntil: Long

)
RxJava subscription
repository.requestCreateNewOrder(newOrder)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<OrderResponse> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                            compositeDisposable.add(d)
                        }

                        override fun onNext(t: OrderResponse) {
                        }

                        override fun onError(t: Throwable) {
                          //HERE I GET JsonSyntaxException
                        }
                    })

Retrofit Service
interface OrderService {
@Headers(
        "Content-Type: application/x-www-form-urlencoded ",
        "Connection: Keep-Alive",
        "Accept-Encoding: application/json",
        "User-Agent: Fiddler"
)
@FormUrlEncoded
@POST("/createOrder")
fun createOrder(@Field("orderId") orderId: String,
                @Field("payCurrency") payCurrency: String,
                @Field("payAmount") payAmount: Double,
                @Header("Content-Length") length: Int): Observable<OrderResponse>}

Anyone have any suggestions for how to pass retrofit or gson the error model to know how to handle it

A: As you are using GSON to parse the JSON.
Your JSON sucessfull response will be something like
{
    "orderId": 1,
    "redirectUrl": "url",
    "validUntil": 12414194
}

while for error response your JSON response start with Array.
[{
    "code": 99,
    "message": "Please check your request"
}]

So tell to server guy to not add the error response in Array [].
If you are getting the response as Array then you have to use list.
repository.requestCreateNewOrder(newOrder)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<List<OrderResponse>> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                            compositeDisposable.add(d)
                        }

                        override fun onNext(t: OrderResponse) {
                        }

                        override fun onError(t: Throwable) {
                          //HERE I GET JsonSyntaxException
                        }
                    })

In Observer response you have to add as List if your JSON response start with Array like error.
Solution : Correct it from backend for not adding Error Response in ARRAY.

A: As per your code you are only handling the success response
but you need to handle your error response too for this you need to ensure that your API should send you error codes different then 200 (success response generally greater then 200 and less then 300 i.e code >= 200 && code < 300 ) because retrofit consider 200-299 as success
You can achieve this simply by changing your observable return type to
 Observable<Response< OrderResponse>>

and after receiving response from server simply check
           if (orderResponse.isSuccessful()) {
              //here you can handle success by using orderResponse.getbody()
            } else {
                 // here you can display error message and if you further want
                // to parse error response from server then use below function
                errorOrderResponseHandling(orderResponse);
            }

you want to further parse response into error model(in this example OrderAPIError is model class for error response) then below is the function
 private void errorOrderResponseHandling(Response<OrderResponse> orderResponse) {
        OrderAPIError orderAPIError = null;
        try {
            orderAPIError = new Gson().fromJson(String.valueOf(new
            JSONObject(orderResponse.errorBody().string())), OrderAPIError.class);
           // further orderAPIError object you can fetch server message and display
            it to user as per your requirement
        } catch (JSONException e) {
            e.printStackTrace();

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

        }
    }

Above example is in android not in kotlin but you can get idea and use function accordingly in kotlin


text:
Q: How can I catch all the url requests of a specific directory? Suppose that we have all these URLs:
http://www.xxx.co/directory/something
http://www.xxx.co/directory/somethingelse
https://www.xxx.co/directory/somethinginHTTPS
http://www.xxx.co/directory/something/withotherthing
http://www.xxx.co/directory/something/page.html

I need a .htaccess inside the directory "directory" to catch all these URLs that get into that directory and process them at
http://www.xxx.co/directory/index.php

without changing the original URL in the browser.
How can I do that?
ANSWER ===================================================
I have found a solution but I have forgotten to paste it here. So here it is. Inside the "directory" folder, place a .htaccess file with the following code.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ ./index.php [QSA,L]
</IfModule>

Then in the index.php inside the same folder, you can inspect the requested address and work with it.
<?php
$url =parse_url((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

echo "<pre>";
echo $url["path"];
echo "</pre>";
?>