text:
Q: Unity Unet Updating transform while clicked I am currently trying to make a little drawing game where two players can draw at the same time over the network.
I am using a GameObject with a TrailRenderer to draw the lines.
Right now only the drawings of the host player are shown on both machines.
If a client player clicks and tries to draw I can see that a new object is spawned but the transform doesn't get updated. The spawned prefab has a NetworkIdentity (with Local Player Authority checked) and NetworkTransform attached to it. The following script is spawned by both players and also has a NetworkIdentity (with Local Player Authority checked).
I think I am actually doing something wrong with the CmdTrailUpdate and how to handle it but I can't really figure out what.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class TrailDrawer : NetworkBehaviour {

    private Plane objPlane;
    private GameObject currentTrail;
    private Vector3 startPos;
    public GameObject trail;

    public void Start()
    {
        objPlane = new Plane(Camera.main.transform.forward * -1, this.transform.position);
    }

    // Update is called once per frame
    void FixedUpdate() {
        if (isLocalPlayer) {
            if (Input.GetMouseButtonDown(0)) {
                CmdSpawn();
            } else if (Input.GetMouseButton(0)) {
                CmdTrailUpdate();
            }
        }
    }

    [Command]
    private void CmdTrailUpdate() {
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        float rayDistance;
        if (objPlane.Raycast(mRay, out rayDistance)) {
            currentTrail.transform.position = mRay.GetPoint(rayDistance);
        }
    }

    [Command]
    private void CmdSpawn(){
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        float rayDistance;
        if (objPlane.Raycast(mRay, out rayDistance)) {
            startPos = mRay.GetPoint(rayDistance);
            currentTrail = (GameObject)Instantiate(trail, startPos, Quaternion.identity);
            NetworkServer.Spawn(currentTrail);
        }
    }
}

A: I think your problem is:
[Command] means: Invoke the method from a client but only execute it on the server.
=> You are executing both methods CmdSpawn and CmdTrailUpdate only on the server.
But:

*

*how shoud the server know your client's Input.mousePosition?

*You don't want to raycast from the server's camera.main, but rather from the client's.
Solution:

*

*Do both things local on the client and pass the position as parameter on the [Cmd] methods to the server.

*Since you say the object already has a NetworkTransform, you wouldn't need to transmit the updated position to the server because NetworkTransform already does it for you. So calling CmdTrailUpdate from the client would not be neccesarry.
But: After spawning the object you have to tell the client who is calling CmdSpawn, which is his local currentTrail which's position he has to update. I would do this by simply passing the calling clients gameObject also to the CmdSpawn method and on the server call a [ClientRpc] method to set this client's currentTrail object.
(I'm assuming here, that the script you posted is attached diectly to the Player objects. If that is not the case, instead of the lines with this.gameObject you have to get the player's gameObject in a nother way.)
void FixedUpdate() {
    if (!isLocalPlayer) return;

    if (Input.GetMouseButtonDown(0)) {
        // Do the raycast and calculation on the client
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        float rayDistance;
        if (objPlane.Raycast(mRay, out rayDistance)) {
            startPos = mRay.GetPoint(rayDistance);

            // pass the calling Players gameObject and the
            // position as parameter to the server
            CmdSpawn(this.gameObject, startPos);
        }
    } else if (Input.GetMouseButton(0)) {
        // Do the raycast and calculation on the client
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        float rayDistance;
        if (objPlane.Raycast(mRay, out rayDistance)) {
            // only update your local object on the client
            // since they have NetworkTransform attached
            // it will be updated on the server (and other clients) anyway
            currentTrail.transform.position = mRay.GetPoint(rayDistance);
        }
    }
}

[Command]
private void CmdSpawn(GameObject callingClient, Vector3 spawnPosition){
    // Note that this only sets currentTrail on the server
    currentTrail = (GameObject)Instantiate(trail, spawnPosition, Quaternion.identity);
    NetworkServer.Spawn(currentTrail);

    // set currentTrail in the calling Client
    RpcSetCurrentTrail(callingClient, currentTrail);
}

// ClientRpc is somehow the opposite of Command
// It is invoked from the server but only executed on ALL clients
// so we have to make sure that it is only executed on the client
// who originally called the CmdSpawn method
[ClientRpc]
private void RpcSetCurrentTrail(GameObject client, GameObject trail){
    // do nothing if this client is not the one who called the spawn method
    if(this.gameObject != client) return;

    // also do nothing if the calling client himself is the server
    // -> he is the host
    if(isServer) return;

    // set currentTrail on the client
    currentTrail = trail;
}


text:
Q: How do I do an `if user_signed_in?` check on an action that triggers a JS toggle? I use Devise, and so in my views whenever I want to hide something from a non-signed-in user, I just  add a quick:
<% if user_signed_in? %> around the portion of the view and voila.
The issue is now, I have a button that triggers a toggle JS action on the page.
This is my HTML:

     <button class="btn btn-default btn-lg btn-primary"> Submit News</button>

This is the JS:
var ready;
ready = function() {

    // This is the Sidebar toggle functionality
    var toggleSidebar = $("#togglesidebar");
    var primary = $("#primary");
    var secondary = $("#secondary");

    toggleSidebar.on("click", function(){

        if(primary.hasClass("col-sm-9")){
            primary.removeClass("col-sm-9");
            primary.addClass("col-sm-12");
            secondary.css('display', 'none');
        }
        else {
            primary.removeClass("col-sm-12");
            primary.addClass("col-sm-9");
            secondary.css('display', 'inline-block');
        }
    });
};

$(document).ready(ready);
$(document).on('page:load', ready);

What I want to happen is, if the current_user is not logged in, they should get redirected to a 'please login' modal before they that Sidebar is toggled.
Then upon successful login, it should then redirect them back to that same page with the Sidebar toggled.
How do I do this?

A: You could set a js variable using erb like this:
var user_signed_in = <%= user_signed_in? %>

and then use that variable inside of your js to determine if you should display the modal, etc.

A: You can mix JS and Rails, directly in view, like this :

redpajama_set_name: RedPajamaStackExchange


text:
Q: background image radio button Would it be possible give each radio button its own background image using jQuery? What I mean is:

<form id="tiepspiel" name="tiepspiel" action="#" method="POST">

        <?php
        $count = 5;
        $i = 1;
        while ($i <= $count) {
            echo '

            <input type="radio" name="selected__'.$i.'" value="stein

            <input type="radio" name="selected_'.$i.'" value="schere">

            <input type="radio" name="selected_'.$i.'" value="papier">

';
            $i++;
        }
        ?>

        <button>Submit</button>

        </form>

and I'm trying to add CSS to each class. For example:
.papier {
    background-image: url("../images/papier_blue.png");
    width: 82px;
    height: 82px;
    cursor: pointer;
    margin-right: 50px;
}

A: Background images don't work so well with the radio buttons themselves. What you can do is wrap them each in a  as follows:

        <input type="radio" name="stein" value="stein">

        <input type="radio" name="schere" value="schere">

        <input type="radio" name="papier" value="papier">

Then, your CSS should work as-is.

A: You put the background styles on the wrong class. Put them in your .selectable class definition.

A: I guess you need a kind of "fake radio button". There are many ways to do this, including jquery, or you can easly do it with css.
As somebody told, you have to wrap the radio button with a span or label. By default they are not 'block' elements, like 'div', so you can't obtain your result unless you will not attribute this ( display:block; or display:inline-block; ). Also don't forget to set the width and the height ( i mean to span/label ) and also set opacity 0 to the radio button.
I recommend to you to have a look at http://ajaxian.com/archives/custom-css-inputs or you can also have a look inside http://www.iamntz.com/625/frontend-developer/formulare-custom-checkbox-radio-v-2/ ( nevermind if it is in romanian, you only check demo and have a look to the code )
There is no rocket-science, you only have to take care of some stuff.


text:
Q: SSIS ForEachLoop editor for Excel files with any extension Task: I'm trying to iterate through excel files using foreachloop editor container.
I was successful until i had different extensions meaning it's works as long as file extension is xls or xlsx but not both together.
Problem: I get errors when i try to iterate files with extensions xls and xlsx. Cannot acquire connection to connectionmanager.
For instance: I have abc.xls and agh.xlsx in a folder and i have trouble iterating thru files using Foreachloop editor.I think i understand & know why it's happening but can i write a script to do it or how to complete this task successfully.
Any ideas..

A: You will need to add 2 For Each Loop containers to iterate through files. the 1st FLC will process only .xls (or .xlsx) and the second FLC would process only .xlsx (or .xls). Other than that, I dont think writing a script would be of any help. But I could be wrong.

A: Presuming all xls file have the same format and all xlsx files have the same format...
What you also could do is using one FOREACH loop to loop through all Excel files... then add a dummy task (empty Script Task or Sequence Container) and connect it to two Data Flow Tasks. One for XLS and one for XLSX. Then add expressions on the lines between the dummy tasks and data flow tasks where you check the extensions. Something like:
LOWER(RIGHT(@[User::Filepath],4))==".xls"
LOWER(RIGHT(@[User::Filepath],4))=="xlsx"


text:
Q: ¿por qué me sigue apareciendo Cannot read property 'getRange' of undefined? muy buenos días fíjense que anduve programando en google appscript en una hoja de sheets pero me aparece este error

13:03:56  Error
TypeError: Cannot read property 'getRange' of undefined
generatePDFIndividualy  @ Código.gs:26

y pues me puse a investigar en Internet pero parece que en mi caso no hay nada en concreto... aun.
este es mi codigo:
var ColSubDate = 1;
  var ColName = 2;
  var ColAge = 3;
  var ColCivilStatus = 4
  var ColAddres = 5;
  var ColNumExt = 6;
  var ColNumInt = 7;
  var ColSubrb = 8;
  var ColPC = 9;
  var ColCity = 10;
  var ColPR = 11;
  var ColRFC = 12;
  var ColBenefactor = 13;
  var ColMail = 14;
  var XclID = "1eqBrrCztfHZEWwcqbaP90zVfhHVNAZASG-apEFbSWCw"; //new
  var ExlID = "14fTKWX_QukKQERTSWY4E_Lpku5VAAXOo"; //folder
  var TemplateID = "1gMiauWEjUc8PvNBHEkRqold8lF5nJO72W1T343XFyAQ";
  var PdfID = "1OMq5DMTuLF9OKHtcGObdcyK9j5gOJNuK";
  var DocsID = "1PT1XSpvrxFQc4TJzaTD09nvfuL9h0GWs";
  var Urls = 0;

