text:
Q: Achar item no array Gostaria de saber se meu código está certo. pois gostaria de pegar o nome vinculado com que está vinculado com o código(id), onde mmot recebe um numero para ser procurado dentro do array. Obrigado
    $url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

    function get_page($url){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

        foreach ($result as $key) {
            if($key['codigo'] == $mmot){
                $mmot = $key['$mmot']['nome'];
            }
        }

    }

    $marcafinal = $mmot;

A: Essa forma da certo e nem precisa usar o curl, caso precise só editar da forma que achar melhor, exemplo funcionando:
 <?php
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');
$mmot = "60";

function get_page($url,$mmot){
    $result = json_decode($url,true);

    foreach($result as $key)
    {
        if($key['codigo'] == $mmot)
        {
            return $key['nome'];
        }
    }

}

$marcafinal = get_page($url,$mmot);

echo "Valor: ".$marcafinal;

?>

A: Seu código está cheio de problemas, mas vou tentar mostrar um por um aqui. Entendi que está fazendo uma chamada pelo curl e que quer manipular a resposta, então vamos lá:
// $url está sendo declarado fora do escopo de onde será usado, no caso, o seu método
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

// essa função não foi chamada em lugar nenhum
function get_page($url){ // $url é redeclarado como alterador de parametro e ofusca a variável ali em cima

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    // está retornando o corpo da response, o bloco for ali em baixo não será executado
    return $result;

    // você sabe o que está vindo no $result para enumerar ele?
    foreach ($result as $key) {

        // quem é codigo e quem é $mmot (que nem foi declarado)?
        if($key['codigo'] == $mmot){

            // aqui nunca será processado, pois será atirado um erro na linha acima.
            // mas se $mmot fosse declarado, a linha abaixo também não faria lógica, já que está procurando a chave '$mmot' na coleção $key.
            $mmot = $key['$mmot']['nome'];
        }
    }

}

$marcafinal = $mmot;

Sua pergunta não está clara e a refatoração do seu código seria aproximadamente isso:
$url_endpoint = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    $responseValues = json_decode($result, true); // isso se sua API for JSON

    // Você precisa associar esse $mmot a algo, não pode deixar ele vago e sem declaração.
    $mmot = 0;
    $returnValue = null;

    foreach ($result as $key) {
        if($key['codigo'] == $mmot){
            $returnValue = $key['nome'];
        }
    }

    return $returnValue;
}

$marcafinal = get_page($url_endpoint);

Fiz isso levando em consideração que $mmot é um código que leva até o objeto JSON que procura por nome. Assim, você deverá especificar $mmot no método onde deixei claro ali, ou passar como um parâmetro.

A: Ta errado, você está declarando o $mmot dentro do if e usando ele na condição, acredito que você tenha que declarar ela antes

A: Código testado e funcionando:
<?php

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function procuraMmot($mmot) {
    $retorno = '';
    $url = 'https://parallelum.com.br/fipe/api/v1/motos/marcas';
    $resultado = json_decode(get_page($url), true);

    foreach ($resultado as $value) {
        if($value['codigo'] == $mmot){
            $retorno = $value['nome'];
        }
    }
    return $retorno;
}

$resultado = procuraMmot(60);
echo "resultado: $resultado";


text:
Q: loop with delay should run 5 times each time I've this function that runs every 10s and it should do that untill j= 50.
It's working allright.
But what i want is that on every interval something gets executed 5 times and 5 gets added to j.
The first loop is executed as it should but the next 2 are not and doesn't seam to execute the code 5 times but more and then it stops.
Not sure if i'm clear enough but perhaps a look at the the code revaels to you what i'm doing wrong?
My code:
function botsLoop() {
    setTimeout(function () {
        for (var startloop = 0; startloop <= 5;startloop++) {
            var dateTime = new Date();
            ajaxChat.messagedata = ({
                "messageinfo": {
                    "userID": botUserNodes[j].userID,
                    "userName": botUserNodes[j].userName,
                    "userRole": botUserNodes[j].userRole,
                    "UserGender": botUserNodes[j].UserGender,
                    "Profile_Provider": botUserNodes[j].ProfilePro,
                    "Profile_user_name": botUserNodes[j].Profilename,
                    "UserRegion": botUserNodes[j].nameregion,
                    "channelID": botUserNodes[j].channel,
                    "istor": botUserNodes[j].IsTor,
                    "channelName": botUserNodes[j].channelName,
                    "text": 'userenterinchat,' + botUserNodes[j].lat + ', ' + botUserNodes[j].lng + ', ' + botUserNodes[j].namecity + ', ' + botUserNodes[j].nameregion,
                    "dateTime": dateTime
                }
            });

            Onlinelistupdate = {
                "onlinelist": {
                    "userID": botUserNodes[j].userID,
                    "userName": botUserNodes[j].userName,
                    "UserGender": botUserNodes[j].UserGender,
                    "Profile_Provider": botUserNodes[j].ProfilePro,
                    "Profile_user_name": botUserNodes[j].Profilename,
                    "Profile_user_picture": botUserNodes[j].profilepicture,
                    "UserRegion": botUserNodes[j].nameregion,
                    "channelID": botUserNodes[j].channel,
                    "istor": botUserNodes[j].IsTor,
                    "channelName": botUserNodes[j].channelName,
                    "camonoff": botUserNodes[j].camonoff,
                    "ABOUTME": botUserNodes[j].ABOUTME,
                    "lat": botUserNodes[j].lat,
                    "lng": botUserNodes[j].lng,
                    "namecity": botUserNodes[j].namecity,
                    "nameregion": botUserNodes[j].nameregion,
                    "ismobile": botUserNodes[j].ismobile,
                    "namecountry":  botUserNodes[j].namecountry
                }
            };

            sendBotMsg(ajaxChat.messagedata, ajaxChat.channelID,Onlinelistupdate);
            j++;

            if (j < 50) {
                botsLoop();
            }

        }
        startloop = 0;
    }, 10000)
}

solution
    function botsLoop() {
              setTimeout(function () {
                if (j < 50) {
                  var times = 5;
                  for (var i=0; i < times; i++){
                    console.log('inner loop: ' + (i + 1));
                    j++;
             var dateTime = new Date();
             ajaxChat.messagedata = ({"messageinfo":{ "userID": botUserNodes[j].userID, "userName": botUserNodes[j].userName, "userRole": botUserNodes[j].userRole,
              "UserGender": botUserNodes[j].UserGender, "Profile_Provider": botUserNodes[j].ProfilePro, "Profile_user_name": botUserNodes[j].Profilename, "UserRegion": botUserNodes[j].nameregion,
             "channelID": botUserNodes[j].channel, "istor": botUserNodes[j].IsTor, "channelName": botUserNodes[j].channelName, "text": 'userenterinchat,' + botUserNodes[j].lat + ', ' + botUserNodes[j].lng + ', ' + botUserNodes[j].namecity + ', ' + botUserNodes[j].nameregion, "dateTime": dateTime}});

             Onlinelistupdate = {"onlinelist":{ "userID": botUserNodes[j].userID, "userName": botUserNodes[j].userName,
             "UserGender": botUserNodes[j].UserGender, "Profile_Provider": botUserNodes[j].ProfilePro, "Profile_user_name": botUserNodes[j].Profilename, "Profile_user_picture": botUserNodes[j].profilepicture, "UserRegion": botUserNodes[j].nameregion,
             "channelID": botUserNodes[j].channel, "istor": botUserNodes[j].IsTor, "channelName": botUserNodes[j].channelName, "camonoff": botUserNodes[j].camonoff, "ABOUTME": botUserNodes[j].ABOUTME,
              "lat": botUserNodes[j].lat, "lng": botUserNodes[j].lng, "namecity": botUserNodes[j].namecity, "nameregion":  botUserNodes[j].nameregion, "ismobile": botUserNodes[j].ismobile,  "namecountry":  botUserNodes[j].namecountry}};

            sendBotMsg(ajaxChat.messagedata, ajaxChat.channelID,Onlinelistupdate);
                  }
                  botsLoop();
                }
              }, 10000);
            }

A: This could probably do the trick for you:

var j = 0;

function botsLoop() {
  setTimeout(function () {
    if (j < 50) {
      console.log('timeout function');
      var times = 5;
      for (var i=0; i < times; i++){
        console.log('inner loop: ' + (i + 1));
        j++;
      }
      botsLoop();
    }
  }, 10000);
}

botsLoop();

I think you can apply this to your needs by yourself.

