text:
Q: cloning "rows" of a form with inner functions im trying to make dynamic form with inner functions...
I have a template like:
``

                      <input type="hidden" name="policko0[]">

                      Pořadí: <input type="number" class="inputPoradi" required name="policko1[]" tabindex="1" placeholder="" value="<?php echo $posledniVPoradi + 1; ?>" min="1">

                      Typ:
                      <select class="col-md-7" name="typ[]" id="sem" tabindex="3" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
                      <option selected>Choose...</option>
                        <option value="1" <?php /* echo ($result['Typ'] == '1' ? 'selected' : '') */ ?>>Oddělení</option>
                        <option value="2" <?php /*echo ($result['Typ'] == '2' ? 'selected' : '')*/ ?>>Skupina</option>
                        <option value="3" <?php /*echo ($result['Typ'] == '3' ? 'selected' : '')*/ ?>>Položka</option>
                        <option value="4" <?php /*echo ($result['Typ'] == '4' ? 'selected' : '')*/ ?>>Vlastní sleva</option>
                      </select>

                      Název:
                      <select class="form-select" id="Sub1" required>
                        <option selected>Choose...</option>
                        <option value="sub1">Applied Maths-1</option>
                        <option value="sub2">Applied Physics-1</option>
                        <option value="sub3">Applied Physics-2</option>

                      </select>

                  <button class="col-md-1 form-group btn btn-block btn-danger odebrat" onclick="odebrat(this)">× Odebrat</button>

                      <button class="btn btn-block btn-success" type="button" onclick="pridatPole()" tabindex="1">+ Přidat</button>

`

and the "template row" can be clone with this:
``

my problem is that I want to have on the every "template row" 2 select inputs... which the first one determines options what i see in the second SELECT input... the function:
` function dynamicdropdown(n) {
                      var arr1 = ["oddělení 1", "oddělení 2"];
                      var arr2 = ["skupina 1", "skupina 2"];
                      var arr3 = ["polozka 1", "polozka 2"];
                      var arr4 = ["sleva 1", "sleva 2"];
                      if (n === "1") {
                        document.getElementById('Sub1').innerHTML = '';
                        for (var i = 0; i < arr1.length; i++) {
                          document.getElementById('Sub1').innerHTML += "<option>" + arr1[i] + "</option>";

                        }
                      } else if (n === "2") {
                        document.getElementById('Sub1').innerHTML = '';
                        for (var i = 0; i < arr2.length; i++) {
                          document.getElementById('Sub1').innerHTML += "<option>" + arr2[i] + "</option>";
                        }
                      }
                      else if (n === "3") {
                        document.getElementById('Sub1').innerHTML = '';
                        for (var i = 0; i < arr3.length; i++) {
                          document.getElementById('Sub1').innerHTML += "<option>" + arr3[i] + "</option>";
                        }
                      } else if (n === "4") {
                        document.getElementById('Sub1').innerHTML = '';
                        for (var i = 0; i < arr4.length; i++) {
                          document.getElementById('Sub1').innerHTML += "<option>" + arr4[i] + "</option>";
                        }
                      }

                    }`

now it works only in the first row... I know that i cannot us getElementById and the id in html inputs... This was just used for the examle...
How to do it? Thanks for help. M.

A: I think I understood your question and code correctly and hope that the following might be helpful. In most instances ID attributes when generating dynamic content are more trouble than they are worth ( as the expression goes ) - you are better using events to identify DOM elements and from the event.target &/or event.currentTarget you can then use other selectors (parent,child,sibling) to further traverse the DOM.
Rather than using inline event handlers ( and you were having issue with one of those anyway ) you can use delegated event listeners bound to a parent element ( in this case the document itself ) and, as mentioned, use the event to identify the element that invoked the event. From that point the various functions for adding,cloning and deleting should be modified to work with the event.target and parentNode / childNodes.
I modified very little of the original HTML ( added new class to the buttons - XBTN, modified IDs to become data-id values and removed the PHP only for the demo. The only element that still has an ID is the main parent element, id='polozky' - everything else uses dataset attributes instead.

document.addEventListener('change', e => {
  if (e.target instanceof HTMLSelectElement && e.target.dataset.id == 'sem') {
    const args = [
      ["oddělení 1", "oddělení 2"],
      ["skupina 1", "skupina 2"],
      ["polozka 1", "polozka 2"],
      ["sleva 1", "sleva 2"]
    ];
    let key = e.target.value - 1;
    let data = args[key];

    let oSelSub = e.target.closest('[data-id="sablona"]').querySelector('[data-id="Sub1"]');
        oSelSub.innerHTML = '';
        data.forEach( item=>{
          oSelSub.appendChild(new Option( item, item ));
        });
  }
});

document.addEventListener('click', e => {
  if (e.target instanceof HTMLButtonElement && e.target.classList.contains('XBTN')) {
    switch (e.target.dataset.id) {
      case 'odebrat': odebrat.call(this, e); break;
      case 'pridat': pridatPole.call(this, e); break;
    }
  }
})

var prvniPolozka = document.querySelector('[data-id="sablona"]');
var sablona = prvniPolozka.cloneNode(true);
var indexPoradi = 2;

function pridatPole() {
  let kopie = sablona.cloneNode(true);
      kopie.querySelector('input.inputPoradi').focus();
      kopie.querySelector('input.inputPoradi').value = indexPoradi;
  prvniPolozka.parentNode.appendChild(kopie);
  indexPoradi++;
}

function odebrat(e) {
  let el = e.target.parentNode;
      el.parentNode.removeChild(el);
}
[data-id='sablona'] {
  padding: 1rem;
  border: 1px solid black;
  margin: 1rem
}

        <input type="hidden" name="policko0[]">

        Pořadí: <input type="number" class="inputPoradi" required name="policko1[]" tabindex="1" value=54 min="1">

        Typ:
        <select class="col-md-7" name="typ[]" data-id="sem" tabindex="3">
          <option selected>Choose...</option>
          <option value="1">Oddělení</option>
          <option value="2">Skupina</option>
          <option value="3">Položka</option>
          <option value="4">Vlastní sleva</option>
        </select>

        Název:
        <select class="form-select" data-id="Sub1" required>
          <option selected>Choose...</option>
          <option value="sub1">Applied Maths-1</option>
          <option value="sub2">Applied Physics-1</option>
          <option value="sub3">Applied Physics-2</option>

        </select>

    <button data-id='odebrat' class="XBTN col-md-1 form-group btn btn-block btn-danger odebrat">× Odebrat</button>

        <button data-id='pridat' class="XBTN btn btn-block btn-success" type="button" tabindex="1">+ Přidat</button>


text:
Q: ¿Cómo puedo crear una clase a partir de un JSONObject con GSON (Uso Volley)? tengo este método que crea un jsonobject a partir del jsonarray. Pero ahora quisiera que GSON convirtiese ese jsonobject en un objeto de una clase que yo tengo creada llamaba Amiibo. Gracias. Este es mi código:
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsArray = response.getJSONArray("amiibo");
                    for(int i = 0;i < jsArray.length();i++){
                        JSONObject object = jsArray.getJSONObject(i);
                        list.add(gson.fromJson(String.valueOf(object), Amiibos.class));
                    }
                    miTextView.setText(list.get(5).toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("TAG", "Error Respuesta en JSON: " + error.getMessage());

                    }
                });
        requestQueue.add(jsObjectRequest);

Y aquí mi clase Amiibo:
public class Amiibos {
    String serie;
    String Personaje;
    String juegoSerie;
    String cabecera;
    int imagen;
    String nombre;
    String cola;
    String tipo;

    public Amiibos(String serie, String personaje, String juegoSerie, String cabecera, int imagen, String nombre, String cola, String tipo) {
        this.serie = serie;
        this.juegoSerie = juegoSerie;
        this.cabecera = cabecera;
        this.imagen = imagen;
        this.nombre = nombre;
        this.cola = cola;
        this.tipo = tipo;
    }
    }

    public String getSerie() {
        return serie;
    }

    public void setSerie(String serie) {
        this.serie = serie;
    }

    public String getPersonaje() {
        return Personaje;
    }

    public void setPersonaje(String personaje) {
        Personaje = personaje;
    }

    public String getJuegoSerie() {
        return juegoSerie;
    }

    public void setJuegoSerie(String juegoSerie) {
        this.juegoSerie = juegoSerie;
    }

    public String getCabecera() {
        return cabecera;
    }

    public void setCabecera(String cabecera) {
        this.cabecera = cabecera;
    }

    public int getImagen() {
        return imagen;
    }

    public void setImagen(int imagen) {
        this.imagen = imagen;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getCola() {
        return cola;
    }

    public void setCola(String cola) {
        this.cola = cola;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

A: Primeramente tienes que mapear los campos de tu clase Amiibos con los de la respuesta
{
  "amiibo": [
    {
      "amiiboSeries": "Super Smash Bros.",
      "character": "Mario",
      "gameSeries": "Super Mario",
      "head": "00000000",
      "image": "https://raw.githubusercontent.com/N3evin/AmiiboAPI/master/images/icon_00000000-00000002.png",
      "name": "Mario",
....

usando la anotación  SerializedName , por ejemplo:
import com.google.gson.annotations.SerializedName;

public class Amiibos {
    @SerializedName("amiiboSeries")
    String serie;
    @SerializedName("character")
    String Personaje;
    @SerializedName("name")
    String nombre;
    ...
    ...

Posteriormente crea el array a partir de la respuesta :
   Gson gson = new Gson(); //Instancia Gson.
   JSONArray jsonArray = response.getJSONArray("amiibo");
   Amiibos[] arrJson = gson.fromJson(jsonArray.toString(), Amiibos[].class);

Con esto tendrás los datos dentro de un Objeto GSON, para validar puedes realizarlo de esta forma:
            for(Amiibos objJson : arrJson){
                if(objJson!=null) {
                    Log.i("Nombre", objJson.getNombre());
                    Log.i("Serie: ", objJson.getSerie());
                }
            }

No olvides agregar la dependencia de GSON en tu archivo build.gradle para poder usar sus clases :
dependencies {
    ...
    compile 'com.google.code.gson:gson:2.8.2'
}

A: Supongo que estas Utilizando ArrayList.
Siendo Asi El Tamaño del Array lo podes obtener con :
list.size();

Obtener el valor de un campo de una posicion especifica por ejemplo el campo Personaje en la posicion 0,
list.get(0).getPersonaje();

Si Necesitas todos los campos lo podes recuperar con un for por ejemplo.
for (int i=0;i < list.size();i++){
        System.out.println("Personaje"+list.get(0).getPersonaje());

    }

y asi vas agregando todos los campos que desees ver,recorrer.!

Recuerda para que Gson Funcione correctamente tus variables deben de llamarse exactamente iguales a los que estan el JSON.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is the reference for the reStructuredText roles needed for using Sphinx and Sphinx's autodoc like Javadoc? I would like to use reStructuredText, Sphinx, and Sphinx autodoc for Python code in the same way one uses Javadoc for Java code, that is, for specifying parameters and return values, but also for linking to other classes, methods, etc.
I am finding it very hard to find a reference for learning how to do this. The Sphinx documentation mentions :param and :return: in passing, as mere examples of field lists. I cannot find a proper reference for these roles (and similar ones I imagine exist, such as one for "see also") anywhere.
More importantly, I find it unclear how to create links for other classes and methods, especially if those are in other packages.
Is this the main way Python developers extract documentation from source code? If so, I would expect some clear documentation and reference for this purpose somewhere.
Update: please note that I don't mean the autodoc reference. This page explains how to import docstrings into arbitrary Sphinx documents. It does not explain which roles can be used in docstrings to document parameters, return values, types, or to link to other methods and classes. For instance, a search on this page for :param does not find anything.

A: ReST fields such as param and return that can be used in docstrings are described under "Info field lists" in the "Python domain" section: https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#info-field-lists.
The roles that are available for creating cross-references to documented Python objects are described here: https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#cross-referencing-python-objects.
You should also take a look at the Napoleon extension, which supports docstring styles that many people find more legible: https://sphinx-doc.org/en/master/usage/extensions/napoleon.html.


text:
Q: MySQL data transfer/update to another database I have a forum which is here or http://neue.st/index.php
and I want to transfer the data from that forum to a new forum in a different directory http://neue.st/forums
I also only want to have select pieces of data to be transfered such as users, posts, topics, forums but not things like themes & mods
I am doing this because I kinda of screwed up the data for mods & themes for the original forum & have no idea how to reverse it because I forgot to do the backuping
Is there anyway to do this with phpmyadmin

A: A good tool to use... but not absolutely necessary is PMA (phpMyAdmin). You should log in, click on the database you want to export data from and then click the export button.

You can see there is a "custom" choice, upon selecting that you will be presented with more options including the ability to choose which tables you need to export.
After that, head on over to your other database and import the SQL file that was generated/downloaded and happy days.

A: you can use SQLYog community edition, it is easy to select what ever data you want to export.

A: If you download the Support toolkit from phpBB you are able to 'clean' the database of all non standard tables and rows (i.e. things added by MODs), leaving you with a clean database.
For themes that you no longer need, you can delete and uninstall these via your Admin control panel before removing them from your server.
If you just use 'selected' parts of your database then chances are it won't work properly because there are so many relationships between the different tables.


text:
Q: how to reset to a specific commit? I have the following recent commits when I do "git log --oneline"...I want to reset to "8ec2027",I tried some rebase commands that didnot work..what is the exact command to do this?
2503013 code: cs release 1.2.3.47
269ed14 code: Fixed below issues due to which 2nd client is not associating to GO
dca02a3 code: Donot allow the scan during WPS/EAPOL exchange.
b2fee57 code: MCC Adaptive Scheduler
6af29c4 code: Not able to connect more then 10 STA
150aacd code: Fix the Max Tx power value in 5G band and .ini support for 11h
8ec2027 Merge "code: cs release 1.2.3.46"
9015b60 Merge "code: Quarky Support on Prima"
......

A: You want to reset not rebase. Rebasing is the act of replaying commits. Resetting is making the current commit some other one.
you will need to save any work that you may have in your work directory first:
 git stash -u

then you will make you current commit the one you want with
git reset --hard 8ec2027

Optionally, after you can save where you were before doing this with:
git branch -b temp HEAD@{1}

see reflog documentation to see how this works.

A: Probably this could also work out for you

*

*Create a new branch at 2503013 (this saves the changes after 8ec202)

*git reset --hard 8ec2027


text:
Q: Perl regular expression loop through all the directory and get specific file I would like to translate the unix regular expression into Perl language to get some specific file associated with some condition.
Suppose now I have Perl script in a directory /nfs/cs/test_case/y2016 call totalResult.pl, this directory also contains lot of directories as well such as testWeek1, testWeek2, testWeek3...etc. Each directory contain sub-directory such as testCase1, testCase2, testCase3...etc. and Each testCase directory contains a file call .test_result, the contain record the result either success or fail.
So I can get the file information using unix command, for example:
wc /nfs/cs/test_case/y2016/testWeek1/testCase1/.test_result

If would like to get the test_results for each directory and sub-directory which is fail, I can do it from the current path /nfs/cs/test_case/y2016 in unix like:
grep -ri "fail" */*/.test_result

It will give me the output:
/nfs/cs/test_case/y2016/testWeek1/testCase1/.test_result:fail
/nfs/cs/test_case/y2016/testWeek3/testCase45/.test_result:fail
/nfs/cs/test_case/y2016/testWeek4/testCase12/.test_result:fail
.
.
...etc

How can I achieve it in writing a Perl script just run the command perl testCase.pl then can get the same output? I'm new in unix and Perl, anyone can help?

A: # Collect names of all test files
my @TestFiles = glob('/nfs/cs/test_case/y2016/*/*/.test_result');
# Check test files for "fail"
foreach my $TestFile ( @TestFiles ) {
  open(my $T,'<',$TestFile) or die "Can't open < $TestFile: $!";
  while(<$T>){
    if( /fail/ ) {
       chomp;
       print $TestFile,":",$_,"\n";
    }
  }
  close($T);
}

A: You can also execute the same linux command within Perl using back tick (`) operator.
@result=`grep -ri "fail" */*/.test_result`;
print @result;