function generatePDFIndividualy(Client){
  var ActiveRow = SpreadsheetApp.getActiveRange().getLastRow();
  var Client = {}
    Client.Date = Sheet.getRange(ActiveRow , ColSubDate).getValue;
    Client.Name = Sheet.getRange(ActiveRow , ColName).getValue();
    Client.Age = Sheet.getRange(ActiveRow , ColAge).getValue();
    Client.CivilStatus = Sheet.getRange(ActiveRow , ColCivilStatus).getValue();
    Client.Addres = Sheet.getRange(ActiveRow , ColAddres).getValue();
    Client.NumExt = Sheet.getRange(ActiveRow , ColNumExt).getValue();
    Client.NumInt = Sheet.getRange(ActiveRow , ColNumInt).getValue();
    Client.Subrb = Sheet.getRange(ActiveRow , ColSubrb).getValue();
    Client.PC = Sheet.getRange(ActiveRow , ColPC).getValue();
    Client.City = Sheet.getRange(ActiveRow , ColCity).getValue();
    Client.PR = Sheet.getRange(ActiveRow , ColPR).getValue();
    Client.RFC = Sheet.getRange(ActiveRow , ColRFC).getValue();
    Client.Benefactor = Sheet.getRange(ActiveRow , ColBenefactor).getValue();
    Client.Mail = Sheet.getRange(ActiveRow , ColMail).getValue();

  var TemplateID = "1gMiauWEjUc8PvNBHEkRqold8lF5nJO72W1T343XFyAQ";
  var PdfID = "1OMq5DMTuLF9OKHtcGObdcyK9j5gOJNuK";
  var DocsID = "1PT1XSpvrxFQc4TJzaTD09nvfuL9h0GWs";

  var TemplateFile = DriveApp.getFileById(TemplateID);
  var PDFFile = DriveApp.getFolderById(PdfID);
  var DocsFile = DriveApp.getFolderById(DocsID);
  var Sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("formulario");

  var TemplateFileCopy = TemplateFile.makeCopy(DocsFile);
  var CopyID =TemplateFileCopy.getId();
  var Namedoc = "CIT de "+ Client.Name + " " + Client.Date;
  TemplateFileCopy.setName(Namedoc);
  var Docs = DocumentApp.openById(CopyID);
  Docs.setName(Namedoc);

  //Remplaze variables
  Docs.getBody().replaceText("{{Nombre}}", Client.Name);
  Docs.getBody().replaceText("{{Edad}}", Client.Age);
  Docs.getBody().replaceText("{{Estado Civil}}", Client.CivilStatus);
  Docs.getBody().replaceText("{{Domicilio}}", Client.Addres);
  Docs.getBody().replaceText("{{Numero Ext}}", Client.NumExt);
  Docs.getBody().replaceText("{{Numero Int}}", Client.NumInt);
  Docs.getBody().replaceText("{{Colonia}}", Client.Subrb);
  Docs.getBody().replaceText("{{CP}}", Client.PC);
  Docs.getBody().replaceText("{{Ciudad}}", Client.City);
  Docs.getBody().replaceText("{{Curp}}", Client.PR);
  Docs.getBody().replaceText("{{RFC}}", Client.RFC);
  Docs.getBody().replaceText("{{Beneficiario}}", Client.Benefactor);

  Docs.saveAndClose();
      var source = SpreadsheetApp.getActiveSpreadsheet();
    var paper = source.getSheets()[0];

    var destination = SpreadsheetApp.openById(XclID);
    paper.copyTo(destination);

  const Pdfblob =Docs.getAs(MimeType.PDF);
  var PDFcreated = PDFFile.createFile(Pdfblob);
  PDFcreated.addViewer(Client.Mail);
  var Urls ={}
    Urls.PDFurl = PDFcreated.getUrl();
    Urls.Docurl = Docs.getUrl();
    //Urls = generatePDF(Client);
    Client.PDF = Urls.PDFurl;
    //
    var Message = "este es solo una prueba de CIT, descarga aqui el pdf: " + Client.PDF;
    MailSender.sendEmail(Client.Mail, "documento prueba", Message);
    //
}

como pueden ver dice que es en la linea 26 sin embargo al hacer debugging aparece que todos los que tienen la variable "Cliente" también aparecen como indefinidos o "undefined" y pues creo que puede ser como esta programado :/
sin embargo no encuentro donde puede estar el error o si alguien sabe del tema que me lo explique ya que no veo por que me sigue apareciendo el error :(((

A: El error ocurre porque se llama Sheet antes de que esta variable haya sido declarada. Intenta mover
var Sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("formulario");

antes de la línea indicada en el mensaje de error.
Notas:

*

*El código deberá estar en un proyecto contenido por una hoja de cálculo que contenga una hoja llamada formulario.

*El código tiene otros errores, por ejemplo, en la línea
 Client.Date = Sheet.getRange(ActiveRow , ColSubDate).getValue;

faltan los paréntesis de getValue.


text:
Q: Debug C# error. Access element within an object Following on from a previous question, I have the following code:
           var results =
            from result in xml.Descendants(ns + "GetMetalQuoteResult")
            select new
            {
                Type = result.Element(ns + "Type").Value,
                Currency = result.Element(ns + "Currency").Value,
                Date = result.Element(ns + "Date").Value,
                Time = result.Element(ns + "Time").Value,
                Rate = (decimal)result.Element(ns + "Rate"),
                Bid = (decimal)result.Element(ns + "Bid"),
                BidTime = result.Element(ns + "BidTime").Value,
                ExpTime = result.Element(ns + "ExpTime").Value,
                DisplayTime = result.Element(ns + "DisplayTime").Value,
                DisplayDate = result.Element(ns + "DisplayDate").Value,
                Ask = (decimal)result.Element(ns + "Ask"),
                AskTime = result.Element(ns + "AskTime").Value,
            };

How do I access these elements?
e.g. If I want to gain access to the value of element 'Ask', why can't I just use the following code.
System.Diagnostics.WriteLine(results.Ask);

Am I doing something stupidly wrong because I am getting the following error
Error   2   'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'Ask' and no extension method 'Ask' accepting a first argument of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' could be found (are you missing a using directive or an assembly reference?)

A: I was wrapped up in the context for a moment there, but your issue lies in that results is a collection, so you can't do that - you need to do it on one item of the collection:
System.Diagnostics.WriteLine(results.First().Ask);

I could have picked a number of other extension methods to do this other than First and would do it differently anyway, that's an example. You should first check whether or not your collection contains any items and retrieve accordingly.
Alternatively, and for the sake of demonstration, you could just loop through the results:
foreach (var result in results) {
  System.Diagnostics.WriteLine(result.Ask);
}


text:
Q: Discord.py Button, Select, View error import I want to create a command that generates the select menu but it generates an import error
import discord
import datetime
from discord.ui import Select, View
from discord.ext import commands

client = commands.Bot(command_prefix = '.', help_command=None)

@client.command()
async def hello(ctx):
    select = Select(options=[
        discord.SelectOption(label="Hello", emoji= "✌", description="Hello")
        discord.SelectOption(label="Hello1", emoji= "", description="Hello2")
        ])
    view = View()
    view.add_item(select)
    await ctx.send("Select", view= view)

error:
Traceback (most recent call last):
  File "c:\Users\bicco\Desktop\Coding\leiaraiel_bot\main.py", line 4, in <module>
    from discord.ui import Select, View
ImportError: cannot import name 'Select' from 'discord.ui' (unknown location)

A: *

*Update to discord 2.0 using:

pip install discord==2.0

If you are using replit to host your code it will show you an error as replit is still not compatible with discord 2.0. Instead, you can go to the shell terminal of replit and do the following:
pip uninstall discord.py # or pip uninstall discord

*

*Wait for some time until replit asks for confirmation and type y to confirm the removal.

*Then install it like this:

pip install git+https://github.com/Rapptz/discord.py

Hope it helps.


text:
Q: Indentify numbers on screen What do you recomend to recognize a number on screen, and stores it, in real time.
  I'm working with Java, I'm new on this. Thank you.

A: If by 'recognize a number on a screen' you mean to recognize a number that a user typed, I'd use JOptionPane.showInputDialog. It looks like this:
int userInput = JOptionPane.showInputDialog("Enter a number");
int number = userInput;

This stores the number that the user entered in the variable number.
I hope I answered your question


text:
Q: static media player object access for resource file in entire application hello  i am new in android development ,in my application i created one class Music to access media Player each and every activity.i have around 50 activities.
MY Music class Have static media Player object.
each activity have next button and forward button.on click of next button there is one static counter that will increase as per the click.each counter value have different song.
so i want to stop first counter value song  and start next one.on forward same must be done.
anyone have idea , how to implement static method which stop first song and start next one.
here is my code.
public class Music extends Application implements OnCompletionListener    {

   public static   MediaPlayer mp=null;

public static void playGeneric(int name, final ImageButton button,final ImageButton pervious,Context context) {
        button.setEnabled(false);
        button.setClickable(false);
        pervious.setEnabled(false);
        pervious.setClickable(false);
            try{

                mp = MediaPlayer.create(context, name); // used to re-initialze the mediaplayer for reuse since resources were released.

                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer arg0) {

                            mp.start();

                        }

                    });

              mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        mp.release();
                        System.out.println("Object released");
                        button.setEnabled(true);
                        button.setClickable(true);
                        pervious.setEnabled(true);
                        pervious.setClickable(true);
                    }
                });

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            e.getMessage();
        } catch (NullPointerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            e.getMessage();
        }

    }

 public static void stopplaying() {
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }

}
}

on activity on next button click static counter increment
    if (v == next) {
       counter++

 if (counter == 1) {
            Log.i("counter", "value :: " + counter);
            Music.playGeneric(audio, next,pervious, getBaseContext());

        }

     if (counter == 2) {
                   Music.playGeneric(audio, next,pervious, getBaseContext());
}

    ....................................
          if(counter==25){}
    }

like this way. now i want to stop music , how to stop it? please help
  me.

A: @Sydroid you need to make two static method 1 next and second previous and call this when you click next and previous, In next and previous method call your stopplaying() method and then increment your counter and call palygeneric().


text:
Q: Fill fields of a form on Django 1.5.7 I'm trying to do fill a form on Django==1.5.7, atm I have these codes:
models.py:
class UsuarioFidetel(models.Model):
"""
Modelo de usuario fidetel
"""

usuario = models.CharField(max_length=30)
id_usuario = models.IntegerField()
nombre = models.CharField(max_length=255, null=True)
apellido = models.CharField(max_length=255, null=True)
tipo_cedula = models.CharField(max_length=1, null=True)
cedula = models.CharField(max_length=9, null=True)
fecha_nacimiento = models.DateField(null=True, blank=True)
sexo = models.CharField(max_length=1, null=True)
correo = models.EmailField(max_length=254, null=True)
estado_civil = models.CharField(max_length=1, null=True)