A: pass initial value to j while calling bots loop for the first time , retain that value:
function botsLoop(j) {
    setTimeout(function () {
        for (var startloop = 0; startloop <= 5;startloop++) {
            var dateTime = new Date();
            ajaxChat.messagedata = ({
                "messageinfo": {
                    "userID": botUserNodes[j].userID,
                    "userName": botUserNodes[j].userName,
                    "userRole": botUserNodes[j].userRole,
                    "UserGender": botUserNodes[j].UserGender,
                    "Profile_Provider": botUserNodes[j].ProfilePro,
                    "Profile_user_name": botUserNodes[j].Profilename,
                    "UserRegion": botUserNodes[j].nameregion,
                    "channelID": botUserNodes[j].channel,
                    "istor": botUserNodes[j].IsTor,
                    "channelName": botUserNodes[j].channelName,
                    "text": 'userenterinchat,' + botUserNodes[j].lat + ', ' + botUserNodes[j].lng + ', ' + botUserNodes[j].namecity + ', ' + botUserNodes[j].nameregion,
                    "dateTime": dateTime
                }
            });

            Onlinelistupdate = {
                "onlinelist": {
                    "userID": botUserNodes[j].userID,
                    "userName": botUserNodes[j].userName,
                    "UserGender": botUserNodes[j].UserGender,
                    "Profile_Provider": botUserNodes[j].ProfilePro,
                    "Profile_user_name": botUserNodes[j].Profilename,
                    "Profile_user_picture": botUserNodes[j].profilepicture,
                    "UserRegion": botUserNodes[j].nameregion,
                    "channelID": botUserNodes[j].channel,
                    "istor": botUserNodes[j].IsTor,
                    "channelName": botUserNodes[j].channelName,
                    "camonoff": botUserNodes[j].camonoff,
                    "ABOUTME": botUserNodes[j].ABOUTME,
                    "lat": botUserNodes[j].lat,
                    "lng": botUserNodes[j].lng,
                    "namecity": botUserNodes[j].namecity,
                    "nameregion": botUserNodes[j].nameregion,
                    "ismobile": botUserNodes[j].ismobile,
                    "namecountry":  botUserNodes[j].namecountry
                }
            };

            sendBotMsg(ajaxChat.messagedata, ajaxChat.channelID,Onlinelistupdate);
            j++;

            if (j < 50) {
                botsLoop(j);
            }

        }
        startloop = 0;
    }, 10000)
}

botsLoop(0); // when called first time

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check the decimal position AngularJS I am working with a value such as var number = 23.8981   I need to check the 4th number after the decimal and determine if it is a number that is not 0. I am uncertain how to go about this check. I am new to angularjs so any help with this particular problem would be greatly appreciated.

A: Could make use of some javascript logic like one below.

const number = 23.8981;
const fourthDigit = number * 10000 % 10;
console.log(fourthDigit);


text:
Q: Green's formula for area Using Green theorem I need to calculate the area bounded with $(x+y)^4=x^2y$. First(after converting to polar coordinates) i get $x=\cos^6\phi\sin^2\phi$ and $y=\cos^4\phi\sin^4\phi$. And after i plug that into Green's formula i get $\int\limits_{0}^{2\pi} \cos^9\phi\sin^5\phi d\phi$ and that is $0$. But when i set bounds for $\phi$ to be $0, \frac{\pi}{2}$ i get correct solution. Why we have $\frac{\pi}{2}$ for $\phi$ when we don't have any restrictions?

A: The closed curve is drawn once as $\phi$ goes from  $0$ to $\pi/2$, because both the functions for $x$ and $y$ have period $\pi/2$.  Then as $\phi$ goes from $\pi/2$ to $\pi$ the same curve is traced backward.  So integrating from $0$ to $\pi$ should give $0$.   This act is repeated from $\pi$ to $2\pi$.


text:
Q: Run A Function Every Time a Map Document is Opened I am working with C# and ArcObjects. I have some functions that I need to run every time a map document is opened (.mxd, or any other type of map file as well). I have no idea of the code needed to accomplish this though.
An example would be that every time a map document is loaded up or opened, a message box could display that says: "Map document loaded successfully"

A: You need to create an extension to do this, and add a handler for the ArcMap.Events.OpenDocument event - there's a good example in the API Docs that has everything you need:
public class LogExtension : ESRI.ArcGIS.Desktop.AddIns.Extension
  {
    public LogExtension()
    {
    }

    protected override void OnStartup()
    {
      ArcMap.Events.OpenDocument += new ESRI.ArcGIS.ArcMapUI.IDocumentEvents_OpenDocumentEventHandler(Events_OpenDocument);
    }

    void Events_OpenDocument()
    {
      System.Windows.Forms.MessageBox.Show("I opened a document.");
    }
}


text:
Q: mootools | overwrite propery of a tween without create new tween everytime Is there a way to overwrite the property of a tween?
If I write
el.set('tween', {duration: 'long', onComplete: callback});

and then
el.set('tween', {duration: 200, onComplete: secondcallback });

I can't replace the old property (callback is triggered again)
Is possible to solve this problem without the creation of a new Fx.Tween everytime?

A: Each time you set onComplete on the same instance, callbacks are pushed and associated with the same 'complete' event and each callback will be called after the event is fired.
To 'replace' the onComplete callback, you could use removeEvent, i.e.
el.set('tween', {duration: 'long', onComplete: callback});

//and then...

el.get('tween')
    .removeEvent('complete', callback)
    .addEvent('complete', secondcallback);

demo => http://jsfiddle.net/NNzQ7/

A: I would create two independent tweens and keep them around:
var fx1 = new Fx.Tween(element, {onComplete: callback});
var fx2 = new Fx.Tween(element, {onComplete: anothercallback});

And then you can use them individually:
fx1.start('background-color', 'cyan', 'red');
fx2.start('background-color', 'red', 'cyan');


text:
Q: Counting occurrences of a given input If I had an input box with a simple submit button, is there a way to keep track of the amount of times the button was clicked when certain input was given. For instance, I enter milk and hit submit, milk count would be 1, click again milk count would be two. I know that using a simple counter variable, I can keep track of the count, but the count would not match any particular input per se, it's just a generic counter of button clicks. I could store the values from the input in an array and then count the occurrences of a particular item to find its count,  but is there a more elegant way to do this?

A: You can use a simple object to store the occurrences. The basic idea is to grab the input value and add it to an object, using the input as the index, with the value being the number of times it's been added.

$(document).ready(function(){

  // Create simple storage
  var items = {};

  $('#submit').click(function(event){
    event.preventDefault();

    var item = $('#item').val();
    items[item] = items[item]+1 || 1;

    $('#result').html(JSON.stringify(items));

    $('#item').val('');
  });
});

<input id="item" name="item">
<input id="submit" type="submit">

A: Solution without jQuery, and some nicely formatted JSON:

// Create storage and find nodes we need
var items = {};
var btn = document.getElementById('submit');
var textInput = document.getElementById('item');
var result = document.getElementById('result');

// Add event-handler for button click
btn.addEventListener('click', function(event){
    event.preventDefault();

    // Increment counter
    items[textInput.value] = items[textInput.value]+1 || 1;

    // Prettyprint the result
    result.textContent = JSON.stringify(items, null, 2);

    // Reset text
    textInput.value = '';
});
<input id="item">
<input id="submit" type="submit">

A: var listCount   = [];
$("#getButton").click(function() {
    var getTextValue    = $("#getInput").val();
    if(getTextValue!="") {
        var initVal     = typeof(listCount[getTextValue])=="undefined" ? 0 : listCount[getTextValue];
        listCount[getTextValue] = parseInt(initVal)+1;
        alert(listCount[getTextValue]);
    }
    return false;
});

Initialized an Array var listCount = [];, which stores the Input Value as Associative Key, and parseInt(initVal)+1 increments the value of n times click.


text:
Q: Express.js index.js 404 (Not Found) For some reason it can't load my index.js script that is being referenced from my index.html.  server.js, index.html, and index.js are all located at the root of my project folder.
server.js
var express = require('express'),
    app = express();

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.get('/', function (req, res) {
    res.render('index.html');
});

app.listen(4000, function () {
    console.log('Example app listening on port 4000!');
});

index.html

A: You have to serve those files. You could do them individually:
app.get('/index.js', function (req, res) {
    res.sendFile('index.js');
});

Or create a directory (e.g. www) for everything you want to serve and use express.static:
app.use(express.static('www'));

A: By looking declaration
app.use(express.static(__dirname + '/public'));

Your index.js file should be in the public directory.
Since index.js and server.js are in the same directory, define
app.use(express.static(.));


text:
Q: Do Something on WPF Form Minimize –PowerShell (version 5) I have PowerShell script that creates a WPF form from inserted XML code. This form will run on a kiosk station and has no window (so no maximize, minimize, or close buttons) and consumes the entire screen.
Even though the form itself has no window buttons, a person can still press the WIN key on a keyboard, get the task bar, right click on the form in the task bar and choose to minimize, maximize, or close for the form.
So, I set an action for close to lock the workstation (which is better option for this kiosk instead of preventing the form from closing at all) by doing this:
$form.Add_Closing({
    $shell = New-Object -ComObject "Wscript.Shell"
    $shell.Run("%windir%\System32\rundll32.exe user32.dll,LockWorkStation")
})

I would also like to do this for Minimize if possible, but can't seem to figure out how.
FYI. I'm not intending this to be a security feature per-se, but more so something that is better done then not for this kiosk station.

A: if $form is your form, then you could try this (wrapping the repetitive part in a function to stay DRY):
function Lock-Workstation {
    $shell = New-Object -ComObject "Wscript.Shell"
    $shell.Run("%windir%\System32\rundll32.exe user32.dll,LockWorkStation")
}

$form.Add_Closing({ Lock-Workstation })

$form.Add_StateChanged({
    if($form.WindowState -eq "Minimized") {
        Lock-Workstation
    }
})

Since you don't want the window to be resized anyway, you could simply use:
$form.Add_StateChanged({ Lock-Workstation })


text:
Q: Is it possible to add objects that we do not define in the schema to the database using pymongo? I want to add objects that ı don't define in the schema to my database without changing my schema.
from pymongo import MongoClient

def create_collection(coll_name):
    db = MongoClient('mongodb://localhost:27017/')['dbname']
    result = db.create_collection(coll_name, validator={
        '$jsonSchema': {
            'bsonType': 'object',
            'additionalProperties': True,
            'required': ['component', 'path'],
            'properties': {
                'component': {
                    'bsonType': 'string'
                },
                'path': {
                    'bsonType': 'string',
                    'description': 'Set to default value'
                }

            }
        }
    })
    print(result)