text:
Q: Prevent script file to invoke remotely using SSH I am trying to prevent a script from being invoked remotely. User need to SSH login instead first and then run the script
ssh remote-server "script.sh" should fail
ssh remote-server and after login
./script.sh should work
I can change the ownership and apply chmod, but then the remote user can use ssh remote-server "sudo -u newuser ./script.sh"
Using AWS EC2 instance

A: Running ssh foo@remote-server followed by ./script.sh is equivalent to running ssh foo@remote-server ./script.sh, and running ssh foo@remote-server followed by sudo -u bar ./script.sh is equivalent to ssh foo@remote-server sudo -u bar ./script.sh (except sudo might fail because it needs a TTY, which can be worked around easily). So I'm afraid what you are asking does not make sense. Anything you do to work around this artificial difference, such as testing for the presence of $TERM or [ -t 0 ] are probably easily worked around.


text:
Q: laravel echo server , redis i have a problem with remote connections.
my vhost is : redis.test
i added this on blade file:
<script src="//redis.test:6001/socket.io/socket.io.js"></script>

.env file
BROADCAST_DRIVER=redis
REDIS_HOST=redis.test
REDIS_PASSWORD=null
REDIS_PORT=6379

echo configuration
import Echo from "laravel-echo"

window.Echo = new Echo({
   broadcaster: 'socket.io',
   host: 'http://redis.test:6001'
});