def __unicode__(self):
    return unicode(self.id_usuario)

views.py:
def crear_usuario_fidetel(request):
"""
Muestra el formulario que permite ingresar los datos del usuario de
fidetel cuando aún no han sido creados

@return: El formulario que permite ingresar los datos del usuario de
    fidetel.
"""

usuario_fidetel = request.session['usuario_fidetel']
if(usuario_fidetel.id_usuario):
    usuario_fidetel = UsuarioFidetel.objects.get(id_usuario=usuario_fidetel.id_usuario)
    #usuario_fidetel = UsuarioFidetel.objects.get(id_usuario=usuario_fidetel['id'])
    return render_to_response('fidetel/usuario_fidetel.html',
                              { },
                              context_instance=RequestContext(request))

usuario_fidetel_form = FormularioUsuarioFidetel(instance=usuario_fidetel)

return render_to_response('fidetel/usuario_fidetel.html',
                          { 'form': usuario_fidetel_form },
                          context_instance=RequestContext(request))

@autenticacion_fidetel_requerida
@permiso_requerido([PERMISOS_FONDO['CREAR_USUARIO_FIDETEL'],
                PERMISOS_FONDO['MODIFICAR_USUARIO_FIDETEL']])
@transaction.commit_on_success

Now, my question is, how can I have these model fields 'empty' on my template view, for me to fill them with data (ie add a user to the db).
At the moment, when I access usuario_fidetel.html it shows me the labels, but fields are not activated somehow, I just see labels without the possibility to fill them and save data.
Refer to this image:

Any ideas?
It's the Create phase of a CRUD, idk if I'm explaining myself well, if you need more code let me know.
Thanks in advance!
EDIT
My template usuario_fidetel.html code:
{% extends "fidetel/base.html" %}
{% block titulo %}::: AUTANA ::: Fidetel{% endblock %}

{% block panel_operaciones_crud %}

{% endblock %}

{% block titulo_seccion %}{% endblock %}

{% block area_trabajo %}

    {% if mensaje_error %}

{{ mensaje_error }}

    {% endif %}
    {% if form.errors %}

            No se pudieron guardar los datos del usuario debido a los siguientes errores:

                {% for field in form %}
                    {% if field.errors %}
{{ field.errors|striptags }}
{% endif %}
                {% endfor %}

    {% endif %}
    <form id="form_usuario_fidetel" action="{% url 'guardar_usuario_fidetel' %}" method="post">
        {% csrf_token %}

*Nombre:

                    {{ form.nombre }}

*Apellido:

                    {{ form.apellido }}

*Cédula:

                {{ form.tipo_cedula }}
                {{ form.cedula }}

*Correo Electrónico:

                    {{ form.correo }}

*Fecha de Nacimiento:

                    {{ form.fecha_nacimiento }}

*Sexo:

                    {{ form.sexo }}

*Estado Civil:

                    {{ form.estado_civil }}

                (*) Datos obligatorios

    </form>

{% endblock %}


text:
Q: How to solve Undefined Index in PHP This might be a beginner question for some but I can't get through with this: See, what I have is a simple text box and submit button. The text box is required to be inputted by numbers (it should be the user's salary). When ever I load the php file in the any browser I got this error (see image below). What's in the line 35 is the code?
$a = $_POST['salary'];

I don't know what's wrong with that...

<form method="POST">

Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event)">

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

<?php

$a = $_POST['salary'];

?>

<?php
switch($a) {

    case ($a==""): echo "Input first your Compensation for the period!";
    break;

    case ($a < 1000 ): echo "Your Compensation is too low. You are not required to contribute for the period.";
    break;

    case ($a >=1000 && $a <=1249.99): echo "Your ER is 80.7 and Your EE is 33.30";
    break;

    case ($a >=1250 && $a <=1749.99): echo "Your ER is 116 and Your EE is 50.00";
    break;

    case ($a >=1750 && $a <=2249.99): echo "Your ER is 151.3 and Your EE is 66.70";
    break;

    case ($a >=2250 && $a <=2749.99): echo "Your ER is 186.7 and Your EE is 83.3";
    break;

    case ($a >=2750 && $a <=3249.99): echo "Your ER is 222 and Your EE is 100";
    break;

    case ($a >=3250 && $a <=3749.99): echo "Your ER is 257.3 and Your EE is 116.7";
    break;

    case ($a >=3750 && $a <=4249.99): echo "Your ER is 292.7 and Your EE is 133.3";
    break;

    case ($a >=4250 && $a <=4749.99): echo "Your ER is 328 and Your EE is 150";
    break;

    case ($a >=4750 && $a <=5249.99): echo "Your ER is 363.3 and Your EE is 166.7";
    break;

    case ($a >=5250 && $a <=5749.99): echo "Your ER is 398.7 and Your EE is 183.3";
    break;

    case ($a >=5750 && $a <=6249.99): echo "Your ER is 434 and Your EE is 200";
    break;

    case ($a >=6250 && $a <=6749.99): echo "Your ER is 469.3 and Your EE is 216.7";
    break;

    case ($a >=6750 && $a <=7249.99): echo "Your ER is 504.7 and Your EE is 233.3 ". "with a total SSS Contribution of 738.00" ;
    break;

    case ($a >=7250 && $a <=7749.99): echo "Your ER is 540 and Your EE is 250";
    break;

    case ($a >=7750 && $a <=8249.99): echo "Your ER is 575.3 and Your EE is 266.7";
    break;

    case ($a >=8250 && $a <=8749.99): echo "Your ER is 610.7 and Your EE is 283.3";
    break;

    case ($a >=8750 && $a <=9249.99): echo "Your ER is 646 and Your EE is 300";
    break;

    case ($a >=9250 && $a <=9749.99): echo "Your ER is 681.3 and Your EE is 316.7";
    break;

    case ($a >=9750 && $a <=10249.99): echo "Your ER is 716.7 and Your EE is 333.3";
    break;

    case ($a >=1025 && $a <=10749.99): echo "Your ER is 752 and Your EE is 350";
    break;

    case ($a >=1075 && $a <=11249.99): echo "Your ER is 787.3 and Your EE is 366.7";
    break;

    case ($a >=1125 && $a <=11749.99): echo "Your ER is 822.7 and Your EE is 383.3";
    break;

    case ($a >=1175 && $a <=12249.99): echo "Your ER is 858 and Your EE is 400";
    break;

    case ($a >=1225 && $a <=12749.99): echo "Your ER is 893.3 and Your EE is 416.7";
    break;

    case ($a >=1275 && $a <=13249.99): echo "Your ER is 928.7 and Your EE is 433.3";
    break;

    case ($a >=1325 && $a <=13749.99): echo "Your ER is 964 and Your EE is 450";
    break;

    case ($a >=1375 && $a <=14249.99): echo "Your ER is 999.3 and Your EE is 466.7";
    break;

    case ($a >=1425 && $a <=14749.99): echo "Your ER is 1034.7 and Your EE is 483.3";
    break;

    case ($a >=1475 && $a <=30000): echo "Your ER is 1090 and Your EE is 500";
    break;

    default:
    echo " Your ER is 1090 and Your EE is 500. Your Salary for the Period reached the Maximum Range of Compensation. ";
    break;

}
?>

A: A common idiom is to do this
 $a = isset($_POST['salary']) ?  $_POST['salary'] : '';

This will set $a to the posted value if set, and use a default if not.

A: You need to check of the index is set. For example, before assigning your variable to $a, use:
$a = (isset($_POST['salary'])) ? $_POST['salary'] : '';

This uses a ternary operator (similar to an if-else block) but essentially, if $_POST['salary'] is indeed set, it will use that value, otherwise it falls back to a default of an empty string.

A: you should include your calculation inside a condition which does the following
$a = "";
if (isset($_POST['salary'])) {
    $a = $_POST['salary'];
}

A: You should use isset() method before you actually use your $_POST['salary'] to check if it is set.

A: First check if $_POST has elements
if($_POST){
   $a = $_POST["salary"];
 }