if __name__ == '__main__':
    create_collection('collectionname')

When ı run this code it creates database and collection.
db.dbname.insertOne({name: "Jason", status:"updated"})

i want to add name and status that ı don't define in schema. Is there a way to add objects that ı dont define in my schema using python?


text:
Q: What is the precise description of such positive integers $n$: for any integer $a, a^{n+1} \equiv a \pmod n$? Here's what I've managed to get till now(of course, we only have to consider $a$ from $0$ to $n-1$):

*

*If $n \ne 2, n$ isn't prime. Otherwise we'll have $2^n \equiv 1 \pmod n$, a contradiction.

*Do prime factorization of $n$. Then the power of each prime factor of $n$ is $1$. Otherwise, we can consider $a=p_1p_2...p_k$, where $p_i$ are the prime factors of $n$. Then we would definitely have $a \mid n$, another contradiction.

*Besides, $n$ has $2$ as its factor. Otherwise, we would have $(-1)^{n+1} \equiv 1 \pmod n$.
All above arguments has excluded the case $n=2$, where $n$ satisfies the statement.
That's all i've got. How can I arrange further progress? The Euler $\phi(n) = (p_1-1)(p_2-1)...(p_k-1)$, where $p_i$ are $n$'s prime factors. How can I link it with $n$ itself, and use some results like Fermat's little Theorem?
Update: Found on this page  http://www-groups.mcs.st-andrews.ac.uk/~john/Zagier/Problems.html.


text:
Q: Unable to convert WSDL url to JAVA I'm working on a Spring Boot project. I have a 3rd party to use its service. It provides me WSDL url but I really new to the WSDL.
I've found that if I want to connect its service I need to convert WSDL to the JAVA class.
So, I've found 2 solutions to do this.

*

*Using "wsimport -keep -verbose http://compA.com/ws/server?wsdl"
refer: https://mkyong.com/webservices/jax-ws/jax-ws-wsimport-tool-example/
When I attempt on this method I get below error.

The operation couldn't be completed. Unable to locate a Java Runtime
that supports wsimport. Please visit http://www.java.com for
information on installing Java.

Here is my java --version

java 19.0.1 2022-10-18
Java(TM) SE Runtime Environment (build 19.0.1+10-21)
Java HotSpot(TM) 64-Bit Server VM (build 19.0.1+10-21, mixed mode,
sharing)

*Using Eclipse

According to How do you convert WSDLs to Java classes using Eclipse?, my Eclipse has no Web Services option to be selected even I download Eclipse from https://www.eclipse.org/downloads/packages/release/2022-09/r/eclipse-ide-enterprise-java-and-web-developers

A: I would do the following steps:

*

*put the WSDL in my repo anyway to see later changes

*create a maven or gradle task to have the "WSDL to java generation" with JAXB whenever I will need it: https://spring.io/guides/gs/consuming-web-service/#initial

*extend from WebServiceGatewaySupport to have a client

You could also follow this complete example:
https://spring.io/guides/gs/consuming-web-service/


text:
Q: How do I list all numbers for all contacts even if one contact has multiple numbers associated with it? I am trying to allow the user to select a contact's phone number by using the default system contact selector. Min SDK is 11 and target is 19, this is the code I'm using the bring up the contact selector:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
this.startActivityForResult(intent, 1);

This works and does bring up the contact selector activity. The problem is that this has different behavior based on the phone you're on. I understand this and that's okay, but there's one issue that I feel is a problem for the end user of the app. Here is how this works on two different phones:
Samsung Galaxy S2 running Cyanogenmod 10: Opens the contact selector activity and displays every single phone number for all contacts, so if a user has 2 phone numbers it would look like this
702-555-1212 Mobile Contact1Name
702-555-4321 Work   Contact1Name
702-555-8879 Work   Contact2Name

Samsung Galaxy S5 running Android 4.4.4: Opens the contact selector activity and displays only one entry per contact, regardless of how many phone numbers are tied to a contact. It looks like this
Contact1Name
Contact2Name

With the S5, it automatically selects the first or default phone number if there are multiple numbers for that contact. How can I get the S5 to behave like the S2 and show me every number for the user to select? I'm hoping I don't need to write my own contact selector activity.
NOTE: This answer, Selecting a number from user with multiple numbers when using the contact picker, is almost exactly what I'm doing but it does not work as expected between the two phones I've tested.