laravel-exho-server.json
{
    "authHost": "http://redis.test",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "f27485125ac2627f",
            "key": "6328e672f42cbf4cba1de3da215ec41a"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "redis.test"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "redis.test",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

it works when i try to broadcast with a local connection (2 browsers - same pc), but when i try to send a "message" from other pc on lan network (192.168.1.50) i have this error
GET: http://redis.test:6001/socket.io/socket.io.js net::err_connection_refused

[vue_warn] error in created hook

how ca i resolve this?

A: It may be a firewall issue as I can see, try to open redis port in the firewall


text:
Q: Options for remote administration of Firefox on a Windows network I'm a web developer responsible for an intranet. I develop using Firefox, but the IT guys here plan to use only Internet Explorer on the network going forwards.
This is because IE can be installed / configured from an MSI file, but Firefox doesn't provide an MSI. According to the admins, this means that remote administration of Firefox (e.g. managing updates, configuring NTLM authentication) is much harder.
From a developer's point of view, Firefox is a far superior browser, so if we were to use any browser as the company's default, I'd rather it was Firefox.
Tool me up! In the absence of an MSI file, what options are there for remote administration of Firefox? Are the same things possible, but done differently? Or do my admins have a point?
Speak slowly! I'm only a developer...

A: No doubt that it's a better browser to use and to develop for from me, but that's only a small part of what makes a good platform in the workplace. Your admins don't so much have "a" point as they do a whole zoo full of points and a large family group of baby little pointlings all waiting to grow up into points themselves.
We discussed Firefox's suitability here in the past as it happens, and the long and the short of it is that while there are a few things you can do with it, it's not suited to enterprise deployment and management in many ways, making the cost of deploying it and managing on Windows desktops it much higher than that of deploying IE, and the attitudes of the Firefox developers seem to range from total disinterest in making the product more "enterprise friendly" to active hostility towards the idea.

A: There is a project that provides MSI files of Firefox:
Firefox MSI Packages
However, you can achieve near the same result with group policy and startup scripts. You can assign a script to each PC as a startup script that will install/upgrade Firefox (or any non-MSI package for that matter). When it reboots, it runs the script and installs it. Typically you would want to check the version on firefox.exe to see if it needs upgraded and if not move on without installing again. You can even make a computer group and assign the script to the group to do a targeted deployment. It does lack the management of AD deployed software, but you can work around most of it. For example, if you wanted to remove Firefox later, you would use the same method to publish a script that would uninstall it.
Example of how to install silently in a script:
Set Installation = WshShell.Exec("\\server\share\firefox-installer.exe /S /INI=""\\server\share\customizations.ini""")

Do While Installation.Status = 0
    WScript.Sleep 5000
Loop

When installing, you will want to use any switches to make it silent since there won't be a user there to interact with it. As far as managing the customizations, you have the option of making custom group policy templates. There are also several resources available online that already have a few of these:
Firefox ADM
Additionally you can use a custom ini when installing to set defaults. This is the method I use personally. I like to let users choose when possible. They aren't going to be likely to change anything that is required for functionality (your authentication/proxy settings for example) so it's generally safe to trust them.
Installer:Command Line Arguments

A: The admins do have a point regarding manageability, although I don't see how the lack of an msi file for Firefox has anything to do with configuring it's authentication methods. That being said there are a number of application packaging tools available that can wrap the Firefox installer in an msi and provide for highly customized installs.
http://www.windowsnetworking.com/articles_tutorials/MSI-Packaging-Tools.html


text:
Q: Cordova navbar bigger in iOS 6 Working with Cordova and Ionic at the moment and trying to make an app as backwards compatible as possible (which is going surprisingly well) except I have stumbled upon one small issue.
The navbar after iOS 7 is bigger in that it covers the background of the status bar as well, as seen below.

So when I load the app on a phone running iOS 6 or earlier, the status bar doesn't get resized, the whole page just gets moved down, hiding some of the content in the footer.
Any help would be greatly appreciated. I'm probably missing something simple.

A: If I'm understanding correctly, then you need to add padding like this:
document.body.style.marginTop = "20px";

This should make the navbar view correctly.
See this - http://coenraets.org/blog/2013/09/phonegap-and-cordova-with-ios-7/


text:
Q: Can I create an Haskell function that put some strings in a tuple or in a list? For example I have a string in input: "aaa bbb ccc dddd" and my function give me
["aaa", "bbb", "ccc", "dddd"]

or
("aaa", "bbb", "ccc", "dddd")

Is possible?

A: We can just reason about the types and then look for the function in Hoogle.
For example, you need a function, which accepts a String and returns a list of Strings, e.g String -> [String]. Let's look for it:
https://www.haskell.org/hoogle/?hoogle=String+-%3E+%5BString%5D
The first one is lines with a description:

breaks a string up into a list of strings at newline characters. The resulting strings do not contain newlines.

Hm, but we need to break at spaces, not only at newline characters. Maybe there's something else?
What about words?

breaks a string up into a list of words, which were delimited by white space.

Yea, the right, one.
Thus, the answer is:
You need the words function:
words "aaa bbb ccc dddd" returns ["aaa","bbb","ccc","dddd"]


text:
Q: Runtime annotations design and performance I have a java api which performs an external resource lookup and then maps the values to a Pojo. To do this, the api needs the field names of the Pojo as string values, something like:
public <F> F populatePojoFields(String primaryField, String secondaryField);

This works fine, however passing the pojo field names as String to the api does not feel right. I was able to change this by writing marker annotations for the pojo, so now it is like
public class POJO {
   @Primary //custom marker annotation
   private int mojo;

   @Secondary //custom marker annotation
   private String jojo;
}

String primaryField = getFieldNameUsingReflection(Pojo.class, Primary.class)
String secondryField = getFieldNameUsingReflection(Pojo.class, Secondary.class)

Pojo pojo = populatePojoFields(primaryField, secondaryField);

This way I don't have to keep track of string values, I can just add marker annotations to the Pojo fields. This works fine, but I'm worried about performance. Is this a standard way to do things? as keeping hardcoded string values is more efficient than looking up the field names every time we need to call the api. Is there a better way to do this?

A: If you call getFieldNameUsingReflection often you can think to cache the result of this call.
You can use a singleton class with internal Map with a code like the following:
public class SingletonMapPrimarySecondary {
    Map<Class, String> mapPrimary;
    Map<Class, String> mapSecondary;

    // TODO: Handle mapPrimary and mapSecondary creation and singleton pattern

    public String getPrimary(Class clazz) {
        String primary = mapPrimary.get(clazz);
        if (primary == null) {
            primary = getFieldNameUsingReflection(clazz, Primary.class);
            mapPrimary.put(clazz, primary);
        }
        return primary;
    }

    public String getSecondary(Class clazz) {
        // TODO: Similar to getPrimary
    }
}


text:
Q: Error indexing method FunctionName does not resolve to a value Does anyone know why I'm getting this error?
Here is my SendGrid output binding:
{
  "bindings": [
    {
      "name": "docId",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "movedocument",
      "connection": "cpoffice365_STORAGE"
    },
    {
      "type": "sendGrid",
      "name": "message",
      "apiKey": "<MYSENDGRIDKEY>",
      "from": "<MYFROMEMAIL>",
      "direction": "out"
    }
  ],
  "disabled": false
}

My code compiles, but then it throws this error in the log:
Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.<MYFUNCTIONAME>'. Microsoft.Azure.WebJobs.Host: '<MYSENDGRIDKEY>' does not resolve to a value.

A: Statto,
Please make sure you define an app setting (Function app settings > App Settings) with the name matching what you've used for your binding configuration, where the value is your Sendgrid key.
The binding configuration expects that to be an app setting name, not the actual key.
Thanks!


text:
Q: How do I display the Var name of a variable instead of the value that Var hold in javascript? So I am trying to build myself a debugger. Here is how I want the output to look:
kills:    7
level:    60
weapon:   sniper

These values will be displayed in a black rectangle that can be dragged around the screen using the mouse. Here is what is does so far. (I have cut out all visuals except the Text command)
Note: I am using Khan academy, so the code will look slightly different.
var kills = 0;
var level = 10;
var weapon = 'sniper';

var input = [kills,level,weapon];
var debug1 = function(data){
    for(var i = 0; i < data.length; i ++){
        text(data[i],mouseX + (i*30) + 4,mouseY - 75);
    }

};

var draw = function() {
    debug1(input);
};

Code explanation: The Vars at the top are just sample Vars. I want debug1(){}; to be able to take any and all vars.
What my output results look like (compare to what I want them to look like):
0
60
sniper

My problem: I cannot find a way to print out the bar names to the screen! In my formatted print I want the Var name associated with the data it holds. but whenever (and however) I try and print in the var name I always end up with its value. This makes my debugger useless, because even though it prints out values, I cant tell what vars the data is connected with. Please help me by showing a way to do this! Things I have tried:
data[i].text

"data[i]"

A: do you have the option of making the data an associative array
i.e.
input = [Kills: kills, Level: level, Weapon: weapon]

so you can refer to them as Key/Val pairs?
You could then use something like
$.each(data, function(key, value) {
    text(key + ': '+ value,mouseX + (i*30) + 4,mouseY - 75);
});

that could be one way to work it out (havent tested it yet, but it seems straight forward)


text:
Q: Error while running annonate function for grouped bar chart: annotate() got multiple values for argument 'xy' I am using a dictionary "my_dictionary" containing key and a list containing two int items.
Dictionary - {key : [men_mean, women_mean]}.
Counts:
Values of men_mean and women_mean are close to 2000.
Total keys are 400.
I am getting following error:
Error:
----> 5         ax.annotate('{}',format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0,maximum),
textcoords="offset points", ha='center', va='bottom')

TypeError: annotate() got multiple values for argument 'xy'

Code:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels, list_item = zip(*sorted(my_dictionary.items())
for key, item in my_dictionary.items():
    men_means.append(item[0])
    women_means.append(item[1])

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects, maximum):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, maximum),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(rects1, max(men_means))
autolabel(rects2, max(women_means))

fig.tight_layout()

plt.show()

A: The problem is the comma , between {} and format(), it should be dot .:
ax.annotate('{}'.format(height), ...)

with a comma, the function annotate considers that {} is the first argument and format(height) is the second argument. since the second argument of the function is xy, it thinks you've passed two values to xy, one by position, and then one by keyword xy=.
Instead, what you wanted to do is to pass a formatted string '{}'.format() to the first argument (s) of the function


text:
Q: Mediaplayer stream online MP3 file I have an Android app that streams an MP3 file and plays this file in player,
but the problem is mediaPlayer.prepare(); takes a long time  buffering and the app freezes
so I tried to use prepareAsync();,  but with this function I can't make the player play the next file.
It just plays a single file online; if I need to play another file I have to close and restart the activity when play ends. This is my code:
public void playMp3(String _link)
{
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
    public void onPrepared(MediaPlayer mp) {
        if(!mediaPlayer.isPlaying()){
        mediaPlayer.start();
        Progressbar.setVisibility(View.INVISIBLE);
        play.setVisibility(View.GONE);
        stop.setVisibility(View.VISIBLE);
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        }
        updateProgressBar();
    }
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        mediaPlayer.reset();
        songProgressBar.setProgress(0);
        songProgressBar.setSecondaryProgress(0);
        play.setVisibility(View.VISIBLE);
        stop.setVisibility(View.GONE);
        link = "http://server11.mp3quran.net/hawashi/002.mp3";
        playMp3(link);

    }
});
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
       // Toast.makeText(getApplicationContext(), "n" + percent, Toast.LENGTH_LONG).show();
        songProgressBar.setSecondaryProgress(percent);

         if(percent==100)
         {
             Progressbar.setVisibility(View.INVISIBLE);

         }else if(percent > songProgressBar.getProgress())
         {
             Progressbar.setVisibility(View.INVISIBLE);
         }else
         {
             Progressbar.setVisibility(View.VISIBLE);
         }

    }
});

mediaPlayer.reset();
Progressbar.setVisibility(View.VISIBLE);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

try {
    mediaPlayer.setDataSource(_link);
    //mediaPlayer.prepare(); // might take long! (for buffering, etc)   //@@
    mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalStateException e) {
    // TODO Auto-generated catch block///
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}}