text:
Q: Hi i am struggling with a formula I have an excel spreadsheet with the following formula in column "L":
=IF($A4="","",IF($J4>=$K4,"",IF($J4="","",if($M4<>"Released","",$J4+90)))
I am trying to populate Column "L" with a date 90 days from column "J" but only if either Column M=Released or if Column K is greater than J on any other occasion Column "L" must remain blank
I can get the formula to work if I remove the IF($J4>=$K4,"", element and just have
=IF($A4=""," ",IF($M4<>"Released","",IF($J4="","",$J4+90)))
or just with this element
=IF($A4="","",IF($J4>=$K4,"",IF($J4="","",$J4+90)))
but when I try to add IF($J4>=$K4,""** and **IF($M4<>"Released","" together I can't get it to work
Appreciate any advice

A: I test ok with your formula,
=IF($A4="","",IF($J4>=$K4,"",IF($J4="","",if($M4<>"Released","",$J4+90))))

your formula do less a ")" at the last,
However, I believe that you should be prompted by the Excel to correct the formula.
The Excel should correct the mistake for you automatically.

A: Your statement and formula are in disagreement.
=IF($A4="","",IF(OR($J4>=$K4,$M4<>"Released"),$J4+90,""))
Edit:
Based on OP's input
=IF($A4="","",IF($M4="Released",$J4+90,IF(AND($M4="Terminated",$K4>$J4),$J4+90,"")))


text:
Q: Django-Filter returns the request object I was trying to dynamically filter the queryset in Django using Django-filters library in DRF but the filters send the response exactly as the same to request ie if i choose mode = transfer the response is
{
  "data": {
    "mode": "transfer"
  }
}

the filterset_class is defined in the views and queryset is passed on to it along with the request type.
views.py
from .filters import DataFilter
def get(self, request):

    query_set = ModelName.objects.all()
    queryset_filter = DataFilter(
        request.GET, queryset=query_set)
    return Response({"data": queryset_filter.data}, status=status.HTTP_200_OK)

filters.py
from django_filters import rest_framework as filters
from .models import ModelName
from common.models import MODE_CHOICES

class DataFilter(filters.FilterSet):

    currency = filters.ModelMultipleChoiceFilter(lookup_expr='iexact')
    coin_type = filters.ModelMultipleChoiceFilter(lookup_expr='iexact')
    mode = filters.ModelChoiceFilter(
        lookup_expr='iexact', choices=MODE_CHOICES)
    max_amount = filters.NumberFilter(
        field_name='price', lookup_expr='gt')
    min_amount = filters.NumberFilter(
        field_name='amount', lookup_expr='lt')

    class Meta:
        model = ModelName
        fields = ('currency', 'coin_type', 'mode',
                  'max_amount', 'min_amount')

The django-filters documentation suggests django-filter backend can be used by default by adding it to the DEFAULT_FILTER_BACKENDS.
Is there some configuration that i am missing or something

A: The filterset.data attribute is literally the data/query params you provide to DataFilter on initialization. In this case, you are providing request.GET as the data.
What you want to access is the filterset's .qs property, which is the filtered results. e.g.,
def get(self, request):
    queryset_filter = DataFilter(request.GET, queryset=ModelName.objects.all())
    return Response({"data": queryset_filter.qs}, status=status.HTTP_200_OK)

Note that you will likely need to serialize the filtered queryset.


text:
Q: python Unable to get return values from async function using HTTP requests I'm trying to rewrite my flask application to FastAPI which uses uvloop as the base.
When I execute code without the routes, I see no issue and executes as expected. But throws me error after I add the routes and hit a request using Postman.
> INFO: ('172.17.0.1', 42352) - "GET /api/v1/getpass HTTP/1.1" 500
> ERROR: Exception in ASGI application Traceback (most recent call
> last):   File
> "/usr/local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py",
> line 375, in run_asgi
>     result = await app(self.scope, self.receive, self.send)   File "/usr/local/lib/python3.6/site-packages/starlette/applications.py",
> line 133, in __call__
>     await self.error_middleware(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/middleware/errors.py",
> line 177, in __call__
>     raise exc from None   File "/usr/local/lib/python3.6/site-packages/starlette/middleware/errors.py",
> line 155, in __call__
>     await self.app(scope, receive, _send)   File "/usr/local/lib/python3.6/site-packages/starlette/exceptions.py", line
> 73, in __call__
>     raise exc from None   File "/usr/local/lib/python3.6/site-packages/starlette/exceptions.py", line
> 62, in __call__
>     await self.app(scope, receive, sender)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 590, in __call__
>     await route(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 208, in __call__
>     await self.app(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 41, in app
>     response = await func(request)   File "/usr/local/lib/python3.6/site-packages/fastapi/routing.py", line 111,
> in app
>     raw_response = await dependant.call(**values)   File "./iowait.py", line 51, in get_pvt
>     print(kpair) UnboundLocalError: local variable 'kpair' referenced before assignment

My Code:
import random
import asyncio as aio

from fastapi import FastAPI
from pydantic import BaseModel

get_id = '/api/v1/getid'
get_pass = '/api/v1/getpass'
app = FastAPI()
key_pass_list = [
    {
        'uid' : 'uid1',
        'pass' : 'pass1'
    },
    {
        'uid' : 'uid2',
        'pass' : 'pass2'
    },
    {
        'uid' : 'uid3',
        'pass' : 'pass3'
    },
]
id_list = [_['uid'] for _ in key_pass_list]

class KeyDoc(BaseModel):
    uid : str

async def key_pass(uid):
    for keypair in key_pass_list:
        if keypair['uid'] == uid:
            return keypair
    return {uid: 'Key not Found'}

@app.get(get_pass)
async def get_pvt(key_doc: KeyDoc):
    uid = key_doc.uid
    print('uid :' + uid)

    try:
        myloop = aio.get_event_loop()
        kpair = myloop.run_until_complete(aio.wait([key_pass(uid)]))
        await kpair
    except Exception as err:
        print(err)

    print(kpair)
    return None

@app.get(get_id)
async def get_pub():
    return random.choice(id_list)

@app.get("/")
async def root():
    return {"message": "Test-AIO"}

NOTE
get_id and / route works anytime because there is no logic, it fails with the get_pass requests.
Any help or pointers on this is very much appreciated.
Thank you

A: Two things here. Firstly, using aio.get_event_loop() is throwing an exception This event loop is already running before await kpair which throws the UnboundLocalError you're seeing when trying to print a non-existent variable. You can see this behavior by adding kpair = None under your first print statement in get_pvt. Below is how you would structure this using asyncio.wait.
@app.get(get_pass)
async def get_pvt(key_doc: KeyDoc):
    uid = key_doc.uid
    print('uid :' + uid)
    done = set()
    try:
        done, pending = await aio.wait([key_pass(uid)])
    except Exception as err:
        print(err)

    if done:
        for task in done:
            print(task.result())
    return None


text:
Q: SDL2: Slow window clean and update I found out that my program - which only draw two pictures on the screen  - runs at 200FPS. 200FPS is really low number at this point of development! It does not matter if I remove all textures and other data.
The slow part of code are SDL_RenderPresent and SDL_RenderClear. Without them, the program runs at about 300K FPS. Could you tell me where could be the problem?
Window and Renderer
_window = SDL_CreateWindow( "Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0 );

if ( _window == NULL ) {
    std::cout << "CreateWindow problem: " << SDL_GetError() << std::endl;
}

_renderer = SDL_CreateRenderer( _window, -1, SDL_RENDERER_ACCELERATED );

if ( _renderer == NULL ) {
    std::cout << "CreateRenderer problem: " << SDL_GetError() << std::endl;
}

Acording to SDL_RendererInfo only two flags are used - SDL_RENDERER_ACCELERATED and SDL_RENDERER_TARGETTEXTURE.


text:
Q: TAR Files: Move Files From Subdirectories to Main Directory I've been trying to use this code:
find documents -maxdepth 1 -type f -print0 | xargs -0 tar cvf documents.tar.gz

to create a backup of the directory documents.
The directory has the structure:

And I want to archive them into a single directory documents/:

But I fail to do so. How can I do this? Thank you

A: You could hardlink them on a different directory and than tar
# find all files in directory named directory
find directory -type f | \
while read f;
do
    f2=`echo "$f"|sed -e 's/\//:/g'`  # replace / with :
    ln "$f" "directory2/$f2"  # create hardlinks in directory2/
done

This will create the following links
directory/file1 => directory2/directory:file1
directory/file2 => directory2/directory:file2
directory/folder1/file3 => directory2/directory:folder1:file3
directory/folder1/file4 => directory2/directory:folder1:file4
directory/folder2/file5 => directory2/directory:folder2:file5
directory/folder3/folder4/file6 => directory2/directory:folder3:folder4:file6
directory/folder3/folder4/file7 => directory2/directory:folder3:folder4:file7

A: I guess the way to do this is to create a new directory just as backup source and fill it with hardlinks. I hope the whole directory tree you want to backup is on the same volume.
> pwd
/path/to/documents
> cd /path/to/
> mkdir tar-documents
> mkdir tar-documents/documents
> ln /path/to/documents/file1
> ln /path/to/documents/file2
> ln /path/to/documents/folder1/file3 folder1:file3
[...]

If the number of files is high then this should be done by a script.
Afterwards you run tar on this directory:
> cd /path/to/tar-documents
> tar cvzf /backup/path/documents.tar.gz documents

At the end it may be useful to delete the tar directory.

A: You can try this.
Find all *tar files in current folder and copy to MainDirectory folder or wherever do you want.
find . -iname "*tar*" -exec cp {} ~/MainDirectory/ \;

A: Firstly, if you want to archive a directory, having the identical file structure in the archive is the best practice for taking that snapshot. What you are asking for is the renaming of your files to include its parent directories succeeded by colons followed by the filename. However strange to me this is out of context, I did manage to get pretty close using the --transform option:
 --transform=EXPRESSION, --xform=EXPRESSION
                         use sed replace EXPRESSION to transform file

An example of this is outlined in this stackexchange answer (Though be aware that it is not proper sed syntax). Using --transform your command would be this:
tar czvf documents.tar.gz --transform 's/\//:/g' documents

Unfortunately, this did not have the desired effect, as it keeps your subdirectories in the archive but they are empty, and the files are at the root of the archive, not in the first parent directory.
I thought I had a solution for you using -C, --directory option, but it would not be very dynamic, nor would it accomodate for maintaining the directory names of files in the new file name.
The solution I did find is a hybrid of what you have and the use of the transform command:
find documents -type f -print0 | xargs -0 tar czvf test.tar.gz --no-recursion --transform 's/\//:/g' --transform 's:\::/:1' documents/

Also, in your question you name your file with the .gz extension but it was lacking the -z, --gzip option.
Hope this helps,
Alex


text:
Q: How to deinstall top panel or allow programs/windows to be ontop of that panel As the title says.
The problem is my screen size is 1080p, and i need a program to run in 1080p in window mode, but the top panel is forcing the programwindow out of the screen how to fix that. or deinstall the top panel.
Thanks in Advance!

A: I installed now the gnome-shell, and its a pretty good solution, now I only got the panel on the left screen, and on the right (dual monitor) is now no panel, also every window has it's own toolbar, idk know how it's actually called.
sudo apt-get install gnome-shell

but yet not the solution I expected.

A: Many programs can be set to run fullscreen by pressing F11.
You can use ccsm (compiz config settings manager) to temporarily remove the top & side bars.
Install ccsm & put shortcuts to the program and ccsm on your desktop, then use ccsm to disable the unity desktop plugin and run the program fullscreen in windowed mode.
Use ccsm to re-enable the unity plugin when you are finished.
Not the perfect solution, but a workable workaround until you get a better answer.


text:
Q: clickevent in javascript what is difference between onclick and onclientclick events?

A: The difference is that onclientclick does not exist in Javascript.
It's an ASP.net extension. As shown in the example in MSDN's Button.OnClientClick Property page, onclientclick will call client-side script, while onclick will call the server-side script.


text:
Q: Schauder fixed point extended The Schauder fixed point theorem states that if $X$ is a Banach space, $K\subset X$ is a convex, bounded and closed subset and $T:K\rightarrow K$ is compact, then $T$ has, at least, one fixed point in $K$. I want to know if this statement still holds true when the subset $K$ is replaced by another subset $D$ that is homeomorphism to $K$.
Roughly speaking, if $h:K\rightarrow D$ is an homeomorphism, then $h^{-1}Th:K\rightarrow K$ and I am able to apply the Schauder fixed point theorem if $h^{-1}Th$ is compact.
Is there any result that guarantee that the compactness of operators is preserved by homeomorphism or something similar?

A: If $T(D)$ is a compact subset of $D$, then $Th(K)=T(D)$ is a compact subset of $D$, whence $h^{-1}Th(D)$ is a compact subset of $K$.  Thus there is some $x_0\in K$ such that $h^{-1}Th(x_0)=x_0$.  Put $y_0=h(x_0)$.  Then $Ty_0=hh^{-1}Th(x_0)=h(x_0)=y_0$, so $T$ has a fixed point.


text:
Q: Mapping sockjs-client in systemjs I'm using typescript and angular2 and I want to use SockJS in my project. I run: npm install sockjs-client. Now I want to add mapping of node_modules/sockjs-client in systemjs.config.js. It is how the file looks now:
/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs':                       'npm:rxjs',
            'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
            'sockjs-client': 'npm:sockjs-client',
            'stompjs': 'npm:stompjs/lib/stomp.min.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular2-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);

And I've the following exception in the browser:
localhost/:16 Error: Error: XHR error (404 Not Found) loading http://localhost:8080/node_modules/sockjs-client(…)

What is the proper systemjs mapping for sockjs-client library?

A: Try:
'sockjs-client': 'npm:sockjs-client/dist/sockjs.js'


text:
Q: Can it cause problems to switch from apt-get to aptitude? I've been thinking about switching to aptitude, but I've heard people say "if you're already using apt-get, you should wait until your next installation to switch." Why do people say this? What sort of problems (if any) can this cause?

A: apt-get and aptitude are different UIs that are part of the same package management system, APT, the Advanced Packaging Tool.  For instance, both are configured using /etc/apt/apt.conf, both use the same filespace and formats to represent package state, and the same filespace to store downloaded .debs.
How they differ is their internal rule system to represent potential conflicts between package, how to resolve them (say during apt-get dist-upgrade vs. aptitude full-upgrade), and how to express these when interacting with the user.  Generally speaking, both might do the wrong thing in tricky situations, but apt-get is much more likely to get it wrong than aptitude.

A: Lots of good advice is already here, but let me add one thing nobody has mentioned. If you do decide to switch, you may want to run this command, depending on what you've been up to with apt-get:
aptitude keep-all

That command resets aptitude's sense of what packages are orphans and should be removed.
Here's the reason it's sometimes useful: for awhile now, both apt-get and aptitude will track packages that were automatically installed as a dependency of something else. So, for example, if you install mpd, you might get lib-so-and-so as a dependency. They do this, so that if you later remove mpd, lib-so-and-so gets removed too. But aptitude and apt-get handle this clean up differently. aptitude immediately tries to remove all orphaned dependencies; but apt-get merely suggests that you run apt-get autoremove to clean up. (The logic behind all of this is that you only got the library since mpd needed it. If you don't keep mpd, you shouldn't need the library any longer. If another package still depends on it, then both aptitude and apt-get will know this and not try to remove the library.)
What's my point? Well, if you've been seeing constant nudges to run apt-get autoremove and you switch to aptitude, then you may be in for a shock the first time you try to install something. aptitude will straightaway try to remove all those orphans. In general, this will be fine (they're orphans after all, and not necessary), but there is one complicating case. The desktop meta-packages all involve a complex dependency chain where each individual program is pulled in as a dependency of a virtual package wrapper. For example, if you have Gnome installed because you installed the gnome package, then all of your normal desktop programs were installed as dependencies. If you have uninstalled a single one of these programs (e.g., Ekiga or Gedit), then in the eyes of aptitude the rest of your desktop should be removed too. Note that aptitude always asks before it removes things, but people often enter 'Y' without reading. In my experience, this is the single most common complaint/confusion for people new to Debian.
Two general pieces of advice:

*

*Always read the output of aptitude or apt-get carefully, before saying yes to anything.

*Remember that you can always do a dry-run using aptitude -s safe-upgrade or aptitude -s install foo. The -s|--simulate flag is your friend.

A: It was said on the Debian mailing list, years ago, that switching from apt-get to aptitude was risky.  This is two Debian versions (say 10 years) ago.  All those problems seem to be worked out now, and certainly I haven't seen problems on either Debian or Ubuntu.

A: I'd also say go ahead and use aptitude.
Aptitude has a better dependency management than apt-get. This will help keeping the count of orphaned packages low.
I've read a while ago that aptitude has the better dist upgrade algorithm compared to apt-get. But that's hardly a killer feature as it's not used that often in the life time of a system.
Additionally you'll have more stuff united in one tool. Rather than remembering when to call apt-get, apt-cache or dpkg and with which switches I just use aptitude and get most things done.
As for complications when switching "in the middle": I don't remember having had any when I did it.

A: Are they not just a different interface to the same backend?

A: From my experience, they have a different way of pinning package versions. In my case, I told aptitude to lock certain packages, assuming I'd be safe from future updates. I was wrong; the cron-scheduled update manager, which uses apt-get, proceeds to upgrade it to my dismay.
Drats, as I was writing this, I googled and found out that the bug (#557580 aptitude does not obey pins in preferences.d/*) was already fixed!

A: I use both apt-get and aptitude without any problem: I have the same question...Why do people say this??? :D
Go on, and don't worry: aptitude is just a text-gui for apt-get, that you could even use as a command line application, for example apt-get install foo is the same as aptitude install foo.
Regards


text:
Q: An Algebraic Proof that $|y^3 - x^3| \ge |(y - x)|^3/4 $ I can prove this using calculus, but not by simple algebra: can anyone help ?

Calculus Proof:
Fix the separation of $x$ and $y$ so that $y = x + d$ with $d>0$ ($ \implies y > x \implies y^3 > x^3$) and now consider $ f(x) = y^3 - x^3 = (x+d)^3 - x^3$.
$ f(x) = (x+d)^3 - x^3$ = $3x^2d + 3d^2x +d^3$ which is a quadratic in $x$ with a minimum given by $f`(x) = 0 = 6xd + 3d^2$ giving $x = - d/2$ and therefore $y = d/2$. This is not surprising considering the geometry: it says that for a fixed separation of $x$ and $y$, $y^3 - x^3$ is minimised when $x$ and $y$ are symetrically placed around the inflexion point of the cubic.
So, $y^3 - x^3 = d^3/8 - (-d^3)/8 = d^3/4$ and since this is the minimum value it follows that for $x \in (-\infty, +\infty)$ and $y > x$ then $y^3 - x^3 \ge (y - x)^3/4 $, so that  $|y^3 - x^3| \ge |(y - x)|^3/4 $ whether $y > x$ or $y < x$ (and clearly this is true for $y = x$.)

(The original interest in the inequality comes from this question: cauchy sequence on $\mathbb{R}$)

A: Wlog. $y\ge x$. Then
$$\begin{align}y^3-x^3&\ge \frac{(y-x)^3}{4}&\iff\\
4(y^3-x^3)-(y-x)^3&\ge 0&\iff\\
3y^3+3y^2x-3x^3-3x^2y&\ge 0&\iff\\
3(y+x)^2(y-x)&\ge0\end{align}$$

A: $ |y^3-x^3| \geq |y-x|^3/4 \\
\iff |y-x|(x^2+xy+y^2) \geq |y-x|(y-x)^2/4 \\
\iff 4(x^2+xy+y^2) \geq (x^2-2xy+y^2)$
(Assuming that $y\neq x$)
$\iff 3x^2+6xy+3y^2 \geq 0\\
\iff (x+y)^2 \geq 0$
EDIT
$x^2+xy+y^2 = (x+y/2)^2 + 3y^2/4 \geq 0$


text:
Q: EF: checking if object has been modified I have a Listview with objects.
When I select an item from the Listview, I need to know if the selectedObject of the Listview has been modified to activate or not a saveButton.
This is how I proceed using Mvvmlight and Entity Framework 5 :
public RelayCommand SaveObjectCommand { get; set; }

public MainViewModel()
{
    SaveObjectCommand = new RelayCommand(SaveObject, CanSaveObject);
}

private bool CanSaveObject()
{
     using (DBContext ctx = new DBContext())
     {
         //selectedObject is the object selected from the Listview
         Object dbObject = ctx.Object.Single(x => x.ID == selectedObject.ID);

         if (selectedObject == dbObject) //simplified
             return false;
     }
}

That's working but it's quite slow.
In fact each time I select an object from the listview, I request the DB to know if selectedObject is equal to the same object in DB (my way to know if the selectedObject properties have been modified)
Is there a better way to do that?
I've heard about DBContext.ChangeTracker but it seems that it needs a DB request to.

A: I can't add comment.
What DB are you using? Is it compact?
And a workaround for your question: you can declare property
private List<Object> MyCollectionOfObjects {get; set;}

with your own collection and access to it in CanSaveObject() wethod. If DB needs for update you should update DB and this property.

A: You mentioned, your textblocks probably textboxes can modify the selected object properties where you will check if that object CanSave. I recommend looking at IEditableObject interface
A quick sample
public class Customer : IEditableObject
{

    struct CustomerData
    {
        internal string id ;
        internal string firstName ;
        internal string lastName ;
    }

    private CustomersList parent;
    private CustomerData custData;
    private CustomerData backupData;
    private bool inTxn = false;

    // Implements IEditableObject
    void IEditableObject.BeginEdit()
    {
        Console.WriteLine("Start BeginEdit");
        if (!inTxn)
        {
            this.backupData = custData;
            inTxn = true;
            Console.WriteLine("BeginEdit - " + this.backupData.lastName);
        }
        Console.WriteLine("End BeginEdit");
    }

    void IEditableObject.CancelEdit()
    {
        Console.WriteLine("Start CancelEdit");
        if (inTxn)
        {
            this.custData = backupData;
            inTxn = false;
            Console.WriteLine("CancelEdit - " + this.custData.lastName);
        }
        Console.WriteLine("End CancelEdit");
    }

    void IEditableObject.EndEdit()
    {
        Console.WriteLine("Start EndEdit" + this.custData.id + this.custData.lastName);
        if (inTxn)
        {
            backupData = new CustomerData();
            inTxn = false;
            Console.WriteLine("Done EndEdit - " + this.custData.id + this.custData.lastName);
        }
        Console.WriteLine("End EndEdit");
    }

    public Customer(string ID) : base()
    {
        this.custData = new CustomerData();
        this.custData.id = ID;
        this.custData.firstName = "";
        this.custData.lastName = "";
    }

    public string ID
    {
        get
        {
            return this.custData.id;
        }
    }

    public string FirstName
    {
        get
        {
            return this.custData.firstName;
        }
        set
        {
            this.custData.firstName = value;
            this.OnCustomerChanged();
        }
    }

    public string LastName
    {
        get
        {
            return this.custData.lastName;
        }
        set
        {
            this.custData.lastName = value;
            this.OnCustomerChanged();
        }
    }

    internal CustomersList Parent
    {
        get
        {
            return parent;
        }
        set
        {
            parent = value ;
        }
    }

    private void OnCustomerChanged()
    {
        if (!inTxn && Parent != null)
        {
            Parent.CustomerChanged(this);
        }
    }

    public override string ToString()
    {
        StringWriter sb = new StringWriter();
        sb.Write(this.FirstName);
        sb.Write(" ");
        sb.Write(this.LastName);
        return sb.ToString();
    }
}

I request the DB to know if selectedObject is equal to the same
  object in DB (my way to know if the selectedObject properties have
  been modified)

In your case it's better to do the check against in memory instead of going to the database and see if any of the values are different to what was inputted.


text:
Q: Epsilon induction I recently came upon this technique called epsilon induction, and was searching for some proof using the same. But I saw no such proof. Does someone know of any proof using this technique?

A: You can use epsilon-induction to prove that every set belongs to the von Neumann hierarchy. For ordinals $\xi$ define $V_\eta$ in the usual way: $V_0=0, V_{\eta+1}=\wp(V_\eta)$, and $V_\eta=\bigcup_{\xi<\eta}V_\xi$ for limit $\eta$. Let $x$ be any set, and suppose that $\forall y\in x\,\exists\xi\in\mathbf{ON}\,(y\in V_\xi)$. For $y\in x$ let $\xi(y)$ be the least ordinal such that $y\in V_{\xi(y)}$, and let $\eta=\sup\{\xi(y):y\in x\}$. (We can do this using Replacement.) Then $x\subseteq V_\eta$, so $x\in V_{\eta+1}$. It now follows immediately by epsilon-induction that every set is in some $V_\xi$.


text:
Q: Madgwick IMU algorithm, how to get 360 degree freedom variables? I'm implementing different IMU methods in a project of mine and I'm currently experimenting with the well known Madgwick's implementation of Mayhony's AHRS algorithm (MahonyAHRS.c)
So far it works around as good as my self implemented one which is based on Vector rotation and an running average sensor fusion (often called complementary).
However, I would like to get 360 degree of freedom out of it and I currently use this function:
void imu_mahony_getRollPitchYaw(float *roll_, float *pitch_, float *yaw_)
{
    *yaw_ = fast_atan2f(2*q1*q2 - 2*q0*q3, 2*q0*q0 + 2*q1*q1 - 1);
    *pitch_ = -asin(2*q1*q3 + 2*q0*q2);
    *roll_ = atan2f(2*q2*q3 - 2*q0*q1, 2*q0*q0 + 2*q3*q3 - 1);
}

However, that results in the 90 degree issues.
What I would like is to receive pitch and roll in a form of 0-359 degrees.


text:
Q: Get output of TMSSqlRow in Talend I would like to get the number of row affected / deleted / updated with a TMSSqlRow.
Here is how the job is:

the file use contains a lot of sql statement like DELETE ... INSERT ... UPDATE...
each row are separate by ";"
But now, I would like to get result of each statement (x rows updated, like results are display in management studio).
When I go to "advanced settings" tab of tmssqlrow, I select " Propagate QUERY's recordset" and select a column I created before (Object Type).
On execution, I have this error:

The executeQuery method must return a result set.

So, how I can get the result of each statement and insert it (by example) in a database / file?

A: The option "Propagate QUERY's recordset" must be used in combination with a tParseRecordSet in order to extract info from the returned recordset. However, that is not sufficent: you must explicitly write the query to return the number of records updated/deleted.
Here's what I did:

My tJDBCRow (same as tMSSqlRow) query looks like this (notice how I had to add 'set nocount on' before the update query, and 'select @@rowcount' after)

tParseRecordSet retrieves the number of lines from the column resultset (nbLines is the alias of my rowcount)

A: If you need the number of rows affected, a better option is to use the tMSSqlOutput component which can update,insert or delete rows. After execution, the component provides global variables to show how many rows were affected by the operation.
((Integer)globalMap.get("tMSSqlOutput_1_NB_LINE"))
((Integer)globalMap.get("tMSSqlOutput_1_NB_LINE_UPDATED"))
((Integer)globalMap.get("tMSSqlOutput_1_NB_LINE_INSERTED"))
((Integer)globalMap.get("tMSSqlOutput_1_NB_LINE_DELETED"))


text:
Q: Only one variable is working at a time, and it is dependent on which order I declare them in I really didn't know what to put as the title for this so ignore that. I also don't know how to describe the question so here is my issue.
#include <iostream>
#include <vector>

class ClassB {
public:
  //LOOK AT THIS PART
  int value;
  char letter;
  ClassB(char t, int v) {
    letter = t;
    value = v;
  }
};

class ClassA {
private:
  ClassB* ptr;
public:
  ClassA(ClassB n) {
    ptr = &n;
  }
  ClassB* getPtr(){
    return ptr;
  }
};

int main() {
  std::vector<ClassA> objects;
  for(int i=0;i<4;i++) {
    objects.push_back(ClassA(ClassB('a',i)));
  }
  std::cout << "Value: " << objects[1].getPtr()->value << std::endl;
  std::cout << "Letter: " << objects[1].getPtr()->letter;
  return 0;
}

In this code, the output I should receive is
Value: 1
Letter: a

However I am receiving this
Value: 1
Letter

Also, if I were to declare letter before value (look at the comment in code), then the output would say
Value: 0
Letter: ☺

I'm not sure why the order I declare them in would affect anything, or why I'm getting a smiley face instead of a. Any help is appreciated, thank you!

A: The problem lies here:
 ClassA(ClassB n) {
    ptr = &n;
  }

ClassB is a temporary variable that gets destructed at the end of the function. The pointer becomes invalid and the program goes nuts.
A simple and safe way to go about this, is to use an std::unique_ptr and pass parameters. unique_ptr will automatically delete ClassB when ClassA is deleted:
private:
  std::unique_ptr<ClassB> ptr;
public:
  ClassA(char t, int v) {
    ptr = std::make_unique<ClassB>(t, v);
  }

There's also just keeping a value instead of a pointer.


text:
Q: EXCEL VBA: ConvertFormula returns #VALUE I have several subroutines that use the ConvertFormula VBA command.  Unfortunately I ran into a situation where none of the subroutines work.  It appears it is the single line containing the ConvertFormula command that is returning the #VALUE error so I can't error check any deeper than that.
Using the Immediate window I was able to test this isolated command.  Here are 3 separately executed lines of code.
ActiveSheet.range("Z270")=application.ConvertFormula(formula:="=Sheet2!V23+Sheet2!W23*Z$224+Sheet2!X23*Z$224^2+Sheet2!Y23*Z$224^3+Sheet2!Z23*Z$224^4",fromreferencestyle:=xlA1, toreferencestyle:=xla1, toabsolute:=xlabsolute)

ActiveSheet.range("Z270")=application.ConvertFormula(formula:="=Sheet2!V23+Sheet2!W23*Z$224+Sheet2!X23*Z$224^2+Sheet2!Y23*Z$224^3",fromreferencestyle:=xlA1, toreferencestyle:=xla1, toabsolute:=xlabsolute)

ActiveSheet.range("Z270")=application.ConvertFormula(formula:="=Sheeet2!V23+Sheeet2!W23*Z$224+Sheeet2!X23*Z$224^2+Sheeet2!Y23*Z$224^3",fromreferencestyle:=xlA1, toreferencestyle:=xla1, toabsolute:=xlabsolute)

The first line returned #VALUE, the 2nd returned the formula correctly, and the 3rd returned #VALUE  again.  Notice that in the 3rd I'd renamed the offsheet reference to Sheeet2, with an extra 'e' to add length to the formula.
I suspect that the behavior is related only to the formula string length and not the contents.  The formula string lengths in my example are 85, 66, and 70 characters for the 1st, 2nd and 3rd lines respectively.
I'm not sure where the exact cut-off is, or whether the $ is excluded from the character count limit.  Just wanted to put this out there to see if anyone can confirm my hypothesis, provide further insight, or provide an alternative explanation.
In response to the RFI about reference cell values, all referenced cells contained numeric values.  'Z$224' value was 65, formatted as 65.0.  Sheet2 cells V23 thru Z23 had the following values (formatted in scientific notation):
1.0037243; -0.000062039288; 0.000000012983893; -0.00000000042225392

A: Ran into the same with varying character limits. Have not found a fix but there are workarounds.

*

*Shorten the formulas using Custom user functions

*Write your own conversion function. Which you can use Regular Expression to insert dollar signs to references and simple Replace() to remove them.


text:
Q: How would you traverse a directory and do some function on all files and combine the output in a memory efficient manner? Setting
I need to traverse a directory over 100+ .txt files, open every one and do some function on each, then combine the results. These files are huge, on the order of 10GB. Some common operation in psuedocode might be:
foldr concatFile mempty $ openFile <$> [filePath1, ..., filePathn]
foldr countStuff 0      $ openFile <$> [filePath1, ..., filePathn]

The trick is to make sure all the files never exist in memory at the same time, my previous naive solution created all kinds of swap files on my mac.
In addition, if one of the filePath is invalid, I'd like to just skip over
it and go on with the program.
My Solution
Currently I'm using conduit and would like to find a solution using conduit if possible. But if it's not the right tool I'm fine with using something else.

A: You can nest conduit execution like this:
{-# LANGUAGE OverloadedStrings #-}

import Conduit
import qualified Data.ByteString as BS

-- Process a single file
processFile :: FilePath -> IO ()
processFile path = runResourceT (sourceFile path =$= mapC BS.length $$ sumC) >>= print

-- Run processFile for directory in a tree
doit :: FilePath -> IO ()
doit top = runResourceT $ sourceDirectoryDeep False top $$ mapM_C (liftIO . processFile)

Replace processFile with whatever you want to do -- including
ignoring the file. My understanding is that the sourceFile Producer will efficiently chunk
the contents of a file.
And, according to this Yesod article, sourceDirectoryDeep should
efficiently traverse a directory structure.
The thing you apparently can't do with sourceDirectoryDeep is prune
directories.


text:
Q: How to change background color of divs on mouse click and drag with the HTML5 color input I want to change the background color of my divs by clicking and dragging over them to the value of the color from the color input.
HTML:

  <input type="color" id="colorPicker">

Javascript:
var div = $('.square');
div.mousedown(function() {
  $(this).css("background-color", $("#colorPicker").val());
});

Here is my JS FiddleThis is the effect I want but with the color value: JS Fiddle

A: Do this with your jQuery:
    var div = $('.square');
    div.mousedown(function() {
        $(this).css("background-color", $("#colorPicker").val());
        //add this line
        div.on("mouseenter.square",function(){
             $(this).css("background-color", $("#colorPicker").val());
        });
    });

A:

<input type="color" id="colorPicker">

A: This may be what you want.
var div = $('.square')
div.mousedown(function() {
    $(this).css("background-color", $("#colorPicker").val())
    div.mouseenter(function() {
        $(this).css("background-color", $("#colorPicker").val())
    })
})
$(document).mouseup(function() {
    div.off('mouseenter')
})


text:
Q: \enumerate in \blockquote produces "missing \item" error when specified package options for csquotes I am using XeLaTeX.
\documentclass[10pt,twoside]{report}

\usepackage[thresholdtype=words]{csquotes}
\usepackage{enumerate}

\begin{document}

    \blockquote{
        \textbf{konungr} (-s, -ar), \textit{m.}
        \begin{enumerate}
            \item king.
        \end{enumerate}
    }

\end{document}

which produces the following error:
! LaTeX Error: Something's wrong--perhaps a missing \item.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.13 ^^I}

However, if I remove the package option for csquotes, i.e. replace line 3:
\usepackage[thresholdtype=words]{csquotes}

with this:
\usepackage{csquotes}

It compiles fine. The result looks like:

which is properly indented.
This is a minimally compiling example. I do not want to remove that package option because I want to have a similarly indented \blockquote for a very short line that follows this. Without the package option, this:
\documentclass[10pt,twoside]{report}

\usepackage{csquotes}
\usepackage{enumerate}

\begin{document}

    \blockquote{
        \textbf{konungr} (-s, -ar), \textit{m.}
        \begin{enumerate}
            \item king.
        \end{enumerate}
    }

    \blockquote{
        Nouns like ``konungr'' \textit{king} and ``dvergr'' \textit{ghost} decline in the easiest pattern.
    }

\end{document}

the result is:

The second \blockquote does not get indented like the first one, but instead gets enclosed by double quotes.

A: I assume the problem is due to how csquotes counts words, but I'm in no position to explain the gory details. However, you can work around the problem.
My first thought is that quotations which include lists should simply be put in csquotes' displayquote environment. That is,
\begin{displayquote}
  \textbf{konungr} (-s, -ar), \textit{m.}
    \begin{itemize}
        \item king.
    \end{itemize}
\end{displayquote}

Alternatively, you could create your own version of \blockquote, which switches from counting by words back to the default line-counting. The example below is merely proof of concept and provides a far 'dumber' \blockquote-type command than the original. (But maybe that's no real loss: I hever bother with the optional arguments myself.)
\documentclass[10pt,twoside]{report}

\usepackage[thresholdtype=words]{csquotes}
\SetBlockThreshold{50}
%\usepackage{enumitem}% this package does not affect problem

\newcommand\zzz[1]{%
  \begingroup
  \setkeys{csq}{thresholdtype=lines}%
  \blockquote{#1}%
  \endgroup
}

\newcommand{\example}{This is a minimally compiling example. I do not
  want to remove that package option because I want to have a
  similarly indented blockquote for a very short line that follows
  this.  This is a minimally compiling example. I do not want to
  remove that package option because I want to have a similarly
  indented blockquote for a very short line that follows this.}

\begin{document}

\example

\blockquote{This is a minimally compiling example.}

\blockquote{\example}

    \zzz{%
        \textbf{konungr} (-s, -ar), \textit{m.}
        \begin{itemize}
            \item king.
            \item or: ``rex''
        \end{itemize}
    }

\blockquote{\example}

\example

\blockquote{This is a minimally compiling example.}

\end{document}


text:
Q: fail2ban/ipfw/Mac OS X server not denying connections I am trying to set up some firewall for my 10.5 server, but I just cannot seem to get it to work. The main aim is to try to stop the constant brute force mail login attempts.
To this end I installed fail2ban, to spot and ban the failed logins. For the most part this works, ie the mechanics of submitting the banned IP addresses and sending me an email to that effect is accomplished. If I start up a terminal session I get dozens of IP addresses listed with the following command:
sudo ipfw list

With an entry looking like:
12345 deny tcp from 123.123.23.123 to any in

But, the ban just isn't effective - the same IP address will try again later, sometimes every few seconds for hours.
When I check the fail2ban log it complains (after it has detected a malicious login attempt multiple times):
"WARNING [sasl-ipfw] 123.123.123.123 already banned"

I have tried formatting the ban in different ways:
12345 deny tcp from 123.123.23.123 to 127.0.0.1 dst-port 25
12345 deny tcp from 123.123.23.123 to 192.168.123.123 dst-port 25

But just not making any difference. I even tried just a local network network ban to the web service:
12345 deny tcp from 192.168.123.122 to 192.168.123.123 dst-port 80

But again that does not have any effect. The other rules, seem to be default, in the IPFW list look like:
12300 allow log logamount 1000 tcp from any to any established
12301 allow log logamount 1000 tcp from any to any out
12302 allow log logamount 1000 tcp from any to any dst-port 22 …

and one final rule in the list (which I read somewhere cannot be changed):
65535 allow ip from any to any

Server admin app indicates that the firewall service is running, there are no "deny" listings in the ipfw log. The entries patched in to IPFW by fail2ban do not appear in the Server Admin entries anywhere, nor in the ipfw.conf or ipfw.conf.apple files (so I'm not sure where they are stored). But I do see them when I get "ipfw list" in the terminal and they are listed in the "Active Rules" tab of the Firewall section in Server Admin.
Thanks for any help on this issue.

A: It looks like your fail2ban script is using too high a rule number. ipfw evaluates rules in numeric order, and the first that applies to a given packet determines what's done with it. This means that lower-numbered rules have higher priority. Since the fail2ban "deny" rules are getting added with the number 12345, but the Server Admin-configured "allow" rules start at 12302, at least some of the allow rules are overriding fail2ban's deny rules.
Simple fix: find where the rule number is defined in your fail2ban script, and lower it to something like 12200.
BTW, the fact that fail2ban's rules aren't getting added to the config files is normal, and probably good. These files are used when the firewall is reloaded (e.g. when you reboot), but don't necessarily reflect the "live" firewall state. If you wanted, you could edit the fail2ban script to add its rules to those files as well as setting them in the live state, but that means that your ruleset would grow arbitrarily large over time. IMO, the only time you should bother with such "permanent" bans is if you keep seeing abuse from the same IPs over and over for a long period of time... but I'd expect this to be rare.


text:
Q: What happens exactly to a gulp plugin when .pipe invoke a gulp plugin? For example, here is a simple gulp plugin
'use strict';

var match = require('gulp-match');
var ternaryStream = require('ternary-stream');
var through2 = require('through2');

module.exports = function (condition, trueChild, falseChild, minimatchOptions) {
    if (!trueChild) {
        throw new Error('gulp-if: child action is required');
    }

    if (typeof condition === 'boolean') {
        // no need to evaluate the condition for each file
        // other benefit is it never loads the other stream
        return condition ? trueChild : (falseChild || through2.obj());
    }

    function classifier (file) {
        return !!match(file, condition, minimatchOptions);
    }

    return ternaryStream(classifier, trueChild, falseChild);
};

And here is a typical use case
gulp.task('task', function() {
  gulp.src('./src/*.js')
    .pipe(gulpif(condition, uglify()))
    .pipe(gulp.dest('./dist/'));
});

I am trying to figure out what is going on
According to the documentation, every gulp plugin is suppose to pass in a vinyl file and return a vinyl file.
But where is the passed in vinyl file ?
The only passed in parameter is  condition, trueChild, falseChild, minimatchOptions
Furthermore how does pipe receive the return vinyl file from the plugin?


text:
Q: Netty 4 not work in more than 4 channels i have some netty-server which i use for uploading files on amazon s3.i try do some test with jmeter and i get strange trouble: my server get just 4-files and start uploading them. other files handle after one of those 4files complete uploading. i thing that netty must work with many threads, not 4.sorry for my english, i need help and hope for your advices.
there is my handler
 protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println("request");
        request = (HttpRequest) msg;
        reqURI = request.getUri();
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(reqURI);
        switch (queryStringDecoder.path()) {
            case ("/getfile"):
                sendSimpleResponse(channelHandlerContext, OK, "getfile");
                break;
            case ("/upload"):
                showUploadForm(channelHandlerContext);
                break;
            case ("/formpostmultipart"):
                if (request.getMethod().equals(HttpMethod.POST)) {
                    decoder = new HttpPostRequestDecoder(dataFactory, request);
                    decoder.setDiscardThreshold(0);
                } else {
                    sendSimpleResponse(channelHandlerContext, BAD_REQUEST, "");
                }
                break;
            default:
                sendSimpleResponse(channelHandlerContext, NOT_FOUND, "");

        }
    }

    if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            decoder.offer(chunk);
            readChunk(channelHandlerContext);
            if (chunk instanceof LastHttpContent) {
                resetPostRequestDecoder();
            }
        }
    }
}
private void readChunk(ChannelHandlerContext ctx) throws IOException {
    while (decoder.hasNext()) {
        InterfaceHttpData data = decoder.next();
        if (data != null) {
            try {
                switch (data.getHttpDataType()) {
                    case Attribute:
                        break;
                    case FileUpload:
                        FileUpload fileUpload = (FileUpload) data;
                        System.out.println("send file call");
                        logger.info("start upload");
                        AWSfunctions aws = new AWSfunctions();
                        aws.sendFile(fileUpload);
                        break;
                }
            } finally {
                data.release();
            }
        }
    }
}

and this class for work with amasons3. (you can see that i try give more connections for client,but this not work too)
public class AWSfunctions {
AmazonS3 connection;

AWSfunctions() {
    Config conf;
    String AccessKeyId;
    String SecretKey;
    AWSCredentials credentials;
    ClientConfiguration clientConfiguration;
    conf = ConfigFactory.load();
    AccessKeyId = conf.getString("AWSCredentials.AWSAccessKeyId");
    SecretKey = conf.getString("AWSCredentials.AWSSecretKey");
    credentials = new BasicAWSCredentials(AccessKeyId, SecretKey);
    clientConfiguration = new ClientConfiguration();
    clientConfiguration.setProtocol(Protocol.HTTP);
    clientConfiguration.setMaxConnections(200);
    System.out.println(clientConfiguration.getMaxConnections());
    connection = new AmazonS3Client(credentials, clientConfiguration);
}

public void sendFile(FileUpload fileUpload) throws IOException {
    Random rnd = new Random();
    File file;
    file = fileUpload.getFile();
    System.out.println("upload started");
    connection.putObject(new PutObjectRequest("test-for-est", String.valueOf(rnd.nextInt()), file));
    System.out.println("Upload completed");
}}

A: oh, it very simple. i did some change in server class...
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer());
        ChannelFuture ch = b.bind(port).sync();
        ch.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

change
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();

to
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(20);


text:
Q: How to fetch list of users with permission 'x' in zizaco entrust laravel? I wanted to show list of users those are having permission 'x'.  I am using zizaco/entrust plugin in laravel 5.1 for managing roles/permissions. I have setup roles and permissions already. Previously i was working with roles but change of specs i need it by permissions wise.

A: You can use whereHas():
$permissionName = 'x';

$userList = User::whereHas('roles.perms', function($query) use ($permissionName) {
    $query->whereName($permissionName);
})->get();

dd($userList);


text:
Q: IBM Cloud crashes nodejs server even if errors are caught I'm using IBM cloud bucket storage for my app. When I'm trying to retrieve a file that doesn't exist the app still crashes even though I handle the error. This is my code.
Exported function:
export const getFileStream = (itemName) => {
    return cos.getObject({
        Bucket: bucketName,
        Key: itemName
    }).on('error',(err)=>{
        console.log("we've got an error");
        throw err;
    }).createReadStream();
};

Where it's used
export const getCV = async (req, res) => {
  if (!req.params.id) return res.status(404).json({ message: "Invalid profile id!" });
  await UserModel.findById(req.params.id, '-password').then(async (details) => {
    if (!details) return res.status(404).json({ message: 'User not found!' });
    if (!details.CV) return res.status(404).json({ message: 'No CV found!' });
    res.attachment('CV.pdf');
    res.set("Content-Type", "application/pdf");
    getFileStream(details.CV)
      .on('error', (err) => {
        throw err;
        // return res.status(404).json({ message: err.message });
      })
      .pipe(res);
  }).catch(err => { return res.status(404).json({ message: err.message }); });
};

When details.CV is a bogus item id, then I get the error below.
My logs and the error are displayed in the console, but the server still crashes and requires a restart.
This is the error :
Server running on port : 9000
Connected to DB successfully
we've got an error
we've got another error
/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:31
            throw err;
            ^

NoSuchKey: The specified key does not exist.
    at Request.extractError (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/services/s3.js:585:35)
    at Request.callListeners (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:683:14)
    at Request.transition (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/state_machine.js:14:12)
    at /home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:685:12)
    at Request.callListeners (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/sequential_executor.js:116:18)
    at Request.emit (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:683:14)
    at Request.transition (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/state_machine.js:14:12)
    at /home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/home/paul/Documents/ProiectIBM/proiect-ibm/Server/node_modules/ibm-cos-sdk/lib/request.js:38:9) {
  code: 'NoSuchKey',
  region: null,
  time: 2021-05-10T12:37:47.764Z,
  requestId: '1b2c2405-ea63-4a8f-b81c-1746a0214cde',
  extendedRequestId: undefined,
  cfId: undefined,
  statusCode: 404,
  retryable: false,
  retryDelay: 96.14914686040396
}


text:
Q: ¿Cuál es el error que comento aquí? reposo = 0

class Water():

    def encendido(self):
        if Water is True:
            print('El Water está funcionando')

        elif Water == reposo:
            print('El Water está en reposo')

        else:
            print('El Water está apagado')

print(Water)

Me dice: <class '__main__.Water'> sin nombrarme ningún tipo de error. ¿Estoy usando mal la clase?

A: La mejor explicación que vi sobre clases, objetos y métodos fue en los videos de pildorasinformaticas.es, te los recomiendo.
Te propongo un código por si se parece a lo que quieres.
class water:
    def __init__(self):
        self.encendido = False

    def abre_grifo(self):
        self.encendido = True

    def cierra_grifo(self):
        self.encendido = False

    def __str__(self):
        return 'Water está encendido' if self.encendido else 'Water está apagado'

Creas una clase y la inicias con el atributo encendido  a False. Despues creas métodos para modificar el estado del mismo.
Para poder imprimir el objeto puedes modificar el __str__.
Lamadas a la clase:
w = water()
print(w)
w.abre_grifo()
print(w)
w.cierra_grifo()
print(w)

Creas el objeto w y lo imprimes gracias al __str__ .
Modificas el atributo del objeto e imprimes y observas como cambia el valor del atributo encendido .
Los resultados son:
Water está apagado
Water está encendido
Water está apagado


text:
Q: Is jQuery's "each()" method a for loop? I tried adding a serialized class to each of a set of objects like this:

jQuery('#preload img').each(function(){
    jQuery('#thumbs').append('');
    index = ++index;
    });

And it worked. What resulted was a set of images, each with a class image1, image2, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index is incremented?
Anybody know what's actually happening?

A: This is the inner workings of the each function (1.4.4):
// args is for internal usage only
each: function( object, callback, args ) {
    var name, i = 0,
        length = object.length,
        isObj = length === undefined || jQuery.isFunction(object);

    if ( args ) {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.apply( object[ name ], args ) === false ) {
                    break;
                }
            }
        } else {
            for ( ; i < length; ) {
                if ( callback.apply( object[ i++ ], args ) === false ) {
                    break;
                }
            }
        }

    // A special, fast, case for the most common use of each
    } else {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
                    break;
                }
            }
        } else {
            for ( var value = object[0];
                i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
        }
    }

    return object;
}

You can see here that it has a few different cases but all of them use for loops and call the callback function. So your code should be fine.
You can look it up in the development version of jQuery (change the radio button on the main jQuery site, or click here).

A: .each() is indeed essentially a for loop and it also has a built in index you can use if you pass in an argument like so:
jQuery('#preload img').each(function(i){
    jQuery('#thumbs').append('');
});

EDIT: Bonus implementation with Ken Franqueiro's string concatenation suggestion:
var thumbsAppend = "";
jQuery('#preload img').each(function(i){
    thumbsAppend += '';
});
jQuery('#thumbs').append(thumbsAppend);

EDIT #2: And rahul's array push suggestion:
var thumbsAppend = [];
jQuery('#preload img').each(function(i){
    thumbsAppend.push('');
});
thumbsAppend = thumbsAppend.join('');
jQuery('#thumbs').append(thumbsAppend);

A: http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/

are iterated by numeric index, from 0
  to length-1


text:
Q: C++ template functions accepting parameters in random order I am writing a C++ network library and would like the main (template) function to accept parameters in random order, to make it more user friendly, in the same way the CPR library does.
The template function will accept up to 10 parameters at the same time, each a different type. Is there a way to instantiate the template to accept any random order of param types, other than having to manually include code for every possibility?
For example - in this case using 3 params each a different type:
.h file
namespace foo
{
    template <typename T, typename U, typename V> void do(const T& param_a, const U& param_b , const V& param_c);
};

.cpp file
template <typename T, typename U, typename V>
void foo::do(const T& param_a, const U& param_b, const V& param_c) {
//do lots of stuff
}

//instantiate to allow random param order
template void foo::do<int, std::string, long>(const int&, const std::string&, const long&);
template void foo::do<int, long, std::string>(const int&, const long&, const std::string&);
template void foo::do<int, std::string, int>(const int&, const std::string&, const int&);
//etc... to cover all possible param orders

A: If your goal is to match the API design of a given library, best way to learn is to dig into its source code and dissect it.
Consider this snippet of code (I'm still using CPR as an example as you mentionned it as a reference):
cpr::Session session;
session.SetOption(option1);
session.SetOption(option2);
session.SetOption(option3);

You want a method which can handle option1, option2, ... , no matter in which order they are provided. The subsequent calls to SetOption could be replaced with a single SetOptions(option3, option1, option2). Therefore we need a variadic SetOptions method:
template<typename Ts...> // important: don't specialize the possible argument types here
void SetOptions(Ts&&... ts)
{ /* do something for each param in ts... */ }

The question is "how do you call SetOption for each item inside the ts parameter-pack ?". This is a mission for std::initializer_list. You can find a simple example here.
The key here is to have an overloaded function which can handle each argument type separately (example in CPR with SetOptions). Then, inside your "permutable" function, you call the overloaded function for each of your arguments, one at a time (example in CPR, which is then used in various places).
One thing to note though is that you can pass multiple parameters of the same type. Depending on what you want to achieve, this can be an issue or not.
Also, you can call the method with unsupported argument types (matching none of your overloads), in this case the error message is not always explicit depending on which compiler you are using. This is — however — something you could overcome using static_asserts.

A:
Is there a way to instantiate the template to accept any random order of param types, other than having to manually include code for every possibility?

You cannot do this for explicit instantiation definitions without macros, but you could use a separate approach and rely on implicit instantiations instead, using SFINAE to restrict the primary template (whose definition you move to the header file) based on two custom traits.
To begin with, given the following type sequence
template <class... Ts>
struct seq {};

we want to construct a trait that, for a given type sequence seq<T1, T2, ...> (your "10 parameter types"), denoted as s:

*

*s shall be a subset of set of types of your choosing seq<AllowedType1, ...>, and

*s shall contain only unique types.

We can implement the former as:
#include <type_traits>

template <class T, typename... Others>
constexpr bool is_same_as_any_v{(std::is_same_v<T, Others> || ...)};

template <typename, typename> struct is_subset_of;

template <typename... Ts, typename... Us>
struct is_subset_of<seq<Ts...>, seq<Us...>> {
  static constexpr bool value{(is_same_as_any_v<Ts, Us...> && ...)};
};

template <typename T, typename U>
constexpr bool is_subset_of_v{is_subset_of<T, U>::value};

and the latter as
template <typename...> struct args_are_unique;

template <typename T> struct args_are_unique<T> {
  static constexpr bool value{true};
};

template <typename T, typename... Ts> struct args_are_unique<seq<T, Ts...>> {
  static constexpr bool value{!is_same_as_any_v<T, Ts...> &&
                              args_are_unique<seq<Ts...>>::value};
};

template <typename... Ts>
constexpr bool args_are_unique_v{args_are_unique<Ts...>::value};

after which we can define the primary template as
namespace foo {
namespace detail {
using MyAllowedTypeSeq = seq<int, long, std::string>;  // ...
} // namespace detail

template <
    typename T, typename U, typename V, typename Seq = seq<T, U, V>,
    typename = std::enable_if_t<is_subset_of_v<Seq, detail::MyAllowedTypeSeq> &&
                                args_are_unique_v<Seq>>>
void doStuff(const T &param_a, const U &param_b, const V &param_c) {
  // do lots of stuff
}
} // namespace foo

and where we may and may not use the primary template overload as follows:
int main() {
  std::string s{"foo"};
  int i{42};
  long l{84};
  foo::doStuff(s, i, l); // OK
  foo::doStuff(s, l, i); // OK
  foo::doStuff(l, i, s); // OK
  foo::doStuff(l, s, i); // OK

  // uniqueness
  foo::doStuff(l, l, i); // Error: candidate template ignored

  // wrong type
  unsigned int ui{13};
  foo::doStuff(s, ui, l); // Error: candidate template ignored
}

If types need not actually be unique (it's somewhat unclear from the question) you can simply SFINAE-constrain the primary template only on the first is_subset_of_v trait:
template <
    typename T, typename U, typename V, typename Seq = seq<T, U, V>,
    typename = std::enable_if_t<is_subset_of_v<Seq, detail::MyAllowedTypeSeq>>>
void do(const T &param_a, const U &param_b, const V &param_c) {
  // do lots of stuff
}

A: Why not use the builder pattern here? You would create a foo_builder with various setXxx methods and a final build() to get the fully configured object.

A: Use a struct to hold all the params.
namespace foo
{
    struct do_params {
        int a;
        long b;
        std::string c;
    };
    void do(do_params params);
};