text:
Q: Vega: how to include topoJSON instead of using URL in the Vega spec I use Vega charting library. Every time I switch between tabs, the app render charts and one of charts has a spec with URL of topoJSON. The spec itself is in memory, but this URL is called every time on re-rendering charts.
This example uses URL to load topoJSON of the world map: https://vega.github.io/vega/examples/zoomable-world-map/
Is it possible include topoJSON to the spec instead of using URL?
Or at least cache it somehow on local (can't use CDN).

A: Here is how to supply topojson inline.
Create a data as follows
{
            "name": "i",
            "values": {},
            "format": { "type": "topojson", "mesh": "yourMesh", "filter": "exterior" }
}

Everything between the braces for values should be your entire topojson spec. yourMesh should be the feature or mesh name.
I'd post a working example but the spec it too large. You can download a PowerBI file at the following link showing this working.
https://github.com/deneb-viz/deneb/issues/194


text:
Q: Open Bravo Default URL, how to view the list of users I just want to know the default restful url for the openbravo, for example Let us consider a when admin logged in I should get the list of users and I don't know which path should I pass.

A: The url to view the list of users in is
localhost:8080/openbravo/ws/dal/ADUser you need to provide username and password for the authentication. The username can also be provided by passing l=username&p=password in the url
localhost:8080/openbravo/ws/dal/ADUser?l=Openbravo&p=openbravo


text:
Q: ASP .NET MVC 4 AuthorizeAttribute and ActiveDirectoryMembershipProvider I'm trying to implement Active Directory role based authorization in my ASP.NET MVC 4 Intranet Web Application by using the AuthorizeAttribute.
[Authorize(Roles = "CONTOSO\\G_Helpdesk")]
public ActionResult Index() {
   return View();
}

This should only allow members of the group CONTOSO\G_Helpdesk be able to view the index page. My development Virtual Machine and Web Server are both NOT domain members. So I thought I should configure a ActiveDirectoryMembershipProvider. My web.config is shown below.
<authentication mode="Windows"/>
<authorization>
  <deny users="?"/>
</authorization>

<membership defaultProvider="ADMembershipProvider">
  <providers>
    <add name="ADMembershipProvider"
      type="System.Web.Security.ActiveDirectoryMembershipProvider,
      System.Web, Version=2.0.0.0, Culture=neutral,
      PublicKeyToken=b03f5f7f11d50a3a"
      connectionStringName="ADService"
      connectionUsername="CONTOSO\User"
      connectionPassword="myPassword"
      attributeMapUsername="sAMAccountName"/>
  </providers>
</membership>

<connectionStrings>
  <add name="ADService" connectionString="LDAP://dc1/DC=CONTOSO,DC=com" />
</connectionStrings>

Now here's the problem. I'm not able to login using an active directory user who is member of the CONTOSO\G_Helpdesk group. In fact I'm not able to login at all. When I change the attribute to the lines below, I am able to login using a local account.
[Authorize]
public ActionResult Index() {
   return View();
}

Does the AuthorizeAttribute even use the membership provider? I think it totally ignores it.

A: I found out I'm not thinking in the right direction. I won't be able to authenticate from a standalone webserver using AD credentials while using Windows Authentication. Source.
I have two options.

*

*Make the webserver member of the Domain.

*Use Forms authentication.

I hope this answer will save people who are struggling with the same problem some time.


text:
Q: How do I add sqljdbc_auth.dll to my project build path? I have a project that connects to msSQL Server, the project is exported as a war file then run in Apache, but when I try to connect to the SQL Server it gives me this error.
com.microsoft.sqlserver.jdbc.AuthenticationJNI
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path. - See screenprint below

I've added the dll to the jre native library in eclipse, I've added it to the bin and lib folders of the jre folder in program files, I've added it to the eclipse.ini file with java -Djava.library.path= and I've also tried the -djava line in cmd prompt. Where am I going wrong.


text:
Q: How to loop over to get different array in angular 5? {
   "status":"true",
   "select":[
      {
         "view_":"select",
         "Type":"MARKET_WORKING",
         "Question":"WHICH BRAND COUNTER IS IT?",
         "options":[
            {
               "option":"USPA"
            },
            {
               "option":"HANES"
            },
            {
               "option":"USPA & HANES "
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            }
         ]
      }
   ],
   "text":[
      {
         "view_":"select",
         "Type":"MARKET_WORKING",
         "Question":"WHAT IS THE OPENING STOCK OF INNERWEARS TOP?",
         "options":[
            {
               "option":"VEST"
            },
            {
               "option":"BRA_PADDED"
            },
            {
               "option":"BRA_NON PADDED"
            },
            {
               "option":"CAMISOLE"
            },
            {
               "option":"THERMAL"
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            }
         ]
      },
      {
         "view_":"select",
         "Type":"MARKET_WORKING",
         "Question":"WHAT IS THE OPENING STOCK OF INNERWEARS BOTTOM?",
         "options":[
            {
               "option":"BRIEF"
            },
            {
               "option":"TRUNKS"
            },
            {
               "option":"PANTIES"
            },
            {
               "option":"THERMAL LEGGINGS"
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            }
         ]
      },
      {
         "view_":"select",
         "Type":"MARKET_WORKING",
         "Question":"WHAT IS THE OPENING STOCK OF COMFORTWEARS TOP?",
         "options":[
            {
               "option":"MEN'S T SHIRT"
            },
            {
               "option":"MEN'S TANKS"
            },
            {
               "option":"WOMEN'S T SHIRT"
            },
            {
               "option":"WALL FIXTURE"
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            }
         ]
      },
      {
         "view_":"select",
         "Type":"MARKET_WORKING",
         "Question":"WHAT IS THE OPENING STOCK OF COMFORTWEARS BOTTOM?",
         "options":[
            {
               "option":"BOXER SHORTS"
            },
            {
               "option":"MEN'S SHORTS"
            },
            {
               "option":"MEN'S PANTS"
            },
            {
               "option":"MEN'S SOCKS"
            },
            {
               "option":"WOMEN'S SHORTS"
            },
            {
               "option":"WOMEN'S PANTS"
            },
            {
               "option":"WOMEN'S CAPRI"
            },
            {
               "option":"WOMEN'S SOCKS"
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            },
            {
               "option":""
            }
         ]
      }
   ]
}

This is JSON from api
I want to put all in loop where question and option will come respectively. For that I wrote below code
  if(this.user_type == 1){

        this.mwork = this.navParams.get('mwork');
        this.selectq = this.mwork.select;
        this.selecto = this.selectq[0].options;
        //this.selecto = this.selectq.options;
        this.textq = this.mwork.text;
        this.texto = this.textq[0].options;

        console.log(this.selecto);
    }

and below is html
div class="field-group" *ngFor="let mworkq of selectq">

{{mworkq.Question}}

          <select [(ngModel)]="selectedOption">
            <option value=''>Select</option>
            <option  *ngFor="let mworkq of selecto" value="{{mworkq.option}}">{{mworkq.option}}</option>

          </select>

              {{mworkq.Question}}
              <ion-input *ngFor="let mworkq of texto" class="{{mworkq.option}}" type="text" placeholder="{{mworkq.option}}" ></ion-input>

But now what is happening only first option values are coming in all question because of [0]. So How can I make it dynamic to show options respective to there questions. Please help. Thank you.
For Florin I'm using below html for generating loop

              {{mworkq.Question}}
              <ion-input *ngFor="let mworkq of texto" class="{{mworkq.option}}" type="text" placeholder="{{mworkq.option[i]}}" ></ion-input>

From this ts
 for (const selectItem1 of this.mwork.text){
             this.textq = selectItem1.Question;
               for (const selectItem2 of this.mwork.text){
                      this.texto = selectItem2.options;
                    }
        }

A: Probably I got you wrong. But why don't you use
*ngFor="let option of options; index as i"

and afterwards
values[i]

Note: The index as i syntax requires Angular 5+

A: Your json object has three properties, status, select and text.
It looks like that :
{
 status: "",
 select: [{
   view_:"",
   Type:"",
   Question:"",
   options:[{}]
 }],
 text: [{
   {
   view_:"",
   Type:"",
   Question:"",
   options:[{}]
 }
 }]
}

I want to put all in loop where question and option will come
  respectively.

You can try this. Note that your structure looks really weird to me...and nested loop just highlight the bad structure here.
this.mwork = this.navParams.get('mwork');

for (const selectItem of this.mwork.select){
  console.log(selectItem.Question);
  for (const option of selectItem.options){
    console.log(option.option);
  }
}

EDIT :
Based on your question edit, you are using *ngFor directive, so you need to store your datas in an iterator. Example :
const mworkDatas = [];
for (const selectItem1 of this.mwork.text) {
  const question = selectItem1.Question;
  let answerOptions = [];
  for (const selectItem2 of this.mwork.text) {
   answerOptions  = selectItem2.options;
  }
  mworkDatas.push({
    question,
    answerOptions
  });
}

Then in your template :
*ngFor="let mworkData of mworkDatas"
and you can then use :
mworkData.question and mworkData.answerOptions

A: I have just change the html code to below and it works. I was taking options of api in ts file. It is giving me undefined. I just took collection of first loop from the ts file which is comming from api. Then for second loop is I used value of first loop for collection of second loop and then added .options after it for loop of options

{{mworkq.Question}}

          <select [(ngModel)]="selectedOption">
            <option value=''>Select</option>
            <option [hidden]="mworkq.option == null || mworkq.option.length == 0" *ngFor="let mworkq of mworkq.options" value="{{mworkq.option}}">{{mworkq.option}}</option>

          </select>

              {{mworkq.Question}}
              <ion-input [hidden]="mworkq.option == null || mworkq.option.length == 0"  *ngFor="let mworkq of mworkq.options" class="{{mworkq.option}}" type="number" placeholder="{{mworkq.option}}" ></ion-input>

A: Check this, it will store all options in selecto array irrespective of questions.
   if(this.user_type == 1){

        this.mwork = this.navParams.get('mwork');
        this.selectq = this.mwork.select;

        for(i in this.selectq)
        {
          for(k in this.selectq[i].options)
             this.selecto.push(this.selectq[i].options[k]);
        }

        this.textq = this.mwork.text;
        this.texto = this.textq[0].options;

        console.log(this.selecto);
    }


text:
Q: How to use a link instead of a button in HTML? Consider the following index.html :

<%@ page language="java"
    contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

    <title>Product Inventory Shop 2014</title>
    <link rel="stylesheet"
          href="./css/styles.css"
          type="text/css"/>

    <link rel="stylesheet"
          href="./css/bar.css"
          type="text/css"/>

GET OUT!

Shop Inventory Program

<fieldset>
  <legend>
  Welcome ! Please enter your Username and Password

  </legend >
  <form action="loginPage">
    USERNAME: <input type="text" name="username">

    PASSWORD : <input type="password" name="password">

    <input type="submit" value="Login">
  </form>

  <form action="RegisterPage">
   Or click here to <input type="button" value="Register">
  </form>
</fieldset>

A preview :

How can I use a link instead of the Register box ?
Meaning , I want to have link (a hand that appears when the mouse is over the "Register" word) and forward it to some Servlet . (And yeah , I know it's pretty ugly , I'm working on it ... :))

A: Instead of
  <form action="RegisterPage">
   Or click here to <input type="button" value="Register">
  </form>

Use
   Or click here to register

A: Use the following:
Register

a means anchor. href is the URL of the link; the destination. Replace putregisterlinkhere with the URL of the register page

A: Don't use a form.
Use a simple link...
Or click here to Register


text:
Q: Unable to close the files of JposLogger I am using jpos 2.1.0 and using JposLogger to generate and rotate iso logs. However i am not able to configure the parameters appropriately due to which neither the logs are rotated based on dates neither i am able to close the open log files.
This is related to the previous issue Too many files open
which i thought was due to issue in using generic packager but while going deeply, it was due to improper closure of files generated by JposLogger, which can be identified using command lsof -p  in centos. One file is generated for one request.
[cipsappcen@connectipsappcen local]$ lsof -p 12108 |grep iso.log
java    12108 cipsappcen   36w      REG              253,2     58589 405618549 /u03/connectIPSSRVC/log/iso.log
java    12108 cipsappcen   47w      REG              253,2     58589 405618549 /u03/connectIPSSRVC/log/iso.log

public class Iso8583MessageBOKImpl implements Iso8583Message{
JposLogger logger = new JposLogger(isoLogLocation);
        org.jpos.iso.ISOPackager customPackager = new GenericPackager(isoPackagerLocation+iso8583Properties.getPackager());
        BaseChannel channel = new ASCIIChannel(iso8583Properties.getServerIp(), Integer.parseInt(iso8583Properties.getServerPort()), customPackager);// live
        logger.jposlogconfig(channel);
...
}

public void jposlogconfig(ISOChannel channel){
        try{
            //Configuring Logger
            Logger logger = new Logger();
            logger.setName("Q2");
            org.jpos.util.DailyLogListener dayLog = new org.jpos.util.DailyLogListener();
            ProtectedLogListener pll = new ProtectedLogListener();
            Configuration protectLogCfg = new SimpleConfiguration();
            protectLogCfg.put("protect", "2");
            pll.setConfiguration(protectLogCfg);
            logger.addListener(pll);

            Configuration dayLogCfg = new SimpleConfiguration();
            dayLogCfg.put("window", "86400");
            dayLogCfg.put("prefix", logLocation);
            dayLogCfg.put("suffix", ".log");
            dayLogCfg.put("date-format", "-yyyy-MM-dd");
            dayLog.setConfiguration(dayLogCfg);
            logger.addListener(dayLog);
            logger.addListener(new SimpleLogListener(System.out));
            ((LogSource)channel).setLogger(logger, "connectips-channel");

            logger.removeListener(pll);
        }catch(Exception ex){
            System.out.println(ex);
        }
    }

Since files are not closed properly OS is not able to handle the too many open files.

A: You need to instantiate your logger and loglisteners only once in your application.
One option is to use Logger.getLogger() to register and create your logger.
First you need to create a logger only once in your application for instance with a method like this
public void initLogger() {
    Logger logger = Logger.getLogger("Q2"); //this creates a logger and register it with Q2 name
    org.jpos.util.DailyLogListener dayLog = new org.jpos.util.DailyLogListener();
    ProtectedLogListener pll = new ProtectedLogListener();
    Configuration protectLogCfg = new SimpleConfiguration();
    protectLogCfg.put("protect", "2");
    pll.setConfiguration(protectLogCfg);
    logger.addListener(pll);

    Configuration dayLogCfg = new SimpleConfiguration();
    dayLogCfg.put("window", "86400");
    dayLogCfg.put("prefix", logLocation);
    dayLogCfg.put("suffix", ".log");
    dayLogCfg.put("date-format", "-yyyy-MM-dd");
    dayLog.setConfiguration(dayLogCfg);
    logger.addListener(dayLog);
    logger.addListener(new SimpleLogListener(System.out));
    //all set now logger is accessible via Logger.getLogger
}