A: Actually I don't know where is error in your code but I will explain how I did that in my app
public void playMp3(String _link){

                mediaPlayer.reset();
                Progressbar.setVisibility(View.VISIBLE);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

            try {
                mediaPlayer.setDataSource(_link);
                mediaPlayer.setOnBufferingUpdateListener(this);
                mediaPlayer.setOnPreparedListener(this);
                //mediaPlayer.prepare(); // might take long! (for buffering, etc)   //@@
                mediaPlayer.prepareAsync();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block///
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Then implements OnCompletionListener, OnPreparedListener and OnBufferingUpdateListener in your class
public class PlayerActivity extends Activity implements OnCompletionListener, OnPreparedListener, OnBufferingUpdateListener{
.
.
.

and implements all methodes
public void onPrepared(MediaPlayer mediaplayer) {
    if(!mediaPlayer.isPlaying()){
        mediaPlayer.start();
        Progressbar.setVisibility(View.INVISIBLE);
        play.setVisibility(View.GONE);
        stop.setVisibility(View.VISIBLE);
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        }
        updateProgressBar();
}

@Override
public void onCompletion(MediaPlayer mediaPlayer) {
    //mediaPlayer.reset();
        songProgressBar.setProgress(0);
        songProgressBar.setSecondaryProgress(0);
        play.setVisibility(View.VISIBLE);
        stop.setVisibility(View.GONE);
        link = "http://server11.mp3quran.net/hawashi/002.mp3";
        playMp3(link);
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
     songProgressBar.setSecondaryProgress(percent);

         if(percent==100)
         {
             Progressbar.setVisibility(View.INVISIBLE);

         }else if(percent > songProgressBar.getProgress())
         {
             Progressbar.setVisibility(View.INVISIBLE);
         }else
         {
             Progressbar.setVisibility(View.VISIBLE);
         }
}

I wish this helped you.


text:
Q: What is the right way to install Canon PIXMA drivers on Ubuntu 16.04 LTS? My printer is a Canon PIXMA MG5350 and I am using Ubuntu 16.04 LTS. Linux drivers for debian-based distros are available at Canon's website, but the package depends on libtiff4, which is no longer available in the repositories.
This seems to be a known problem, but I've read too many possible solutions. Some of them work for me, but what is the right way to do it?

*

*Modify the package, so it does not depend on libtiff4.

*

*I tried that and the installation somehow works, but cifmg5300 returns an error, because it is unable to load libtiff.so.4.

*Symlink libtiff.so.4 to libtiff.so.5.

*

*Works, but this definitely is a dirty hack...

*Install an outdated version of libtiff4 from the 12.04 archive.

*

*Is this even secure?

*Another option?
Thanks in advance for helping me out.


text:
Q: Does anyone know how to make a css button look like this? enter image description here
I'm trying to make a button look like this in css but I can't figure out how. Someone please help me!
I haven't tried anything yet.

A: The picture is very blurry, but it should be something like this.

*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding:0;
}

.button {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-around;
  align-items: center;
  border: none;
  border-radius: .5rem;
  overflow: hidden;
  color: white;
  font-size: 1.3rem;
}

.button > * {
  padding: .5rem .8rem;
}

.tick {
  background: green;
}

.content {
  background: lightblue;
}
<button type="button" class="button">

v

Start

</button>


text:
Q: Why does ChangeNotifierProvider exist? According to Flutter's documentation here (https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple),
one way to control the state management is to use ChangeNotifierProvider(or InheritedWidget) when one of its descendants is a Consumer which is rebuilt when the underlying ChangeNotifier changes.
Flutter's team reiterates that approach on the official youtube Flutter channel.
However, that means that some business logic element (ChangeNotifier) is now part of the Widget tree (which otherwise is all about how the UI will look like). So I don't understand why those classes (ChangeNotifierProvider,InheritedWidget,Consumer) even exist.
In particular, why isn't the following approach superior:
-Business logic is a singleton and a ChangeNotifier.
-Instead of Provider(...), for every Widget depending on the business logic simply do this:
BusinessLogicSingleton.instance.addListener(() {

      setState(() {

      });

at initState(...).
What am I missing here?

A: You can indeed do that, but then you'd also have to remember to close the listener on dispose.  Providers handle that automatically.

A: How do you plan to set state in stateless widgets? Also following your suggested method, you would be rebuilding the entire widget with setstate, vs building only a specific part even for complex widgets if you were to use consumers.

A: I think there are benefits to have the ChangeNotifier a part of the widget tree. You need to ask yourself: what are the features of the Widget Tree that can benefit ChangeNotifier? Or rather - by using Widget Tree, can I get everything I get from Singleton? And can I do some things Singleton does not provide?
First - if you put your ChangeNotifier high in the tree, and you create only one ChangeNotifier for your class (e.g. ChangeNotifier) - you practically have a singleton. With added benefit of a Widget Tree logic taking care of disposing your ChangeNotifier etc.
Second - you can have multiple ChangeNotifiers of the same class in different parts of the tree, practically scoping your ChangeNotifier any way you want. This is not something a Singleton approach can offer. I'm not sure this is a good example - but imagine your ShoppingCart demo: it has a single ShoppingCart ChangeNotifier provider at the top of the tree.
Now imagine one of the items you sell are customizable - like Pizza. And when user selects Pizza - you open additional screen where a user will chose toppings. Now, this additional screen could have a new instance of ShoppingCart - tracking the toppings you added, with all the features of the shopping cart - add, remove etc. This way your module (Pizza toppings selection) becomes self-contained - it does not expect a Singleton to be provided for it, but it will inject it's own ChangeNotifier into the tree.
With the Singleton approach you would need to come up with another way - extending your shopping cart for the sake of creating another Singleton. Not very practical.

A: Following up on the question, the following hyper-simple class saves me a lot of boilerplate code, and illogical code (forcing ChangeNotifier to be a part of the Widget tree via Provider etc)
import 'package:flutter/material.dart';

//A class which makes it easier to worker with change notifier without provider/consumer which looks wrong since changenotifier shouldn't be forced into widgets tree for no reason
//eg widgets should represent UI and not business logic

class ListenerWidget extends StatefulWidget {
  const ListenerWidget({Key? key,required ChangeNotifier notifier,required Widget Function(BuildContext) builder,void Function()? action}) : notifier=notifier,builder=builder,action=action,super(key: key);
  final Widget Function(BuildContext) builder;
  final ChangeNotifier notifier;
  final void Function()? action;

  @override
  _ListenerWidgetState createState() => _ListenerWidgetState();
}

class _ListenerWidgetState extends State<ListenerWidget> {

  void emptyListener(){
    setState(() {

    });
  }

  @override
  void initState() {
    widget.notifier.addListener(widget.action??emptyListener);
    super.initState();
  }

  @override
  void dispose() {
    widget.notifier.removeListener(widget.action??emptyListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context);
  }
}


text:
Q: Bidirectional binding from Dropdown to date On selection of date in the drop down I'm trying to auto-select calendar date, however corresponding auto-selection into date, works only for first selection into dropdown, not on subsequent changes.
Could you advise on why and relevant concept I need to refer back?

const [formValue, setFormValues] =
useState({

  date: null
});

const stringToDate = (data: any) => {
  const date = data.value === "6 Months"
    ? moment().subtract(6, "months")
    : data.value === "Last Month"
      ? moment().subtract(1, "months")
      : moment().subtract(1, "weeks");
  return date.toDate();
}

<GridColumn width={8} className="fullWidth">
          <label>How much back </label>
          <Dropdown
            fluid
            selection
            options={dropdownOptions}
            value={dateDropdownValue}
            onChange={(_e: any, data: any) => {
              setFormValues({
                ...formValue,
                date: stringToDate(data.value),
              });

              setDateDropdownValue(data.value);
            }}
          />
        </GridColumn>
        <GridColumn width={8} className="fullWidth">
          <label>Exact Date is:</label>
          <CalendarWrap>
            <DatePicker
              onChange={(date) => {
                setFormValues({
                  ...formValue,
                  date: date,
                });
              }}
              selected={formValue.date}
            />
            <CalendarImg src={Icons.CalendarImage}></CalendarImg>
          </CalendarWrap>
        </GridColumn>

A: As per my understanding, you should keep track of your dropdown's state in dependency array or useEffect,  and once the value changes, call a function to reflect the desired date in Datepicker. I need more information to understand the whole problem


text:
Q: Approximate dirac delta and integration error For a sequence of functions $g_n(x-x_o)$ approximating the Dirac delta I can write:
$ \int_a^b g_n(x-x_o) f(x) dx = \int_a^b \delta(x-x_o) f(x) dx + \epsilon_n$
when $x_o \in [a,b]$. I am trying to estimate the error term $\epsilon_n$ when $g_n(x-x_o)$ is a Gaussian function. Does anybody know how this might be done?
PS: I have seen calculations of upper bounds for $\epsilon_n$ when $g_n$ is a Gaussian. But these upper bound calculations are more concerned with the dependence of the error upon $n$ (which is inversely proportional to the width of the Gaussian) than a reasonable estimate of $\epsilon_n$. If I try using the error term given by these upper bounds calculations to estimate the error then the error is far larger than what one might expect.


text:
Q: I'm implementing this for my project on diabetes prediction using Random Forest (python) please help me with this piece of code. it shows some errors

from sklearn.ensemble import RandomForestClassifier

classifier = RandomForestClassifier(estimators = 6, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

A: This is my function (based on this) to clean the dataset of nan, Inf, and missing cells. So make sure that you have non NaN values in your input. And all those values are actually float values. None of the values should be Inf either.
This error occurs when the following function is called : Github
def _assert_all_finite(X):
"""Like assert_all_finite, but only for ndarray."""
    X = np.asanyarray(X)
    # First try an O(n) time, O(1) space solution for the common case that
    # everything is finite; fall back to O(n) space np.isfinite to prevent
    # false positives from overflow in sum method.
    if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
           and not np.isfinite(X).all()):
        raise ValueError("Input contains NaN, infinity"
                      " or a value too large for %r." % X.dtype)


text:
Q: java selenium webdriver - how to output the attribute of a javascript object? I was wondering if anyone could help me find a way to output to the Eclipse console the results returned from executing a Javascript ?
These are the steps I manually perform (that I would like to automate):

*

*Open test web page.

*Open Google chrome Javascript console

*Type "productObj.mainURL" and enter

This will output to the Chrome Javascript console the URL value/attribute that I'm looking for.
I've done a fair bit of research on my own, and I am stumped.
I've tried the code below:
JavascriptExecutor js = (JavascriptExecutor) driver;
String mainURL = (String) js.executeScript("productObj.mainURL");
System.out.println(mainURL);

But all I get returned is a "null"...
Any help please?

A: Your JavaScript doesn't return anything, so you get null in your mainURL string.
Add a return statement to the JavaScript:
JavascriptExecutor js = (JavascriptExecutor) driver;
String mainURL = (String) js.executeScript("return productObj.mainURL;");
System.out.println(mainURL);

Relevant documentation


text:
Q: How can I edit the style of an object on hover? Simply trying to learn javascript, right now trying to get my content (which is simply just a redbox at this time) to expand once hovered over.
Don't see what I'm doing wrong. Help is greatly appreciated.
My html:

My css:
 .content
    {
      width:100px;
      height:100px;
      background-color:red;
      margin:auto;
      position:absolute;
      top:0;
      right:0;
      left:0;
      bottom:0;
    }

My javascript:
function expand()
{
  var content = document.getElementsByClassName("content");
  content.style.width = "200px";
}

A: The issue is here:
var content = document.getElementsByClassName("content");

Because getElementsByClassName returns an HTMLCollection. (For more info on how this works, check the info in the link).
A quick fix will be to retrieve the first element from the result:
var content = document.getElementsByClassName("content")[0];

But this will only work for the first DOM element with this class, for other elements they will simply be ignored.
Another solution may be passing the current element to the function by using this, then updating the style of the element accordingly.

function expand(elem) {
    elem.style.width = "200px";
}

And a third (and IMO better) option is to do it using CSS :hover.

A: instead of using javascript to expand you can use CSS itself:
.content:hover {
    transform: scale(1.5);
}

change the 1.5 to however much you want to scale it.


text:
Q: MySQL query does not return needed result. Customers who does not have any orders, does not show Im still doing my SQL training. So I have two tables CUSTOMERS and ORDERS( foreign key table). Now I need to get all customers without any ORDERS. Here is my query
select LASTNAME, FIRSTNAME
  from CUSTOMERS
  WHERE CUSTOMERS.ID NOT IN
      (select ID_CUSTOMER from ORDERS);

+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID        | int(11)      | NO   | PRI | NULL    |       |
| FIRSTNAME | varchar(50)  | YES  |     | NULL    |       |
| LASTNAME  | varchar(50)  | YES  |     | NULL    |       |
| ADDRESS   | varchar(100) | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| ID            | int(11)      | NO   | PRI | NULL    |       |
| PRODUCT_NAME  | varchar(100) | YES  |     | NULL    |       |
| PRODUCT_PRICE | double(10,4) | YES  |     | NULL    |       |
| DATE_ORDER    | date         | YES  |     | NULL    |       |
| ID_CUSTOMER   | int(11)      | YES  |     | NULL    |       |
| AMOUNT        | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

But I do recieve Empty set (0,00 sec)/ But Im sure about that those are present;

A: I suspect there are some NULL values in ID_CUSTOMER column of ORDERS table. NOT IN fails when there is a NULL value present in sub-query.
Use NOT EXISTS
select LASTNAME, FIRSTNAME
  from CUSTOMERS C
  WHERE NOT EXISTS (select ID_CUSTOMER from ORDERS O Where C.ID = O.ID_CUSTOMER );


text:
Q: XmlSerializer: The string '' is not a valid AllXsd value I'm getting this message,"The string '7/22/2006 12:00:00 AM' is not a valid AllXsd value.", when deserializing an XML, the element contains a date, this is the property that is supposed to be mapped to the element:
[XmlElement("FEC_INICIO_REL",typeof(DateTime))]
public DateTime? FechaInicioRelacion { get; set; }

Am I doing something wrong?
UPDATE:
Here is the XML:
<Detalle>
  <NOM_ASOC>Financiera Panameña</NOM_ASOC>
  <DESCR_CORTA_RELA>PREST. PERSONAL</DESCR_CORTA_RELA>
  <FEC_INICIO_REL>7/22/2006 12:00:00 AM</FEC_INICIO_REL>
  <FEC_FIN_REL>9/22/2008 12:00:00 AM</FEC_FIN_REL>
  <MONTO_ORIGINAL>1160.0000</MONTO_ORIGINAL>
  <NUM_PAGOS>2</NUM_PAGOS>
  <DESCR_FORMA_PAGO>PAGOS VOLUNTARIOS</DESCR_FORMA_PAGO>
  <IMPORTE_PAGO>59.9400</IMPORTE_PAGO>
  <FEC_ULTIMO_PAGO>11/15/2006 12:00:00 AM</FEC_ULTIMO_PAGO>
  <MONTO_ULTIMO_PAGO>0.0000</MONTO_ULTIMO_PAGO>
  <DESCR_OBS_CORTA />
  <SALDO_ACTUAL>1078.3900</SALDO_ACTUAL>
  <NUM_DIAS_ATRASO>0</NUM_DIAS_ATRASO>
  <HISTORIA>1</HISTORIA>
  <MONTO_CODIFICADO />
  <FEC_ACTUALIZACION>10/17/2008 12:00:00 AM</FEC_ACTUALIZACION>
  <COD_GRUPO_ECON>  </COD_GRUPO_ECON>
  <TIPO_ASOC>  </TIPO_ASOC>
  <NUM_REFER>2008628116</NUM_REFER>
</Detalle>

A: I realize that this is an old question, but I had this issue today and I found a workaround using properties and casting.
private string _date; // Private variable to store XML string

// Property that exposes date. Specifying the type forces
// the serializer to return the value as a string.
[XmlElement("date", Type = typeof(string))]
public object Date {
    // Return a DateTime object
    get
    {
        return
            !string.IsNullOrEmpty(_date) ?
            (DateTime?) Convert.ToDateTime(_date) :
            null;
    }
    set { _date = (string)value; }
}

Now, whenever you need to refer to the date, you simply call:
var foo = (DateTime?)Bar.Date

It's been working fine for me since. If you don't mind adding the extra cast in your code, you can do it this way as well!
Edit: Due to Dirk's comment, I decided to revisit my implementation in a seperate branch. Rather than using an object class, which is prone to runtime compiler errors, I return the value as a string.
[XmlElement("date")]
public string Date;

Which makes the declaration much simpler. But when attempting to read from the variable you now need to provide null checks.
var foo = string.IsNullOrEmpty(Date) ? Convert.ToDateTime(Date) : (DateTime?) null

It works the exact same way as the previous implementation, except the casting and null checks occur at a different location. I want to be able to write my model and then forget about it, so I still prefer my implementation instead.
On another note, I added a correction to the cast before the edit: DateTime should be DateTime?.

A: For those who come across this here is the simplest answer, I ran into the same issue, but didn't need nullable DateTime. The XMLElement only need a get not a set when rendering XML.
private DateTime _fechaInicioRelacion;

[XmlElement("FEC_INICIO_REL")]
public string FechaInicioRelacionString
{
    get
        {
            return _fechaInicioRelacion.ToString("yyyy-MM-ddTHH:mm:ss");
        }
    set { }
}

[XmlIgnore]
public DateTime FechaInicioRelacion
{
    get { return _fechaInicioRelacion; }
    set { _fechaInicioRelacion = value; }
}

A: I solved the issue by storing the date in string and then creating a getter which parses the date and returns it as DateTime.
Sample code:
    [XmlElement("Valid")]
    public string _Valid
    {
        get;
        set;
    }

    [XmlIgnore]
    public bool? Valid
    {
        get
        {
            if (!string.IsNullOrWhiteSpace(_Valid))
            {
                return bool.Parse(_Valid);
            }

            return null;
        }
    }

A: AllocationDate is a mandatory field but can be supplied as blank which is handled by representing it by AllocationDateString:
    private DateTime? _allocationDate;

    [XmlIgnore]
    public DateTime? AllocationDate
    {
        get { return _allocationDate; }
        set { _allocationDate = value; }
    }

    [XmlAttribute("AllocationDateTime")]
    public string AllocationDateTimeString
    {
        get
        {
            return _allocationDate.HasValue ? XmlConvert.ToString(_allocationDate.Value, XmlDateTimeSerializationMode.Unspecified)
            : string.Empty;
        }
        set
        {
            _allocationDate = !string.IsNullOrEmpty(value) ? XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Unspecified) : (DateTime?)null;
        }
    }

A: Try adding "IsNullable=true" attribute.


text:
Q: Pass an argument when calling setOnClickListener? Is it possible to pass an argument to the listener when a button is clicked:
protected void onCreate(Bundle savedInstanceState) {
    ....

    String myArg = "Hello";
    Button button1 = (Button)findViewById(R.id.myButton);
    button1.setOnClickListener(myListener);

    String myArg = "Goodye";
    Button button2 = (Button)findViewById(R.id.myOtherButton);
    button2.setOnClickListener(myListener);
}

OnClickListener clickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
            // print the value from the passed in argument myArg
        Log.v("TEST", myArg);
    }
};

This is just an example and not a reflection on what I actually wan't to do but it does illustrate the question.
Basically I want to pass in myArg to the listener so when the button is clicked it has access to the myArg variable.
I know I could do this as an inline anonymous class but I will have lots of buttons and the click logic is the same for all of them. I need the argument as it will be different for each button.
FYI: My real usage requires that the argument be a View object.

A: I think the typical manner in which this sort of problem is addressed is a test of the id of the click target:
OnClickListener clickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.myButton) {
             //
        } elseif (v.getId()==R.id.myOtherButton) {
             //
        }
    }
};

If that's insufficient, you can employ the generic tag property of a view:
Button button1 = (Button)findViewById(R.id.myButton);
button1.setTag("Hello");
button1.setOnClickListener(myListener);

Button button2 = (Button)findViewById(R.id.myOtherButton);
button2.setTag("Goodye");
button2.setOnClickListener(myListener);

...
OnClickListener clickListener = new View.OnClickListener() {

@Override
public void onClick(View v) {
        // print the value from the passed in argument myArg
    Log.v("TEST", v.getTag());
   }
};

And finally you can even set multiple tags:
 button1.setTag(R.id.arg1, "Hello");
 button1.setTag(R.id.arg2, "World");

Would that suit your purposes?

A: Why not just create a class that implements View.OnClickListener? This would ideal if you are reusing the code for each button as well.
public class MyListener implements View.OnClickListener
{
    private View mView;

    public MyListener(View v) {
        mView = v;
    }

    @Override
    public void onClick(View v) {
        // Use mView here if needed
    }
}

And then use it like you would normally:
OnClickListener listener = new MyListener(myView);


text:
Q: javascript drag a div if you click in a subsection of this div I am developing this javascript application that when you open there a few svg components that have click listeners. The idea is that most (maybe all) of them will need to display information at the same time and I would like the user to choose what information he can see simultaneously because certainly all will not fit in the screen. So my idea was to use a div that you can drag but also interact with the content (and multiple of these divs could be open at any time.
I have tried some of the jQuery UI stuff but that does not seem to do the trick, the closest thing I could find there was a pop-up that blocks the rest of the site content.
I decided to go for interactjs that basically just gives me draggable and resizable divs, which is great! Unfortunately, I could not find how to make just certain parts of the divs draggable (like the top of the window that actually drags the window in your regular OS) and how to allow the user to interact with the content inside the div window (since everything is just the click-to-drag area). I mainly used the code from the example http://interactjs.io/ (pasting here for reference):

     Resize from any edge or corner

and here is the js:
interact('.resize-drag')
  .draggable({
    onmove: window.dragMoveListener
  })
  .resizable({
    preserveAspectRatio: true,
    edges: { left: true, right: true, bottom: true, top: true }
  })
  .on('resizemove', function (event) {
    var target = event.target,
        x = (parseFloat(target.getAttribute('data-x')) || 0),
        y = (parseFloat(target.getAttribute('data-y')) || 0);

    // update the element's style
    target.style.width  = event.rect.width + 'px';
    target.style.height = event.rect.height + 'px';

    // translate when resizing from top or left edges
    x += event.deltaRect.left;
    y += event.deltaRect.top;

    target.style.webkitTransform = target.style.transform =
        'translate(' + x + 'px,' + y + 'px)';

    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
    target.textContent = Math.round(event.rect.width) + '×' + Math.round(event.rect.height);
  });

A: I think I figured it out in a very simple way. My problem is just this: How to make only parts of a div draggable? Usually when you do something like:

 I want to be dragged if this is clicked

 I do not want to be dragged if this is clicked

The whole #draggable div is set to draggable so you cannot really interact with the contents of the div. However, with jQuery I did the following:
<!doctype html>

      <meta charset="utf-8">
      <title>jQuery UI Draggable - Default functionality</title>
      <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

      <link rel="stylesheet" href="/resources/demos/style.css">

                click here to drag this thing

Do not want to drag if click here

When your mouse is over the top div the draggable is enabled and you are able to move the div. Otherwise is just like any other div with content.


text:
Q: rmarkdown resize plot inside of code chunk I have an rmarkdownfile with a chunck that has a loop that creates many pages. Below is a toy example.  See the "loop_chunk" code chunk. The "loop_chunk" has  fig.width=9, fig.height=6, results="asis" and I am running into a problem where i need to reduce the size of a plot inside loop_chunk. All plots are 9x6 but I need to adjust one plot. I found the codee below: http://michaeljw.com/blog/post/subchunkify/
and I tried using it below but when you run the code you can see that there are 2 plots on pages 3 and 5 and there should not be. it  is somehow not keeping the \newpages. There should be 1 plot on pages 2,3,4 and 5. There should only be 5 pages.
Any idea how to fix this?
---
title: "Untitled"
output: pdf_document
toc: yes
---

```{r setup, include=FALSE}

knitr::opts_chunk$set(echo = FALSE  , comment = NA, message= FALSE, warning = TRUE)

subchunkify <- function(g, fig_height=7, fig_width=5) {
  g_deparsed <- paste0(deparse(
    function() {g}
  ), collapse = '')

  sub_chunk <- paste0("
  `","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
  "\n(",
    g_deparsed
    , ")()",
  "\n`","``
  ")

  cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}