Then when you create a new channel all you need is to set the previously created logger:
public class Iso8583MessageBOKImpl implements Iso8583Message{
...
        org.jpos.iso.ISOPackager customPackager = new GenericPackager(isoPackagerLocation+iso8583Properties.getPackager());
        BaseChannel channel = new ASCIIChannel(iso8583Properties.getServerIp(), Integer.parseInt(iso8583Properties.getServerPort()), customPackager);// live
        channel.setLogger(Logger.getLogger("Q2"),"connectips-channel");
...
}

Internally Logger.getLogger(String name) creates a new logger if there is no previously registered logger with that name, and registers it in NameRegistrar
Succesive calls with the same name return the previously created one. This way you are creating the files only once.
The most important thing here is that initLogger is only called at the start of your application, for instance (this is not the best way just an example) in a static initializer of your class if that is the only place where you use jpos related class:
public class Iso8583MessageBOKImpl implements Iso8583Message{

    static {
        initLogger();
    }
...

Last but not leas I strongly suggest you to use Q2 for the initialization of jpos objects, this tutorial has all you need to create a channel and a logger.
Then when you want to send a message you don't even need to instantiate the channel, just call QMUX.getMUX(mux-name) and QMUX.request() method to send a message to the channel and receive its response.


text:
Q: How to preselect a option - Dropdown my HTML is a static variant, not a solution builded with ng-repeat or an existing JSON/Angular Controler.
I need to select a custom option and used alreay ng-select without a success.
My HTML looks like:

        <button type="button" class="pull-right btn btn-block btn-dropdown" dropdown-toggle>

                {{my.filter}}

        </button>

                Germany

                England

so how can i solve it to preselect the option "Germany" by pageloading into the div.pull-left section?

A: You mention ng-select in your question, but you used ng-selected. Maybe it is just a typo.


text:
Q: Check if app was bought I just wanted to ask if there is a way to check if the user actually did buy an app programmatically. I saw how Infinity Blade 3 and other games forced the user to log in to their apple accounts and somehow checked with the store on whether or not the app has been bought. How is this possible to create programmatically? I've searched all over the web just to find how to open up the storkit view from which you can purchase other apps or videos, etc... Thanks in advance

A: You could try to check for the app's receipt and verify it with the AppStore -
NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL]; // iOS 7+, do not use respondsToSelector as it will report YES for iOS 6 too

Here's Apple's documentation on how to verify your receipt.
If the receipt is nil or the url points to a non existent path, you may need to refresh the receipt.
Implement SKRequestDelegate and check:
NSError* err = nil;
if (![url checkResourceIsReachableAndReturnError:&err]){
    SKReceiptRefreshRequest* request = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
    request.delegate = self; /* or your delegate's instance here */
    [request start];
}
....
-(void)requestDidFinish:(SKRequest*)request{
    if([request isKindOfClass:[SKReceiptRefreshRequest class]]){
        // The URL should be available now, if it's not - I guess the app is cracked
    }
}
-(void)request:(SKRequest*)request didFailWithError:(NSError *)error{
    ; // This does not mean the app is pirated, use this to schedule the test for later.
}

I would disable these checks in debug mode (and on the simulator).
You may want to check this project - VerifyStoreReceiptiOS for verifying your receipts.


text:
Q: Path Optimizer system data (SFMC) Is it possible to retrieve Path Optimizer data from the data views or from tracking extract?
We export both sets daily to BiqQuery.
Example:
A/B test, 2 versions (10k vs 10k)
Winning (50k) version send automatically after 1 day
Is it possible to query the results of the A/B test (10k vs 10k) from Data Views of Tracking Extract?
When looking at the data, the mails are send via one sendID. Both the test send(10k) as the winning version (50k). So the sendid has a send count of 60k.
I'm looking for a more easy way then using the eventdate to split. Because it will be a lot of work to lookup all dates every time. For example when using Path optimizer in triggered journeys.
So is there some kind of indicator to distinguish the A/B 'test' send from the winning version?


text:
Q: Stream of readLines I'm attempting to create an infinite stream of strings from readLine calls:
import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input: Stream[String] = Stream.cons(in readLine, input)

But it appears that the readLine call isn't being called lazily. Immediately after entering that code, the readLine expects input then the Stream becomes an infinite list of that same input. Is it possible to accomplish what I have in mind?

A: See the example at Stream. Note that the lazy thunk is in the tail, not the head. Each time the thunk is invoked it should return the next cons (including the next thunk which in turn should supply the next cons incl....)
Here is the signature for Stream.cons: <http://www.scala-lang.org/docu/files/api/scala/collection/immutable/Stream$$cons$.html>. Note the thunk (=> Stream) as the 2nd argument to apply.

A: import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input = Stream.continually(in readLine)


text:
Q: Laravel authorization/policy prevents access for everyone I found similar title and similar asked question on this website when I was researching to solve the problem. But none of posted answers helped me. This question might be duplicated but I could not solve the problem using existing questions on StackOverflow.
I'm trying to prevent access to users who are not logged in OR who are not member of "School" model!
In "web.php" file I used "middleware("auth")" to prevent access to users who are not logged in.
Now I created a "Policy" named "SchoolPolicy" to prevent access to users who are not member of "Schools" database/model.
When I call "view" method from SchoolPolicy, it prevents access for all authorized and unauthorized users!
I also checked and I realized "School" model returns "null" when I try to catch "user_id" foreign key from "schools" table.
The below piece of code is the way I created "Schools" table using Migration:
Schema::create('schools', function (Blueprint $table) {
  $table->id();
  $table->foreignId('user_id')->constrained();
  $table->string('school_name');
  $table->string('school_address')->nullable();
  $table->string('school_email');
  $table->string('school_phone')->nullable();
  $table->string('url');
  $table->longText('descriptions')->nullable();
  $table->timestamps();
});

This is the route to view any school which is created by any user (URL can be dynamic)
Route::group(['middleware' => 'auth'], function () {
 Route::get('/schools/{url}', [ViewSchool::class, 'index'])->name('yourschool.show');
});

And this is "School" model. I used php artisan make:model School command to create this model:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Auth;

class School extends Model{
  use HasFactory;

  /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
  protected $fillable = [
    'user_id',
    'school_name',
    'school_address',
    'school_email',
    'school_phone',
    'url',
    'descriptions'
  ];
}

In this section I created School Policy. However I used Laravel 8 but I also registered created Policy manually

*

*SchoolPolicy
<?php

namespace App\Policies;

use App\Models\School;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class SchoolPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\Models\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        //
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\School  $school
     * @return mixed
     */
    public function view(User $user, School $school)
    {
        return $user->id == $school->user_id;
    }
}

*

*In AuthServiceProvider.php I registered SchoolPolicy like this:
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use App\Models\User;
use App\Models\School;
use App\Policies\SchoolPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        School::class => SchoolPolicy::class
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
    }
}

*

*"ViewSchool.php" file where I want to use authorize method:
<?php

namespace App\Http\Controllers\Schools;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\School;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ViewSchool extends Controller
{
    public function index (School $school) {

        $this->authorize('view', $school);

        return view('layouts.viewschool');
    }
}

I tried many ways to solve the problem, but none of them properly worked:

*

*First Try:
public function index (School $school) {

 $this->authorize('view', $school);

}

*

*Second Try:
public function index () {

  $this->authorize('view', School::class);

}

*

*I even tried to print any output from School model but I receive "null":
public function index (School $school) {

  dd($school->user_id);

}

I followed all tutorials on YouTube and official Laravel website, but in my examples I gave you, authorization doesn't work properly.
Please help me to solve this problem.
Thank you


text:
Q: Yaru dark theme does not work properly - white boxes in Gnome Software I am new to linux and I am using ubuntu 20.04 LTS.
I use the default yaru dark theme and when I open gnome software centre and some other application I see white and blue things (as shown in the images)

Because of this I am unable to read the names of applications in gnome software centre. I have already installed gnome-tweak-tool and tried various other themes but the problem is the same, my theme gets changed but still I see the white boxes in the software centre and the main problem remains the same but cannot fix it.
Actually when I first installed Ubuntu, everything was fine and my yaru dark theme was also working properly, but because I was new to Linux, I was experimenting with the system and by mistakenly, installed the kde-desktop package. And after that everything changed. It installed the kde desktop which I didn't wanted. And Then I deleted the kde desktop and brought everything back to normal, but It caused changes in my yaru theme and I am not able to fix it now.
So is there any way to bring my theme back to normal?