data = data.frame(group= c("A","A"), value = c(1,3))

```

```{r loop_chunk, fig.width=9, fig.height=6, results="asis", message= FALSE, warning = FALSE}

for(i in 1:nrow(data)){

  cat(paste0("\\newpage\n # Page ", i  ," \n"))

  plot(data$value[i])

  cat("\n\n")

    cat(paste0("\\newpage\n ## page with smaller plot \n\n"))

    cat("Here is some text on this page for the smaller plot.")

     cat("\n\n")

    data2 =  data.frame(x = 7, y = 900)
    library(ggplot2)
    myplot  = ggplot(data2, aes(x = x, y = y    ))+geom_point()
    subchunkify(myplot , 4,4 )
    # print(myplot) -> IS there a way to just reduce the height and width with print()?

  cat("\n\n")

}

```

A: Using your subchunkify() function for the graphics::plot call outputs those plots to the intended pages. Replacing plot(data$value[i]) in your second chunk with
subchunkify(plot(data$value[i]), 5, 5)

outputs the 5 pages with plots as intended (where height & width are set to 5/can be edited to conditionally set dimensions for a specific plot).


text:
Q: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client please solove this Sir i'm facing this issue in nodejs, expressjs while registring  a user in database.
we here making a pizza ordring app .
here is issue:
node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:794:10)
    at ServerResponse.location (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:915:15)
    at ServerResponse.redirect (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:953:18)
    at D:\expressJsBySujeet\Realtime-pizza\app\http\controllers\authController.js:40:32
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

here is my code authController.js:
async newUserregister(req, res) {
  const { Uname, email, password } = req.body; // getting data as array distructing
  if (
    !req.body.Uname.trim().length == 0 &&
    !req.body.email.trim().length == 0 &&
    !req.body.password.trim().length == 0
  ) {
    // check email exist or not
    newUser.exists({ email: email }, (err, result) => {
      if (result) {
        req.flash("error", "This Email Already exists");
        req.flash("Uname", Uname);
        req.flash("email", email);
        return res.redirect("/register");
      }
    });
    // create new user in data base
    const encPass = await bcrypt.hash(password, 10);
    const user = new newUser({
      Uname: Uname,
      email: email,
      password: encPass,
    });
    user
      .save()
      .then((user) => {
        console.log(user);
        return res.redirect("/ac");
      })
      .catch((err) => {
        req.flash("error", "something went wrong");
        return res.redirect("/register");
      });
  } else {
    req.flash("error", "All fields are required");
    req.flash("Uname", Uname);
    req.flash("email", email);

    return res.redirect("/register");
  }
}

line no 40 is start with :

req.flash('error','something went wrong')
return res.redirect('/register')

i'm creating a user register system in expressjs
please answer how this will fixed

A: Wait until you've finished checking if the user exists or not before creating a new user - otherwise, if you do  res.redirect('/register') and then do the same thing later, you'll have redirected twice. Only redirect exactly once.
You should also check if the .exists call throws an error, instead of ignoring it.
async newUserregister(req, res){
    const { Uname, email, password } = req.body;
    if (!Uname.trim().length || !email.trim().length || !password.trim.length) {
        req.flash('error', 'All fields are required')
        req.flash('Uname', Uname)
        req.flash('email', email)
        return res.redirect('/register')
    }
    newUser.exists({ email }, (err, result) => {
        if (err) {
            req.flash('error', 'something went wrong')
            return res.redirect('/register')
        }
        if (result) {
            req.flash('error', 'This Email Already exists')
            req.flash('Uname', Uname)
            req.flash('email', email)
            return res.redirect('/register')
        }
        bcrypt.hash(password, 10)
            .then((encPass) => {
                const user = new newUser({
                    Uname,
                    email,
                    password: encPass
                })
                return user.save();
            })
            .then((user) => {
                console.log(user)
                res.redirect('/ac')
            })
            .catch(err => {
                req.flash('error', 'something went wrong')
                res.redirect('/register')
            });
    });
}

The syntax gets a lot easier if .exists returns a Promise, or you can change to a Promise-based version of it - then you can catch only at the end, and await all the Promises. Something like:
async newUserregister(req, res){
    const { Uname, email, password } = req.body;
    if (!Uname.trim().length || !email.trim().length || !password.trim.length) {
        req.flash('error', 'All fields are required')
        req.flash('Uname', Uname)
        req.flash('email', email)
        return res.redirect('/register')
    }
    try {
        const userAlreadyExists = await newUser.exists({ email });
        if (userAlreadyExists) {
            req.flash('error', 'This Email Already exists')
            req.flash('Uname', Uname)
            req.flash('email', email)
            return res.redirect('/register')
        }
        const encPass = await bcrypt.hash(password, 10);
        const user = new newUser({
            Uname,
            email,
            password: encPass
        })
        await user.save();
        console.log(user)
        res.redirect('/ac')
    } catch (err) {
        req.flash('error', 'something went wrong')
        res.redirect('/register')
    }
}


text:
Q: Can I set the font size of a button inside the  tag directly? I have this code:
<Button x:Name="correctButton" HeightRequest="60" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
   <Button.FontSize>
       <OnPlatform x:TypeArguments="x:Double" x:Key="WindowBackgroundTable">
           <On Platform="Android" Value="20" />
           <On Platform="iOS" Value="25" />
       </OnPlatform>
   </Button.FontSize>
</Button>

Is there a way that platform specific sizes can be set without have the
<Button.FontSize>

A: No, you will always need some kind of extra code like this if you want to make a difference per platform.
Normally, you would set it like this: <Button FontSize="25" x:Name="correctButton" HeightRequest="60" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" />
But you cannot distinguish values for platforms. What you could do, like Anto mentioned, is create a style and set the values, per platform, there. You code will look a bit cleaner in the page itself, but the idea remains the same.
To do this, in your App.xaml, add your style:
<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:Double" x:Key="WindowBackgroundTable">
            <On Platform="Android" Value="20" />
            <On Platform="iOS" Value="25" />
        </OnPlatform>

        <Style TargetType="Button">
            <Setter Property="FontSize" Value="{DynamicResource WindowBackgroundTable}" />
        </Style>
    </ResourceDictionary>
</Application.Resources>

And remove the FontSize from your Button.
Like this, it is implicit, every Button in your app will be styled.
If that is not what you want, add the x:Key property to the Style tag, like so: <Style x:Key="ButtonStyle" TargetType="Button">.
And edit your button like this: <Button Style="{StaticResource ButtonStyle}" Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />

A: Well if you are only desperate about not having nested tags you could go this route:
<Label FontSize="{resources:PlatformedDouble Android=50, iOS=20}"></Label>

By declaring a markup extension like this:
public class PlatformedDouble : IMarkupExtension<double>
{
    public double Android { get; set; }

    public double iOS { get; set; }

    /// <inheritdoc />
    public double ProvideValue(IServiceProvider serviceProvider)
    {
        switch (Device.RuntimePlatform)
        {
            case Device.Android:
                return Android;
            case Device.iOS:
                return iOS;
        }

        return 42;
    }

    /// <inheritdoc />
    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return ProvideValue(serviceProvider);
    }
}


text:
Q: Dynamic transparent background in my Android App Java I want to set the background to a transparent image and change the color of the background on an event firing.
I can set the background image to a resource in an xml file, and I can also change the color of a TextView on event firing, but for some reason I can't do both at the same time. Do I need to create a drawable or something?
Also, how do I reference the top level LinearLayout. I'm programming using Eclipse Java EE Galileo with the ADT Plugin and the android sdk. O.S. android 2.1-update1 (eclair). My friend can do it in actionscript and I have to do it in java to beat him lol.

A: Well Mike you can get the refrence to root LinearLayout only when you declare android:id in your concerned layout xml file.
Then in your java code
get your LinearLayout l1 = (LinearLayout)findViewById('R.id.....');
then set background using setBackground function for l1 object.


text:
Q: How to show that $\mathbb{R}$ admits no algebraic field extension of degree >2? Suppose $F \supset \mathbb{R}$ is an algebraic field extension of degree $\geq 2$.
I would like to show that $F\supset \mathbb{R}$ must be isomorphic
either to $\mathbb{R}$ or to $\mathbb{C}\supset \mathbb{R}$. Is it possible to do so without assuming $F$ is already algebraically closed? (We can assume we already know $\mathbb{C}$ is algebraically closed.)

A: Any algebraic extension of $\Bbb{R}$ is contained in $\Bbb{C}$ as $\Bbb{C}$ is the algebraic closure of $\Bbb{ R}$
$\Bbb{R}\subset F\subset \Bbb{C}$
Then $[F:\Bbb{R}][\Bbb{C}:F]=[\Bbb{C}:\Bbb{R}]=2$
Since $2$ is a prime at least one of the field extension must have degree $1$ i.e either $[F:\Bbb{R}]=1$ or $[\Bbb{C}:F]=1$ .Hence either $F=\Bbb{R} $ or $F=\Bbb{C}$


text:
Q: How does the WAR suit ability Shield Wall work? Any soldier who has a WAR suit (tier 3 heavy weapon armor) equipped gains a "Shield Wall" ability, allowing them to act as high cover for other soldiers (something like one of the MEC Trooper abilities from XCOM: Enemy Within).
The game doesn't really explain well how this ability affects both the soldier who deploys the shield, and any soldiers who then take cover behind the shield.

*

*Is the soldier deploying the shield immune to damage, or do they still take damage as normal?

*Can the soldier deploying the shield still take advantage of any environmental cover while also activating the shield? For example, can a WAR suit soldier crouch behind low cover, deploy the shield, and still take advantage of the low cover?

*Does activating the shield give the WAR suit soldier a defensive bonus that stacks with whatever cover that he is using?

A: The purpose of the shield wall is to provide full cover where none exists. The soldier that casts it turns into that heavy cover, but as a side-effect that soldier receives no bonuses. The benefit of using it is to, say, move up to a soldier that is now being flanked and give him some hard cover. Kinda like in the last game with Alloy SHIVs. You could move one up to a soldier standing, and it would provide them with hard cover.
The uses of the shield wall are still very...limited. I think it can have some good uses if the right combination of buffs are applied by your other squadmates, but that's a lot of spent moves that might work better for a different strategy.
Basically, let's say you deploy it in a no man's land of cover and want to move someone else up, say a Sharpshooter, to get in some sweet pistol kills. But you don't want to leave them flapping in the wind and open to flanks, who wants to do that? So you use the shield wall and move someone up into that no man's land.
However, once you do that, then that soldier is flanked. Even though you can now move someone up behind them and they will have full cover, your shield-wall soldier is considered flanked (they're standing in the open). This renders the full-cover benefit to the soldier behind them worthless, because the aliens will prioritize shooting the now flanked soldier in their sights over everything else.
It still seems to me that it might have some interesting things with it, such as a grenadier with blast padding. That gives you 3 or 4 armor pips I think, which is very tanky. Combine that with a very high dodge PCS, and aid protocol, and you'll have a virtually untouchable wall of hard cover that can move. Still, I'd rather spend moves with my specialists elsewhere, like overwatching with guardian, hacking, or using combat protocol. And use my Grenadier for more useful things like Salvo.

A: The Shieldwall appears to absorb no damage whatsoever. My guy took full damage from all angles and she was even flanked meaning there could be some gain from cover as well.

A: The effect of Shield Wall is: you become high cover.
That's it. You don't get any sort of defense bonus, you don't get damage resistance, nothing else. On the bright side, it doesn't appear to prevent you from taking cover, either. The net effect is that you're a regular soldier in every way, except that wherever you're standing happens to count as a high cover tile.


text:
Q: PHP redirect loop issue When I submit my category search form, I want it to run the php code in the DisplayMealsCont.php and then go back to the main.php with the updated session variables. But when I try to put in a Header("Location: ../View/Main.php"); in the DisplayMealsCont.php it gets stuck in a redirect loop.
main.php
<?php
require_once("../Controller/DisplayMealsCont.php");
session_start();

$category = "All";
if(isset($_SESSION['table'])){
    $table = $_SESSION['table'];
}
if(isset($_SESSION['Category'])){
    $category = $_SESSION['Category'];
    if($category == "All"){
    $category = " ";
    }
}
?>
<?php

if (is_array($table)) {
foreach($table as $item) {
?>

  <?= $item['Meal_Name'] ?>
     <?= $item['Description'] ?>
     <?= $item['Image'] ?>
     <?= $item['Category'] ?>
     <?= $item['Quantity'] ?>
     £ <?= $item['Price'] ?>

 <?php
 }
 }

 ?>

    <form method="post" action="../Controller/DisplayMealsCont.php">
        Category:

        <select name="Category">
        <option value="All">All</option>
            <option value="Main">Main</option>
            <option value="Drink">Drinks</option>
        </select>

        <input type="submit" name="categorysubmit" value="Search" />
        </form>

DisplayMealModel.php
<?php
require_once("../Model/config.php");

class DisplayMeals
{
public $dbConnection;

public function __construct(){

    $db= new database();
    $connect=$db->getdatabase();
    $this->dbConnection = $connect;

}

public function MainMeals($category){
    $_SESSION['test'] = $category;
    $stmt = $this->dbConnection->prepare("SELECT * from meal WHERE Category LIKE '$category%'");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);

}
?>

DisplayMealCont.php
<?php
require("../Model/DisplayMealModel.php");

$newMeal = new DisplayMeals();
if(!isset($category)){
$category = "main";
}
if(isset($_SESSION['Category'])){
$category = $_SESSION['Category'];
}
$table = $newMeal-> MainMeals($category);
$_SESSION['table'] = $table;

?>

A: I can't see why a header() in there causes a redirection loop, but have you tried adding a die(); after header()?
It's a good practice, and in case it works it may shed light into what is causing the issue. Other than that, it would help if you posted the code with the looping header in it so we can see.


text:
Q: Why i can't see the player after starting this code on pygame? while i will starting this code i can't see anything...
why this code cat't drawing player and points?
import pygame , sys, random
from pygame.math import Vector2

class PLAYER:
    def __init__(self):
        self.body = [Vector2(5,10), Vector2(6,10), Vector2(7,10)]
        self.direction = [1,0]
    def draw_player(self):
        for block in self.body:
            x_pos = int(block.x * cell_size)
            y_pos = int(block.y * cell_size)
            block_rect = pygame.Rect(x_pos, y_pos,cell_size, cell_size)
            pygame.draw.rect(screen, (0,255,0), block_rect)
    def player_move(self):
        body_copy = self.body[:-1]
        body_copy.insert(0,body_copy[0] + self.direction)
        self.body = body_copy[:]

class POINT:
    def __init__(self):
        self.x = random.randint(0,cell_num - 1)
        self.y = random.randint(0, cell_num - 1)
        self.pos = Vector2(self.x, self.y)
    def draw_point(self):
        point_rect = pygame.Rect(int(self.pos.x * cell_size),int(self.pos.y * cell_size),cell_size,cell_size)
        pygame.draw.rect(screen,(255,0,0),point_rect)
pygame.init()

while didn't using classes all is worked. But after this moment alls crushed dark screen(
class MAIN:
    def __init__(self):
        self.player = PLAYER
        self.point = POINT

    def update(self):
        self.player.player_move()

    def draw_elements(self):
        self.point.draw_point()
        self.player.draw_player()

cell_size = 40
cell_num = 15

screen = pygame.display.set_mode((cell_num * cell_size, cell_size * cell_num))

main_game = MAIN()

SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE, 150)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == (SCREEN_UPDATE):
            main_game.update()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                main_game.player.direction = Vector2(0,-1)
            if event.key == pygame.K_d:
                main_game.player.direction = Vector2(1,0)
            if event.key == pygame.K_s:
                main_game.player.direction = Vector2(0,1)
            if event.key == pygame.K_a:
                main_game.player.direction = Vector2(-1,0)
    pygame.display.update()
    main_game.draw_elements()
    pygame.time.delay(60)
    screen.fill((0,0,0))

after starting this code i can't see any errors, but screen is dark...I writing this code from the learning video and author can starting this code without any problems.


text:
Q: video_player aspect ratio for m3u8 videos is different from mp4 videos on iOS I moved the videos from my app from mp4 format to m3u8 using Cloudflare Stream API. I noticed that on iOS some videos have incorrect aspect ratio and look zoomed in (not a problem on Android).
I found the following thread https://github.com/flutter/flutter/issues/97206 that has this same issue and what I understood is to use video_player: 2.2.11 version since what I have now is video_player: 2.2.7. I changed the version but that did not solve the issue. I also tried the latest version now which is video_player: 2.4.5 but still have the same problem.
If someone has idea on how to potentially solve it could you please let me know. I am stuck and do not know how to proceed in order to debug this.

A: https://pub.dev/packages/chewie lib will be used for playing m3u8 files
Add Dependency
dependencies:
  chewie: ^latest_version

Code Snippet:
import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final videoPlayerController = VideoPlayerController.network(
      'url.m3u8');
  ChewieController chewieController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      aspectRatio: 3 / 2,
      autoPlay: true,
      looping: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Sample App"),
        ),
        body: Container(
          child: Chewie(controller: chewieController),
        ));
  }
}


text:
Q: How can I know a certain file is a video file? I am trying to figure out if a certain user-uploaded file is a video file.
I first tried ffprobe,
# a png file

Input #0, png_pipe, from '<file>':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba(pc), 920x2094 [SAR 4724:4724 DAR 460:1047], 25 tbr, 25 tbn, 25 tbc

# a text file

Input #0, tty, from '<file>':
  Duration: 00:00:00.24, bitrate: 40 kb/s
    Stream #0:0: Video: ansi, pal8, 640x400, 25 fps, 25 tbr, 25 tbn, 25 tbc

# a video file

Input #0, matroska,webm, from '<file>':
  Metadata:
    encoder         : libebml v1.3.5 + libmatroska v1.4.8
    creation_time   : 2017-12-12T20:18:42.000000Z
  <redacted>

but it's too hard to figure out what's what. Even image files and text files count as a video.
Should I compare the output matroska,webm, with every codec ffmpeg supports or is there a better way to do this?

A: Assuming your system supports the file command, you can pass  -i, --mime option to get the mime type of the file and isolate it before processing with ffmpeg:
# a video file

$ file -i movie.mp4 | cut -d ' ' -f2 | cut -d '/' -f1
--> video

(Credit for cut command).

A: Using ffprobe:
ffprobe -v error -select_streams v:0 -show_entries stream=codec_type -of csv=p=0 input.mkv

Outputs either video or no output at all.
The problem is that ffprobe considers images to be video, so you can additionally/alternatively use codec_name to help determine the type:
ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,codec_type -of default=nw=1 input.png

Outputs:
codec_name=png
codec_type=video


text:
Q: How to instruct NAnt to include the console output to its log file defined in '-l' option? I have a custom NAnt task, which writes to console like this:
Console.WriteLine("Status message: " + message);

If I run my buildscript specifying the log to write to (-l:log.txt), the log file doesn't contain those lines which come from Console.WriteLine. The console window displays all info, obviously.
I know I can redirect the output to log in this way instead:
nant ... > log.txt

But this is not what I'm looking for.
So, the questions are:

*

*Is it possible to instruct NAnt somehow to grab this console output to its log?

*Should I change the custom task to achieve this?

A: Your task should use NAnt Logger instead of writing to console. Plain and simple. Redirection won't work when NAnt is using other loggers, e.g. XML output.


text:
Q: Jquery Validation Remote: displaying 1 as error message I am trying to validate username field in my form using jquery validation plugin. I have the following custom rules.
username: {
            required: true,
            minlength: 2,
            remote: {
                url: '<?php echo base_url();?>mycontoller/myfunction',
                type: 'post'
            }

Now the problem is if  my controller looks like following the plugin displays "1" as error message.
     if(1>2){
                echo False;
            } else{ echo True;}

But if I replace the code of the controller with following code, then it display an error message saying-  the username already exists.
     if(1<2){
                echo False;
            } else{ echo True;}

Now could you please tell me how to get rid of that "1" or what is the proper way to send back the values(false or true) from controller to view.
Just for your information. I am displaying all my jquery validation error messages inside a span.
like this.
         .

A: Here is an example where I'm sure you will find an answer: http://www.opencoder.co.uk/2010/07/jquery-remote-form-validation/


text:
Q: Display text vertically using XDrawString I am using XDrawString to display text on a drawing area. By default this seems to display text horizontally from Left to Right.
Could any one please tell me how I can use this library function to rotate and display text vertically from Top to Bottom or from Bottom to top.
Thanks in advance for you help.

A: You need to call it once per character, there's no single function that can draw a rotated string in Xlib. Here's a quote from the Programming Manual:

Vertical Text and Rotated Text
Xlib provides routines that draw horizontal strings, but not vertical ones. If you want to draw strings vertically that read normally, you need to use a separate text drawing call for each character. You use a baseline with the same x coordinate but a different y coordinate for each character.


text:
Q: How can any mapping $f:F\to G$ be extended to a group homomorphism uniquely? In Artin's Algebra, I read the following statement on pg.220:
"Let $F$ be the free group on a set $S=\{a,b,c,\dots\}$, and let $G$ be a group. Every map of sets $f:F\to G$ extends in a unique way to a group homomorphism $\phi:F\to G$. If we denote the image $f(x)$ of an element $x\in S$ by $\overline{x}$, then $\phi$ sends a word in $S'=\{a,a^{-1},b,b^{-1},\dots\}$ to the corresponding product of the elements $\{\overline{a},\overline{a^{-1}},\overline{b},\overline{b^{-1}},\dots\}.$"
How can any such $f$ be extended to a homomorphism? Say $f$ is defined thus: $f(a)f(b)\neq f(ab)$. Clearly this $f$ cannot be extended to a homomorphism.
Aso, what does extends in a unique way mean here? On face value, it reads like $f$ cannot be extended to a homomorphism in more than one way. But I feel if $f$ is not defined as a homomorphism initially, and extending $f$ to be a homomorphism implies taking a set of generators of $F$ and then defining $f$ for words formed form these generators accordingly, then $f$ does not extend to a homomorphism uniquely.
Thanks in advance!

A: It should read that any map of sets $f:S\to G$ uniquely extends to a homomorphism $\phi:F\to G$. A homomorphism is uniquely determined by its actions on a set of generators--which is precisely determined by $f:S\to G$ in this case.

A: Your statement is incorrect - clearly not every function $F\to G$ is a homomorphism. What is true is that any map $S \to G$ extends uniquely to a homomorphism $F \to G$ - for any string $cab\ldots$ in $F$, we must have $f(ca^{-1}b\ldots) = f(c)f(a)^{-1}f(b)\ldots$, so the homomorphism is determined by its values on $S$.

A: You made a mistake: it must be "every map $f:S\to G$ extends..." Then the expression $f(a)f(b)\neq f(ab)$ is meanless, since $f(ab)$ is not given.


text:
Q: How can I improve my java code to reduce memory garbage on android studio? I am creating a simple app which looks like a scanner with a moving backgroung image, but it start to get laggy and when I check the android profiler I notice that it is using like 400mb of memory and most part comes from graphics and native and i don't know why. Maybe I need some recyclerview or destroy method in my code to delete the used memory. How would i applied something like it in my current code?
A picture of my current android profiler
package com.example.android.miulimaapp;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    View white;
    Animation downtoup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Remove notification bar
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

        //MovingScanSquare
        white = findViewById(R.id.white);
        downtoup = AnimationUtils.loadAnimation(this, R.anim.downtoup);

        white.setVisibility(View.VISIBLE);
        downtoup = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, 1.1f,
                TranslateAnimation.RELATIVE_TO_PARENT, 0.f);
        downtoup.setDuration(2200);
        downtoup.setRepeatCount(-1);
        downtoup.setRepeatMode(Animation.REVERSE);
        downtoup.setInterpolator(new LinearInterpolator());
        white.setAnimation(downtoup);

        //movingscreen

        final ImageView backgroundOne =  findViewById(R.id.background_one);
        final ImageView backgroundTwo =  findViewById(R.id.background_two);

        final ValueAnimator animator = ValueAnimator.ofFloat(0.0f, -1.0f);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(2100L);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final float progress = (float) animation.getAnimatedValue();
                final float width = backgroundOne.getWidth();
                final float translationX = width * progress;
                backgroundOne.setTranslationX(translationX);
                backgroundTwo.setTranslationX(translationX + width);
            }
        });
        animator.start();
    }
}

A: Check the resolution of the background image.If it's too high reduce it.


text:
Q: Using a dom-repeat in a  or  breaks on IE When working with tables and select dropdowns in Polymer I have found that I can use a dom-repeat template inside of a
/<select> to print out an array of values for the tag. This works flawlessly on all Browsers except for of course Internet Explorer.
Example:
<select>
  <template is="dom-repeat" items="{{listOfItems}}" as="item">
    <option value="{{item.value}}">{{item.name}}</option>
  </template>
</select>

Another Example straight from the polymer elements catalog:

  ...

    <template is="dom-repeat" items="[[elements]]">

        [[item.name]]
        [[item.description]]

          <template is="dom-repeat" items="[[item.tags]]">
            <tag-link name="[[item]]" on-tap="tagTapped"></tag-link>,
          </template>

          <element-action-menu element="[[item.name]]" icons-only=""></element-action-menu>

    </template>

Is this just not supported in Internet explorer right now (I noticed on the Polymer site that they do not allow IE browsers to visit the table page) or is there a way to do this?

A: IE doesn't have native support for the <template> tag and has the additional quirk that it does weird things to non-
,
, or
 tags inside a table and non <option> tags inside a select.
Basically the current state is that putting a dom-repeat or similar inside a template just blows up the parser in IE and may actually leak out and break other parts of an application beyond just the table rendering.
The Polymer team is definitely aware of this issue but (as of 2016-04-01) there are no official workarounds.
You could try to fake a table using CSS display: table.  It's an ugly hack, but IE isn't giving much of an option.