A: OK, I haven't had much luck, because a fix I found applies to Ubuntu Software Centre - editing colour values in softwarecenter.css - but I simply cannot find any .css or .xml file for Gnome Software that corresponds to that file. I'm still looking, but for now I have a workaround - not perfect, but better than what you have: open Gnome Software in another theme. I should have mentioned this earlier, but it isn't so much a fix, and I was really hoping I could find that config file. So to do this - and I'm just listing a theme you'll likely have - here is the command to open it in the Adwaita theme:
GTK_THEME=Adwaita gnome-software
You can either run that in the terminal (Alt+F2 probably won't work: for me, it opened Discover, KDE's software manager, without a theme change), or you can edit the launcher - gnome-software.desktop - and replace the Exec=gnome-software line with Exec=env GTK_THEME=Adwaita gnome-software (I suggest just doing this via the terminal first, to see if any theme works for you). It might not be perfect - the picture shows mine opening in Adwaita, but in a mix with my dark theme, but at least the text is somewhat readable (and you might not even get the dark boxes like I did). But you can try specifying other light themes until you find one that's acceptable. I tried Ambiance and Yaru, and the text was very dark, Ambient-MATE was the same as the pic (note that the text gets slightly clearer when you hover your mouse over each box). So it's far from a fix, but it's something (and you might find a theme that makes it readable).

A: If what you're asking is how to change to another dark theme, you can use the Gnome Tweak Tool (gnome-tweaks). Not sure how you changed it to Yaru, and what other dark themes you have, but Gnome Tweak Tool lets you change themes really easily. I have been using Ubuntu for 15 years, and have always used dark themes, and not all are 100% perfect (as you've seen), but you can use others. If you don't have the above installed, run in the terminal:
sudo apt-get install gnome-tweaks

If you need more dark themes, download GTK themes from https://www.gnome-look.org/browse?cat=135&ord=latest (maybe also in the Software Centre?), and to install them Google "Ubuntu 20.04 install GTK theme" (there's lots of info on that).

A: PS: You can obviously try other dark themes to see if they are better. While you're getting white boxes with white text while using your default dark theme, and I'm getting dark boxes with dark text opening Gnome Software in light themes, I tried the Blue-Submarine theme, and it looks nice. However, I'm running a dark theme (Ambiant-MATE-Dark) and don't have your issue, and you've already tried changing your theme to other darker ones, but it's at least worth trying.

A: This is about as close I've come to a solution to this, and I can't really test it since Gnome Software is being themed properly, but I've come across a config file full of colour definitions: org.gnome.Software.Featured.xml
In /snap/snap-store/ you will find 3 folders: 2 numbered, and current (which is actually just a link). It's the folder with the highest number you will want to go into. For example, mine is 558, so the folder containing the .xml file is /snap/snap-store/558/usr/share/app-info/xmls. Right-click org.gnome.Software.Featured.xml and choose to Edit as Administrator, and when it opens in Text Editor, near the top you will see:
      <value key="GnomeSoftware::FeatureTile-css">border-color: #aaa;
text-shadow: none;
color: #333;
background:
 linear-gradient(to bottom, rgba(255,255,255,0.3), rgba(200,200,200,0.9)),

That might not be the section for the tiles/boxes, but I can see straight away the first RGBA value is white. And further down is text-shadow, also white, and other sections to do with text and background you can try to edit. Now, most of the colours are in RGBA, with only a few being Hex (the ones starting with #), and you can either determine the ones in the file with an online converter or a Linux app.
Online: RGBA and Hex Color Converter
Type in the numbers for R (Red) G (Green) B (Blue) & A (Opacity (Alpha)) and the colour will appear on the right. You will see that 255,255,255,0.3 is white, and 200,200,200,0.9 is a light grey.
I suggest using an app, and in the pic you can see I entered the values for the latter in MATE Colour Selection (mate-color-select) - you can also use GNOME Color Chooser (gnome-color-chooser) or KColorChooser (kcolorchooser) - and it shows that light grey. (As for the few hex values, you can copy and paste them into the field - my choice is KColorChooser, because as soon as you paste it in, it shows you the colour, no need to hit Enter).

So you can use this method to determine the colours specified in org.gnome.Software.Featured.xml, and replace them with your own, which you can determine via the colour picker. For example, in the pictured app I clicked one of the dark charcoal presets, giving 46,52,54,15, which you then use to replace the white's 255,255,255,0.3. And of course you can just use 0,0,0,0 for pure black.
Before editing, save a copy (eg: org.gnome.Software.Featured.ORIG.xml) in case you need to restore the original. Then try replacing whites in various sections with black or charcoal, and see if it works. In between opening Gnome Software to see if there are changes, run killall gnome-software in the terminal, as I found during trying different themes in the previous method that a couple of times after I closed it, killing it didn't report "no process found", meaning it was still running in the background.
As I said, I can't test this, but there are a lot of whites in that file, and I'm not seeing those due to my dark theme, so hopefully this is the way to achieve what you want. Best of luck!


text:
Q: How can I make sure the IMXML gets included in an Actionscript project? I am using Flex Builder for an Actionscript which apparently has a dependency on IMXML object. I'd never heard of this object, and there is nothing on the project site about any dependencies. I assume it's a Flex component library, though. Which library should I include in order for this program to resolve its dependency issues?
Thanks in advance.

A: It's part of the core Flex SDK.  (mx.core)  If it's missing - check your SDK path, something's probably gone screwy there.  You should have (amongst others) flex.swc and framework.swc present.


text:
Q: Classes containing other classes as properties in MATLAB I have different classes A & B. I want to assign objects created from class A & B as properties in both A & B . My code looks like this
classdef A < handle

   properties
      container
   end

   methods
      function object = A()
      end
   end
end

and this
classdef B < handle

   properties
      container
   end

   methods
      function object = B()
      end
   end
end

Then I am assigning both objects from class A & B to the container-property from both classes A & B, like
object_from_class_A.container = object_from_class_A

and
object_from_class_A.container = object_from_class_B

This means, I use the same variable/property for storing objects from different classes. Is this a bad design choise? How should I avoid this? I am just trying to assign objects to each other, because I am trying to build relationships between different objects.
P.S. I am new to OOP.
Edit for better explanation:
Class A & B are fundamentally different and should not be connected/inherited from each other. I have something in mind like this: Object city contains object street and object house, object house is connected to object street. So, street and house should inherit from city, but street and house should know each other. But how should I realize the relation between many objects (like sign, car, people, cat, dog, etc) that all inherit from city but dont share/inherit anything else between each other?
For example I want to establish a connection beween a car an an street object, so if I look into a specific street-object, I want to assign the specific objects car1, car2, car3 to the street object.

A: Based on your question, you essentially want to emulate a one-to-many relationship between objects.
One possible way of doing this would be to store the handle to the "one" side of the relationship within each of the "many" side's objects and then use something like findobj to get the a list of objects that share the same "one" object reference.
In the case of your Car and Street example.
classdef Car < handle
    properties
        name
        street      % A handle to the street you're on
    end

    methods
        function self = Car(name, street)
            self.name = name;
            self.street = street;
        end
    end
end

And then your Street class
classdef Street < handle
    properties
        name
    end

    methods
        function self = Street(name)
            self.name = name;
        end
    end
end

And then you could use it like
% Create some streets
streets = [Street('Street1'), ...
           Street('Street2')];

% Create some cars
cars = [Car('one', streets(1)), ...
        Car('two', streets(2)), ...
        Car('three', streets(1))];

% Now get cars that are on Street1
cars_on_street_1 = findobj(cars, 'street', streets(1));

This has the added advantage in that it is trivial to change streets (since you only have to update the car object)
cars(1).street = streets(2);

The downside is that you have to maintain a list of Street and Car objects to pass to findobj and this search could potentially get to be a performance bottleneck for a very large number of objects.
Now if you're not going to be changing what street a car is on etc. then you could always create a factory to construct the class relationships (adding references in both objects) and then just use the data that you've created.

A: If I am understanding your question correctly here is my suggestion.
Inheritance enable a new class to take on properties and methods of another class. Class B in your case wouldn't need the additional function definition if you have it inherit from class A.


text:
Q: tracking multiple objects by color OpenCV 2.x Currently i am trying to track multiple objects by color. I've based on documentation code.
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

With the above code I am tracking blue colored objects filtering the HSV blue channel. I want to simultaneously track Green colored objects and show both blue and Green in 'res' image.
I've added the following code without success
lower_green = np.array([50, 100, 100])
upper_green = np.array([70, 255, 255])
green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image.

I don't know how to add Green mask and mask (blue) in only one 'res' image using bitwise-and. Could you provide me some guidance.
Thanks in advance.

A: Just add them together.
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    lower_green = np.array([50, 50, 120])
    upper_green = np.array([70, 255, 255])
    green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image.

    # Threshold the HSV image to get only blue colors
    blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
    mask = blue_mask + green_mask

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()


text:
Q: How to set a shared example? I'm just learning to write specs in ruby, and rails. So I do have two similar models that act similar when voted: question and answer. So I try to not duplicate code and write shared example for this two.
RSpec.shared_examples_for 'User Votable' do

  let!(:user){ create :user }
  let!(:sample_user){ create :user }
  let!(:vote){ create :vote, user: user, votable: votable, vote_field: 1}

  it 'user different from resource user is accapteble' do
    expect(votable.user_voted?(sample_user)).to be_falsy
  end

  it 'user similar to resource user is accapteble' do

    expect(votable.user_voted?(user)).to be_truthy
  end

end

And a test itself
describe 'user_voted?' do
  def votable
    subject{ build(:question)}
  end
  it_behaves_like 'User Votable'
end

The last it in this spec fails( I think because of subject - it does not change when I create a vote)
So I would be very happy if I could manage and understand how to do it right way. And very thankful for any advice
Also when I try to use mock like this, it complains on not having primary key
allow(:question){create :question}

Failures:

1) Question user_voted? behaves like User Votable user similar to resource user is accapteble
     Failure/Error: expect(votable.user_voted?(user)).to be_truthy
   expected: truthy value
        got: false
 Shared Example Group: "User Votable" called from ./spec/models/question_spec.rb:23

A: Instead of having a votable method could you set the subject as such:
it_behaves_like 'User Votable' do
  subject { build(:question) }
end

A: You actually don't need to use subject, you can just set whatever context you want using let and it will be available within the block:
describe 'user_voted?' do
  let(:votable) { build(:question) }
  it_behaves_like 'User Votable'
end

Then you can just refer to votable within your shared example and it will be defined by the context:
RSpec.shared_examples_for 'User Votable' do
  let!(:user) { create :user }
  let!(:sample_user) { create :user }
  let!(:vote) { create :vote, user: user, votable: votable, vote_field: 1 }

  it 'user different from resource user is acceptable' do
    expect(votable.user_voted?(sample_user)).to be_falsy
  end

  it 'user similar to resource user is acceptable' do
    expect(votable.user_voted?(user)).to be_truthy
  end
end

You can also incidentally pass parameters into the it_behaves_like block for more flexibility.
Ref: Providing context to a shared group using a block
(Note: fixed some spelling typos above.)


text:
Q: Private posts within the user feed What is the best way to implement private posts in a users feed so that when the user pulls their feed they see all content but followers only see public content?

A: There is no way to filter activities within a feed once you retrieve them from the Stream API. With this in mind there are a couple of ways you could approach this problem. First you could perform the filtering on your end, but you would have to store all info about private/public activities inside your database. Second you could use multiple feed groups to achieve this behavior, one feed group for writing public activities one for private activities on feed group that follows both public/private (the users feed form this feed group you show to the user) and to other users you show the private feed group.


text:
Q: Counterexample to $L^1$-boundedness of the maximal operator $f \mapsto f^\#$ with $f^{\sharp}(x):=\sup_{Q\ni x}\frac{1}{|Q|}\int_{Q}|f-(f)_{Q}|dy$ My question concerns the sharp maximal operator, mapping a locally integrable function $f\colon\mathbb{R}^{n}\to\mathbb{R}$ to $f^{\sharp}\colon \mathbb{R}^{n}\to\mathbb{R}$, where $$f^{\sharp}(x):=\sup_{Q\ni x}\frac{1}{|Q|}\int_{Q}|f-(f)_{Q}|dy,$$ the $\sup$ running over all cubes with sides parallel to the coordinate axes and containing $x$.
Similar to the Hardy-Littlewood maximal operator which maps $L^{1}$ to weak-$L^{1}$, but not $L^{1}$ to $L^{1}$, I guess that the sharp maximal operator does not map $L^{1}$ to $L^{1}$. The standard example for this fact with respect to the Hardy Littlewood maximal operator, namely, the indicator function of the unit cube in $\mathbb{R}^{n}$ does not seem to serve as a counterexample in this situation.
My question: Is there a similar "cheap" counterexample which shows that the sharp maximal operator does not map $L^{1}$ to $L^{1}$ - I would appreciate this very much! I've tried to find a solution to this issue in the web, but all references do not deal with this, so that I guess that it's either entirely trivial and I don't see it - or one does have a bound $\|f^{\sharp}\|_{L^{1}}\leq C \|f\|_{L^{1}}$.
However, referring to Variable Lebesgue Spaces of Cruz-Uribe & Fiorenza (Birkhaeuser 2013), p. 230, one has $\|f\|_{L^{p}}\leq c\|f^{\sharp}\|_{L^{p}}$ for all $f\in L^{p}$, $1\leq p<\infty$. Since $f^{\sharp}\leq C Mf$ with $Mf$ the Hardy-Littlewood maximal function pointwisely, one would obtain $\|f\|_{L^{p}}\leq c \|f^{\sharp}\|_{L^{p}}\leq C \|Mf\|_{L^{p}}\leq C'\|f\|_{L^{p}}$ provided $1<p<\infty$ which implies that the norms $\|\cdot\|_{L^{p}}$ and $\|(\cdot)^{\sharp}\|_{L^{p}}$ are equivalent, but somehow I cannot image that this remains valid for $p=1$ (which would be the case if one had a bound of $f^{\sharp}$ in $L^{1}$-norm against the $L^{1}$-norm of $f$).

A: Consider $n=1$ and
$$
f\left(x\right)=\begin{cases}
0, & x\leq-1,\\
-1, & -1<x\leq0,\\
1, & 0<x\leq1,\\
0, & x>1.
\end{cases}
$$
For $x\in\mathbb{R}$ with $\left|x\right|\geq1$, we then have $x\in\left[-\left|x\right|,\left|x\right|\right]=:Q_{x}$
with $Q_{x}\supset\left[-1,1\right]$ which implies $\left(f\right)_{Q_{x}}=\left(f\right)_{\left[-1,1\right]}=0$
and thus
\begin{eqnarray*}
f^{\#}\left(x\right) & \geq & \frac{1}{\left|Q_{x}\right|}\int_{Q_{x}}\left|f\left(y\right)\right|\,{\rm d}y\\
 & = & \frac{1}{2\left|x\right|}\cdot\int_{-1}^{1}\left|f\left(y\right)\right|\,{\rm d}y\\
 & = & \frac{1}{\left|x\right|},
\end{eqnarray*}
which easily implies
$$
\int_{\mathbb{R}}f^{\#}\left(x\right)\,{\rm d}x\geq\int_{1}^{\infty}f^{\#}\left(x\right)\,{\rm d}x\geq\int_{1}^{\infty}\frac{1}{x}\,{\rm d}x=\infty
$$
and hence $f^{\#}\notin L^{1}$, although clearly $f\in L^{1}$.
I leave the modification for $n>1$ to you.


text:
Q: How to combine a SVM classifier and a Naive Bayes classifier I have two different set of features for which I have a SVM classifier and a Naive Bayes classifier, respectively. If I wanted to combine these two classifiers to get a better prediction, what option do I have?

A: You should look into the variety of ensemble methods available for this sort of situation! One idea you might try, is try classifying every sample with both classifiers, and then take the vote of the classifier that has the most certainty associated with its prediction. I like this particular approach, because I tend to learn something new about the way I'm modeling my features by looking at the samples that both classifiers get wrong.


text:
Q: explicit matrix elements for a representation decomposed into subgroup by branching rules I'm looking for a way to construct a representation for a simple Lie group such that one particular subgroup is manifest. I learned the branching rules from Cahn, Georgi and Slansky, but I'm still not sure how to derive the explicit representation from the weight system deformed by extended Dynkin diagram?
To decompose a irreducible representation under a maximal regular subalgebra, we look at the extended Dynkin diagram, which has one more node from the minus highest root added on the original Dynkin diagram, and we then eliminate another node to deform the extended Dynkin diagram into the Dynkin diagram for the maximal regular subalgebra. The key point is to replace the Dynkin coefficient corresponding to the eliminated node by the one corresponding to the extra node of the minus highest root. Thus, deforming the weight system of the given irrep with above replacement gives us the branching rules and the Cartan matrices for the subalgebra in the given irrep. For example, under the subgroup $SU(2)\times SU(2)\times SU(2) \Subset SO(7)$, we have the 8 dimensional irrep of SO(7)  deformed as $8 \rightarrow (1,2,2) + (2,1,2)$, see P33-34 LieART.
To construct the explicit matrix representation, we define the coordinates for each simple roots in an orthonormal basis (Cartan-Weyl basis) and therefore the coordinates for the fundamental weights as well. Thus, the generators corresponding to Cartan matrices have its matrix entries as the coordinate of every weights. Now, my question is what are the fundamental weights for the deformed Dynkin diagram? Should I keep the old fundamental weights except the replaced one or the new fundamental weights are resolved from the deformed Dynkin diagram? Most importantly, what's the new fundamental weight corresponding to the extended root?
I would also need help to reveal how generators of the subalgebra are in the subset of generators of the mother algebra. When I replace the Dynkin coefficient with the extended root, how could the corresponding Cartan matrix belong to linear combination of Cartan matrices of the mother algebra?
I'm a Physics student with poor knowledge in Lie algebra. Please reinterpret my description with proper language whenever you needed to.


text:
Q: Can I force CSS to load an image with Media Queries? here my css:
html {
    background: url(../img/header_mobile.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
    html {
        background: url(../img/header_tablet.jpg) no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
}

If my screen is bigger than 768px, my browser load header_tablet.jpg only

Can I force my browser to load header_mobile.jpg before with media queries ?
edit: for know what I'm doing is this:
<script type="text/javascript">
    $(window).bind("load", function () {
        if ($("html").width() > 767) {
            $('html').css('background-image', 'url({{ site.url }}/img/header_tablet.jpg)');
        }
    });
</script>

I try to find a media queries solution. on mobile load only my small picture. On tablet start to load my mobile image and load my big image.

A: Yes.  Pick a method.

*

*HTML
<img src="img/header_mobile.jpg" width=0 height=0 />

*JavaScript
img = new Image();
img.src = "img/header_mobile.jpg";

*CSS
html:after {
    background: url(../img/header_mobile.jpg);
    opacity: 0;
}


text:
Q: project euler project 4: largest palindrome product I am trying to solve Project Euler Problem 4 (A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers) but am receiving an error with my code, which is as follows:
public static boolean palindrome(String pal, int length){
    int i;//counter for charAt starting at 1
    int x=length;//counter for charAt starting at length of product
    int count=0;//counter to check if product actually is palnidrome
    for (i=1;i<=length;i++){
        if (pal.charAt(i)==pal.charAt(x)){
            count++;
            x--;
        }
    }
    if (count==length){
        return true;
    }
    return false;
}

public static void main(String[] args) {
    int x;//number one
    int y;//number two
    int z;//product of both numbers
    int largest=0;//largest number
    int length;//length of product
    String product;//product of both numbers as string
    boolean check;//variable to determine whether product is palindrome
    for (x=100;x<=999;x++){
        for (y=100;y<=999;y++){
            z=x*y;
            product=String.valueOf(z);
            length=product.length();
            check=palindrome(product,length);
            if (check==true){
                largest=z;
            }
            System.out.println(largest);
        }
    }
}

but am getting the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(String.java:646)
    at pkg4.largestpalindromeproduct.LargestPalindromeProduct.palindrome(LargestPalindromeProduct.java:24)
    at pkg4.largestpalindromeproduct.LargestPalindromeProduct.main(LargestPalindromeProduct.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
the weird thing is, when i change x to equal "length-1", the code runs fine, but that then starts with the second to last digit rather than the last one, so I keep getting 0 as my answer. Please help me fix it. Thank you for all of your help.

A: There are two hard problems in computer science: caching, naming variables, and off-by-one errors.
    for (i=1;i<=length;i++){

Everything in Java is 0-indexed.

A: I was able to figure out the answer, though I am not sure why this was the issue. In my for loop in my palindrome function, I had it as i<=length. What fixed it was changing it to (i < length). I am not sure why this is so, so could someone please enlighten me and tell me why this was happening? Thanks a lot.


text:
Q: Есть ли разница при определении переменной в стеке? Есть ли разница между:
vector<int> vec();

и
vector<int> vec = vector<int>();

Просто у меня intellisense работает только во втором случае, потому я всегда его использовал, но хочу знать имеет ли это последствия.

A: Первое объявляет функцию с именем vec с сигнатурой (void) -> vector<int> (most vexing parse), второе страдает от копипасты. Правильно делать так vector<int> vec{};

A: В первом случае Вы объявляете функцию vec:) -это известная проблема в с++ https://en.wikipedia.org/wiki/Most_vexing_parse
можно просто писать
vector<int> vec;

работать будет хорошо и правильно.


text:
Q: z-index not properly working in all components in reactjs Photo of the problem
I don't know why but I've search all the z-index properties and positioning to make it work but it doesn't
I follow all the different kind of tricks to make z-index work, also in the image this is the only page where my menu bar in the back of the component even I index my menu bar to be 99999.
Here's my code of SASS:
  .menu {
    cursor: pointer;
    position: relative;
    .menus {
      position: absolute;
      z-index: 999 !important;
      padding: 0.5rem;
      top: 120%;
      right: 0;
      background-color: white;
      border-radius: 0 0 5px 5px;
      width: 16rem;
      height: 850%;
      -webkit-box-shadow: 2px 2px 4px 1px rgba(0, 0, 0, 0.2);
      box-shadow: 0px 2px 0 0 rgba(0, 0, 0, 0.2);
      div {
        transition: all ease-in-out 200ms;
        margin: 1.2rem 0.5rem;
        &:hover {
          background-color: rgb(240, 239, 239);
          border-radius: 5px;
          padding: 3px 3px;
        }
        a {
          font-size: 16px;
          font-family: 'Montserrat';
          font-weight: 600;

          .icon {
            margin-right: 7px;
          }
        }
      }
    }
  }

Here's my Code in JSX:
{currentUser && [

             showMenu()}
              onMouseEnter={() => showMenu()}
              className="camel-case menu"
              style={{
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
            >
              {displayName} <TiArrowSortedDown size={18} />

 hideMenu()}
                onMouseEnter={() => showMenu()}
              >

                  <Link to="/dashboard">
                    <BsFillPersonFill className="icon" />
                    Profile
                  </Link>

                  <Link to="/payment">
                    <MdPayment className="icon" />
                    Payment
                  </Link>

                  <Link to="/cart">
                    <AiOutlineShoppingCart className="icon" />
                    Cart
                  </Link>

                  <Link to="/dashboard">
                    <MdHistory className="icon" />
                    Order History
                  </Link>

                  <Link onClick={() => signOut()}>
                    <RiLogoutBoxRLine className="icon" />
                    Log Out
                  </Link>

,
        ]}


text:
Q: Is there a flying-rats / hidden packages equivalent in GTA V? Former GTA titles always featured some kind of collectable placed at various often hard to reach or somewhat special places throughout the map.
It was flying rats (= pigeons) in GTA 4, horseshoes/oysters in San Andreas, hidden packages in Vice City and GTA 3.
I haven't found or heard of any of those things in GTA V.
So is there some kind of collectable, or have they broken with tradition?

A: Looking at the checklist available on Social Club, there appear to be 2 collectible missions listed under Misc. There are also 2 others not listed specifically on there, which makes 4 total.

*

*Collect 50 spaceship parts. This will also net you the From Beyond the Stars achievement/trophy. To start this quest, you need to be Franklin, and start the mission "Far Out". Some guides for this mission can be found here.

*Collect 50 Letter scraps, which are available from the beginning of the game without starting any specific mission.

*Collect 30 barrels of nuclear waste, which can be done after buying the Sonar Collections Dock for $250,000, and using the submarine.

*Collect 30 submarine parts for Abigail, which is a side mission which starts on the Sonar Collections Dock (unsure if buying the property triggers this, or not).

A: Yes, there are hidden packages.  I have found a few underwater in crashed planes and I'm sure there are a lot on land.  There's apparently one near a military base with bodies around.  Also, if you go into the water off the coast just north of the military base and find the plane wreck, the hidden package gives you 12,500 dollars.  Switch to another character and back, and the package is there again.

A: I've read that there are over 180 collectible items: waste barrels, stunt jumps, space ship parts, letter scraps, and strange missions.
However, I'm not sure if they are the equivalent of the 200 flying rats from GTAIV. I really would like to know though!
http://www.gamefront.com/gta-5-all-collectible-locations-map-graphic/

A: I (with the help of a few others) created a map on which you can view all collectables/packages etc. There are 45+ categories of items.
http://gta-5-map.com
Many of the categories have user-added content, which we moderate, but sometimes things slip through the cracks, and a location or two might be off by a few pixels.
The collectables and packages are all 'locked' though, so they should be 100% accurate.
If you sign in you can mark the ones you've already found and keep track of your progress!

A: TPI industries state that if you find anything to bring it them. This is online, and there doesn't seem to be anything to find that you can take to them.

A: There are space ship parts scattered around the map; a total of 50 pieces.


text:
Q: Scala Play Max HTTP Connection With ab I can only have maximum 50 connections (with default configuration).
The ab command I use:
ab -n 50 -c 50 http://myipaddress.net:9000/

I tried increasing the memory limit in, so I invoke the start script this way:
sh $REST_DB_HOME/bin/siie-rest -Dhttp.port=9000 -J-Xms2048M -J-Xmx2048m -J-server -Dconfig.file=$REST_DB_HOME/conf/application.conf

It only helps a little, now max http connection is around 80.
So... I tried additional approach, configuring the thread pool, following this documentation:
https://www.playframework.com/documentation/2.3.7/ThreadPools
I put this in my application.conf:
play {
  akka {
    akka.loggers = ["akka.event.Logging$DefaultLogger", "akka.event.slf4j.Slf4jLogger"]
    loglevel = WARNING
    actor {
      default-dispatcher = {
        fork-join-executor {
          parallelism-factor = 1.0
          parallelism-max = 130
        }
      }
    }
  }
}

It doesn't really change anything. Still stuck with 85 http connections (maximum). Well, Ok, I hit the 100 connections sometimes.
Is there anything else I can do at the configuration level to improve this? For comparison: a tomcat webserver can consistently handle 100 connections, and it can withstand up to 130 connections.
I also read this: http://www.ybrikman.com/writing/2014/02/18/maxing-out-at-50-concurrent-connections/
Requires code changes.... Play's code change. Not the app code. So, no go for me.
Or should I just upgrade to latest version of Play?
Thanks,
Raka


text:
Q: Devise's current_user is returning 'true' TrueClass Has anyone else ever encountered this anomaly in devise? I have a call to current_user in a method and it is returning 'true' instead of the current user currently logged in.
I did a google search on this and it looks like someone has seen these errors in the past. However, I am not able to find an answer or a workaround for this
Update:
Someone asked me whether this is coming from a test and the answer is no it is not coming from a test. It is in the controller.
Basically my user model has a method called has_badge? and it is giving me a NoMethod error saying that the object stored in current_user is a true.


text:
Q: Cant run db:migrate I trying to deploy my rails 4 application on my ubuntu server, if I run the rake db:migrate command I getting this error
rake aborted!
ArgumentError: invalid byte sequence in UTF-8

My environment:
Rails 4.1.6
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
here the trace
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/file_list.rb:395:in `glob'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/file_list.rb:395:in `glob'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:258:in `block in have_rakefile'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:256:in `each'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:256:in `have_rakefile'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:657:in `find_rakefile_location'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:673:in `raw_load_rakefile'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:94:in `block in load_rakefile'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:176:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:93:in `load_rakefile'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:77:in `block in run'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:176:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.1.4/gems/rake-10.3.2/lib/rake/application.rb:75:in `run'
/root/.rbenv/versions/2.1.2/bin/rake:33:in `<main>'

Any ideas?
On my local machine everything works fine...

A: What's the data store being used here out of curiosity?  Is it possible to just destroy the database and start fresh by chance?  If so, you can do that with:
rake db:drop db:create db:migrate