text:
Q: Algorithm for clustering pictures based on date taken Anyone know of an algorithm that will group pictures into events based on the date the picture was taken.  Obviously I can group by the date, but I'd like something a little more sophisticated that would(might) be able to group pictures spanning multiple days based on the frequency over a certain timespan. Consider the following groupings:

*

*1/2/2009 15 photos

*1/3/2009 20 photos

*1/4/2009 13 photos

*1/5/2009 19 photos

*1/15/2009 5 photos

Potentially these would be grouped into two groups:

*

*1/2/2009 -> 1/5/2009

*1/15/2009

Obviously there will be some tolerance(s) that need to be established.
Is there any well established way of doing this, other then inventing my own top/down approach?

A: You can apply pretty much any standard clustering technique to this, it's just a matter of defining your distance function correctly.  When you are making your matrix of distances between your photos you should consider a combination of physical distance between locations - if you have it - and temporal distance between their creation timestamps.  Normalise them and put them on separate dimensions and you may even just be able to take a regular euclidean distance.
Best of luck.

A: Just group the pictures that were taken on successive days (no days on which no pictures were taken) together.

A: You might try to dynamically calculate tolerance based on how many or how big (absolute or %) clusters you want to create.

A: To get a useful clustering of pictures according to date you require the following:
1) The number of clusters should be variable and not fixed a priori to the clustering
2) The diameter of each cluster should not exceed a specific amount.
The clustering algorithm that best satisfies both requirements is the QT (quality threshold) clustering algorithm.  From Wikipedia:

QT (quality threshold) clustering
  (Heyer, Kruglyak, Yooseph, 1999) is an
  alternative method of partitioning
  data, invented for gene clustering. It
  requires more computing power than
  k-means, but does not require
  specifying the number of clusters a
  priori, and always returns the same
  result when run several times.

Although it is mainly used for gene clustering I think it would fit in very well for what you need.

A: Try to detect the Gaps instead of the Clusters.


text:
Q: ubuntu linux install homestead conflict apache Laravel Homestead has a conflict with Apache server.
I installed Laravel Homestead on a Linux Ubuntu 15.04 virtual machine.  The Ubuntu distribution comes with Apache already installed.  The result is that when I try to load the "homestead.app" page in a browser, the Apache server returns the default page assigned by Apache server.
Please, how to I resolve this conflict, so that attempting to load "homestead.app" in a browser will return the default page for Laravel Homestead, instead of the Apache page?

redpajama_set_name: RedPajamaStackExchange


text:
Q: replace in javascript with case conversion I want to make the first character of every word in a string to uppercase.
i am referring to this article Replacement Text Case Conversion.
when i am running the regular expression ([a-zA-Z])([a-zA-Z](\s)) with the replacement text as \u$1\l$2 in my editor (sublime text) it works fine.
However, when i am trying to do the same in javascript using replace method as below, its giving syntax errors and hence fails.
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var rep = "\\u$1\\l$2";  // here it is giving error
var result = input.replace(regex,rep);

How to resolve this?
I know this problem can be solved using charAt() and toUppercase() method. but I want to do it using regex with replace. :)

A: JS regex engine does not support lower- and uppercasing operators \u and \l in the replacement patterns. Use a callback inside String#replace:

var input = "aZ";
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var result = input.replace(regex, function($0,$1,$2,$3) {
  return $1.toUpperCase() + $2.toLowerCase();
});
console.log(result);

Note that you can reduce your pattern to /([a-z])([a-z]*\s*)/gi.


text:
Q: How to make $lookup in aggregate return one object not an array when i call $lookup it return array but my requirment in only one object. is there any way where i'll get only one object. i have to put $lookup value in $group.
 Message.aggregate(

            {$match:{$or:[{"sender":userId},{"receiver":userId}]}},
            { $lookup: {from: 'users', localField: 'senderId', foreignField: '_id', as: 'from'} },

            {$sort:{messageTimeStamp:-1}},
            {
                $group:{"_id":
                {
                  "name":
                      }
                     $cond:[
                         {
                             $eq:["$receiver",userId]
                         },
                         {$concat:["$receiver"," and ","$sender"]},
                         {$concat:["$sender"," and ","$receiver"]}
                     ]
                  }
                },"message":{$first:"$message"},
                   "time":{$first:"$messageTimeStamp"},
                   "name":{$first:{
                     $cond:[
                         {
                              $eq:['$receiver',userId]
                        },
                         "$from"
                     ]
                  }},
                }
            },

A: The $unwind should help you.

Deconstructs an array field from the input documents to output a document for each element.

$unwind (aggregation)


text:
Q: Concatenación de String. Error al comparar cadenas Ante todo, Feliz año nuevo a todo el mundo. Espero que hayáis pasado una feliz nochevieja con los vuestros y que estéis todos bien de saludo.
Al grano. Tengo un método para llenar un ListArray con 50 elementos con datos "aleatorios" para probar cosas del ListArray. Me pasa una cosa muy curiosa. Este es el código del método que he implementado:
public void llenarArray () {               // Método llenarArray para probar cosas con datos predeterminados.

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

        aux = new Vehiculo();

        int digitosMatricula = 1234 + i;
        String letrasMatricula = "AAA";

        String matriculaTemporal = String.valueOf(digitosMatricula) + letrasMatricula;

        aux.setMarca("Prueba " + (1 + i));
        aux.setMatricula(matriculaTemporal);
        aux.setNumKms(1 + i);
        aux.setFechaMatriculacion(LocalDate.now());
        aux.setDescripcion("Rojo");
        aux.setPrecio(2000 + i);
        aux.setNombrePropietario("David Pozo Catalina");
        aux.setDniPropietario("71949635T");

        coche.add(aux);

    }           // FIN DE BUCLE FOR.

}       // FIN DEL MÉTODO llenarArray.

En los 50 elementos creados, crea matrículas consecutivas, p.e 1235AAA, 1236AAA... La cosa es que tengo otro método para buscar vehículo por matrícula:
public String buscaVehiculo (String matricula) {            // Método para buscar vehículos en el ArrayList Vehiculo pasando una matrícula.

    String datosVehiculo = "";                  // Variable de tipo String donde se almacenarán los datos del vehículo buscado.
    String auxMatricula = matricula;            // Variable de tipo String donde se almacenará la matrícula pedida por el usuario para buscar.

    for (int i = 0; i < coche.size(); i ++) {

        if (coche.get(i).getMatricula().equalsIgnoreCase(auxMatricula)) {
            datosVehiculo = "COCHE Nº " + (i + 1) + "\n" + "\nMarca: " + coche.get(i).getMarca() + "\nMatrícula: " + coche.get(i).getMatricula()
                + "\nKilómetros: " + coche.get(i).getNumKms() + "\nFecha de Matriculación: " + coche.get(i).getFechaMatriculacion() + "\nDescripción: " +
                coche.get(i).getDescripcion() + "\nPrecio: " + coche.get(i).getPrecio() + "€" + "\nPropietario: " + coche.get(i).getNombrePropietario() +
                "\nDNI Propietario: " + coche.get(i).getDniPropietario();
        } else {
            datosVehiculo = "Esa matrícula no existe.";
        }
    }

    return datosVehiculo;

}       // FIN DEL MÉTODO buscaVehiculo.

Y el resultado al comparar la matrícula pedida en el método buscaVehiculo con una de las 50 almacenadas es: "Esa matrícula no existe".
Pero cuando meto uno a uno los datos del vehículo con un JOptionPane.showInputDialog, el método buscaVehiculo SÍ QUE FUNCIONA. Y no se cual puede ser la razón porque escupo por consola alguna matrícula generada por el método llenarArray y luego la escribo tal como aparece en el método buscaVehiculo y no me encuentra el vehículo. Pero tengo otro método que se llama listaVehiculo que me saca por pantalla el contenido del ListArray y SÍ QUE APARECE.
No entiendo que ocurre.
Un saludo y gracias.


text:
Q: Sort a 2D array columns by first row in JavaScript Given a 2D array like bellow:
[['c', 'd', 'b', 'a'],
 ['1', '5', '7', '8'],
 ['3', '7', '4', '9']];

What could be the best way to sort the columns by first row values:
[['a', 'b', 'c', 'd'],
 ['8', '7', '1', '5'],
 ['9', '4', '3', '7']];

The values on first row are expected to be unique.

A: One way is to transpose the matrix, then sort it and transpose back:

let arr =
[['c', 'd', 'b', 'a'],
 ['1', '5', '7', '8'],
 ['3', '7', '4', '9']];

arr = arr[0].map((_, colIndex) => arr.map(row => row[colIndex]));

arr.sort((a,b) => a[0] > b[0]);

arr = arr[0].map((_, colIndex) => arr.map(row => row[colIndex]));

console.log(arr);

A: First, Sort the first column array with its index.
Then, whole array with its index.
const res = [
  ["c", "d", "b", "a"],
  ["1", "5", "7", "8"],
  ["3", "7", "4", "9"],
];
const sort2dArrayColumsByFirstRow = (array) => {
  if (!Array.isArray(array)) return [];
  const sortedFirstRow = array[0]
    .map((item, i) => ({ v: item, i: i }))
    .sort((a, b) => {
      return a.v < b.v ? -1 : 1;
    });
  return array.map((row) => row.map((_, i) => row[sortedFirstRow[i].i]));
};

console.log(sort2dArrayColumsByFirstRow(res));

A:

const input = [
  ['c', 'd', 'b', 'a'],
  ['1', '5', '7', '8'],
  ['3', '7', '4', '9']
];

const temp = input[0].map(
  (letter, index) => [letter, input[1][index], input[2][index]]
)

temp.sort(([a], [b]) => a.localeCompare(b))

const result = temp.reduce((acc, cur) => {
  cur.forEach((x, i) => acc[i].push(x));
  return acc;
}, [[],[],[]]) ;

console.log(result)

Or you can remember the steps you followed to sort the first array and apply them to the rest.

const arrayLoop = arr => {
  let i = 0;
  return () => arr[i++ % arr.length]
}

const sortAndRememberSteps = arr => {
  const steps = [];
  arr.sort((a, b) => { const step = a.localeCompare(b); steps.push(step); return step });
  return steps;
}

const input = [
  ['c', 'd', 'b', 'a'],
  ['1', '5', '7', '8'],
  ['3', '7', '4', '9']
];

const [arrayToSort, ...rest] = input

const steps = sortAndRememberSteps(arrayToSort);

rest.forEach(arr => arr.sort(arrayLoop(steps)))

console.log(input)


text:
Q: Accessing models from within the lib directory in a Rails 3 project I have a file in the lib directory that uses some constants defined in a model, like:
class User < ActiveRecord::Base
   MAX_EMAIL_ADDRESS_LENGTH = 255
end

and then I have in lib/foo.rb
module Foo
  LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(User::MAX_EMAIL_ADDRESS_LENGTH, "a")
end

It fails due to not finding the class User. How can I load User before that file on lib?
I'm loading that file by having this in my application.rb:
config.autoload_paths += %W(#{config.root}/lib)

A: I know this is a old question but I've just faced the same problem and after some searches, I found a solution so I think it worth to share it.
I wanted to use a model "Foo" in one required files located in my /lib directory. First, I did this and it didn't work :
# in my rake file
task :foo_task do
  require /some_path/lib/bar.rb
end

# in /lib/bar.rb
puts "Foo = #{Foo.count} "

# => uninitialized constant Foo

After some searches, I found that to access models in my lib's files, I need to specify the environment in my task. So I just added this to my task declaration :
task :foo_task => [:environment] do

Now, when I call my task, it correctly puts the number of Foo :
# => Foo = 6

A: The first part was done right:
config.autoload_paths += %W(#{config.root}/lib)

Next, it is important, module
module Foo
  ...
end

must be placed into
lib/foo.rb

file.
And then, it can be included into application code.
class Comment < ActiveRecord::Base
  include Foo
  ...
end

If file foo.rb from lib directory is not intended to be included (however it is probably a wrong way), then to use Rails models and other stuff inside this code you should put this into foo.rb:
require_relative "../config/environment.rb"

A: The solution was, that my file in /lib was actually being required by a rake file, and it seems rake files are loaded before the whole auto-load system is setup by Rails, so it couldn't find the model. After I remove the require from the .rake file, everything started working.

A: By default, YourApplicationNameHere::Application.autoload_paths is []. I (purely for organizational reasons) add a glob for my app/models directory too.
config.autoload_paths += Dir["#{Rails.root}/app/models/**/"]
config.autoload_paths += Dir["#{config.root}/lib"]

With this setup I'm able to do what you're asking in the Question without trouble. This should benefit you as well, telling Rails where to look if it can't find the User model from within your lib/ module's instantiation.
Edit
Specifying the exact error message in your question would have helped too.
uninitialized constant Foo::User

means Ruby/Rails is looking for User within the Foo namespace. Prefix User with :: to force the lookup to the global namespace.
module Foo
  LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(::User::MAX_EMAIL_ADDRESS_LENGTH, "a")
end

A: It appears that your class User has not be instantiated, which seems unusual, unless you have 'user.rb' in a location other than 'models'.  It is often the case that classes aren't loaded in development unless they are specifically in that directory, but one solution I use is this line that you could put just within your code that you expect to be called prior to the offending line you have..
Rails.application.eager_load! if Rails.env == "development"

The conditional part is probably unnecessary, but I include it just to be certain its effect only occurs in development.


text:
Q: Print C++ array in Objective-C "NSLog" I'm trying to output and C++ Array (int inverse[3]) using NSLog, but If I try this way:
NSLog([NSString stringWithFormat:@"%d", inverse]);

It just dont work, But if I try like this:
NSLog([NSString stringWithFormat:@"%d", inverse[0]]);

I get the right output.
My objective is to get the whole array outputed.
Any ideas? Thanks

A: Use a for loop to print all the values.
for (int i=0; i<3; i++) {
    NSLog(@"%i", inverse[i]);
}

or:
NSLog(@"%i, %i, %i", inverse[0], inverse[1], inverse[2]);

A: There is no need need to convert for string format conversion. You can print like these -
for ( int i=0; i<3; ++i )
    NSLog(@"%i", inverse[i]);


text:
Q: Schedule funtion to Pull CSV file to database Sorry, I have not done any coding in WEB API so I don't have any sample to share here.
But I just wanted to know that, how we can schedule a task on server for WEB API to read a csv file after every 15 or 30 mins.
From client we are successfully able to push csv to my ftp server where my application is located. But how to retrieve the data from csv after every fixed interval?

A: WebAPI is the wrong tool for the job.
You can certainly push (or upload specifically) CSV data to a WebAPI method, and that method can do whatever you need to do with that data.  But WebAPI doesn't run on a timer.  It's not going to periodically look for data to process, you have to send it that data.
A web application is a request/response system.  In order to do something, you have to send it a request.
For an application that periodically runs on a timer, consider a Windows Service or even simply a Console Application which is scheduled to run with some job scheduler (Windows Task Scheduler, cron, etc.).  That would run periodically without the need for input or a user interface at all.
Now, if the code you need to use is in the WebAPI application already, that's ok.  You can refactor that code into a separate Class Library in the same solution as the WebAPI application.  Then add the new application (Windows Service or Console Application) to that solution and reference that same Class Library.  Both applications can share the same supporting code.  Indeed, the application layer should be as thin as possible over a set of common business logic that can be shared by multiple applications.


text:
Q: Excel from Python (openpyxl) Issue I'm new to programming and I'm trying to make a small app where I'll need to copy and paste values to a "stylished" excel woorksheet but when I was testing the first commands, I ran to the first issue:
When I get a cell value from "worksheet1" and paste it into an empty cell from the same worksheet ("worksheet1"), the worksheet stylish kinda messes up (just border cells disapearing), and thats not good, because that table is going to be printed and I need those border cells to stay.
I made a video with the issue: https://www.youtube.com/watch?v=DCZAwYp4zvE
I've tried:

*

*Changing the files directory

*Copying the excel file

*Making the same but in the other woorksheets

*I downloaded the original excel from internet so I though it was some incompatibility issue. I even created a new workbook and duplicated from 0 the original workbook (borders, same font, font size, etc), but didnt fix it.

Code:
from openpyxl import load_workbook

file="Test.xlsx"

wb = load_workbook(file)
ws = wb["COMPRA_DIRECTA"]

ws["A80"] = ws["A13"].value

wb.save(file)

Link to the original excel and the script: Link
Im using:
Excel 2016
Openpyxl 2.5.14
Windows

A: I have used the encoding and it is working fine for me. I have installed Openpyxl 2.6.4 and using LibreOffice Calc on Ubuntu 18.04.
Try this code, it will surely work for you:
from openpyxl import load_workbook
file="Test.xlsx"
wb = load_workbook(file)

# grab the active worksheet
ws = wb["COMPRA_DIRECTA"]

# Data can be assigned directly to cells
ws['A80'] = ws["A13"].value.encode("utf8")

# Save the file
wb.save("sample.xlsx")


text:
Q: Dell Inspiron 5523 does not boot ubuntu i have a problem installing Ubuntu 18.04.2 alongside with windows 10 after boot and choice try ubuntu or install ubuntu gives me a blank screen.
i try many solutions
change IDE ATA/ATAPI Controllers to AHCI
disable Secure Boot
boot UEFI
add no splash, nomodeset, and nouveau.modeset=0 to grub
Processor : Intel(R) Core(TM) i7-3537U CPU @ 2.00GHz
Display Adapters : Intel(R) HD Graphics 4000 + NVIDIA GeForce GT 630M
IDE ATA/ATAPI Controllers : Standard SATA AHCI Controller
best regards

A: I don't know if this helps you out but if you log in as root in emergency mode and try typing journalctl -b you get the logs of the boot, i don't know if ubuntu shows them on startup, Debian does.. You should look at these logs to determine where is the problem.
Otherwise try reinstalling, maybe the installation is corrupted it happens with linux, sometimes you have to reinstall to get everything working. Back up your data!


text:
Q: How to prevent accidental config changes made directly in Production? Too many times we've had developers (as well as our release manager, who also dev's) inadvertently make a change directly in Production because they had the Prod org open alongside their dev org in the browser. It took us weeks to discover several validation rules had been unintentionally deactivated. Mere training/vigilance isn't good enough to prevent this behavior reliably.
What is a good, low-cost (preferably automated) way to guard against the human errors of making changes directly in Prod?
We're a relatively small team, so solutions that are costly to implement aren't viable for us.
Solutions under consideration: (don't like any of these)

*

*Change the Themes & Branding color in every sandbox after creation/refresh (Con: don't see a way to automate this)

*Retroactively scan for accidental changes by periodically retrieving "all" metadata from Prod to identify diffs in source control that didn't go through the change control process (Con: it's retroactive [not proactive], it's a manual step, and it would involve adding metadata types to source control that we don't currently track)

*Remove admin privileges from individual developers' user accounts in Production, using a single service account User for deployments (Con: involves extra license $, post-sandbox-refresh script to grant devs admin access in LLEs)

A:
We're a relatively small team, so solutions that are costly to
implement aren't viable for us.

It's up to your team to decide if the cost is worth removing the risk that accidently doing something in production could have. You seem to suggest it's happening often so you need to implement a solution, but I'd question why it isn't getting better on its own.
I certainly have done this accidently, but can't say it has happened more than a couple times. In those incidences, I do think the working norms of the team contributed to it occuring

*

*Sometimes doing changes directly in production (ex. oh, it's a simple change)

*Not having another person test every single change before it goes to production

*Not documenting all changes or what is expected to be changed

Based on your example, I'd press why it took weeks to realize a validation rule was deactivated in production instead of, presumably, a testing environment? If the validation rule was deactivated in production (instead of a QA org), then someone checking the work should have caught it pretty quickly. You may think it's overkill for making simple changes, but your specific issue is the exact reason you always have someone else other than the dev check their work...because of human error. It's not atypical to see mistakes occur on the simplest of changes

*

*Misspelling label changes

*Wrong order of picklist values

*Page Layout order

No matter how simple or complex the change, someone else should be checking the work against what the expected change should be (acceptance criteria).

Otherwise, changing how you work could help to minimize how someone may have production open or accidently click on the wrong domain link:

*

*Working in more scratch orgs (if possible)

*Using IDE as one-stop shop (ex. open org from VS Code)

*Removing solutions that may accidently redirect to production (links/references in hyperlinks, emails, etc in a sandbox).

That last one can be quite tricky if you, while working or testing something, get redirected to production without realizing it. That doesn't sound like what happened for you, but something to consider.
For Admins, you could also take the following approaches:

*

*Set one person as rotating "production support" and have that person only focus on production for that day, week, etc. Limit the occurrence of them having to be in production and doing work in a sandbox.

*What permissions do they actually need? What changes are they expected to make? Could they get away with limited permissions that would still allow them to make dashboards and reports?

*Going off the above and assuming they do need to make setup changes in sandboxes, you could take your final solution (post-sandbox refresh script) to assign a permission set to your Admin users (add them to a public group) that will give them the "setup" permissions needed just for sandboxes. It's kind of a half-measure, but this is assuming Admins are more at risk for this type of error because they have to be in production at times and they can't adopt all the benefits of the developer workflow mentioned above.

A: I've found a Chrome Extension that changes the color of Salesforce's logo on the tabs and adds a thin line at the top of the page in the same color is all I needed to stop this issue. I use Salesforce Organizer (https://organizer.solutions/donate.html)
PROD is always red. From light to dark colors, I move from sandbox to develop to stage.

Since implementing this two or so years ago, I have not had any issues (knock wood)...
If your organization locks down Extensions, then I would put in place a dev ops tool like GearSet, https://gearset.com/.  Not only will it allow fast deploys to PROD from various places it can track metadata in PROD and let you know if anything has changed as often as you like.
note: I'm involved in neither company, though I did get swag (a hat, candy, etc) from GearSet for attending a focus group. :-)

A: In our department we wanted to increase security awareness. One point of attention was that laptops may only be left unattended with a locked screen.
If you found an unattended laptop with an unlocked screen, you were allowed to send a mail from this person's Outlook to all department members, stating "Tomorrow I will bring cake for everyone". And then lock that laptop (Windows-L key).
This has proven to be very effective. For one or two persons it was difficult to make a habit out of locking their screens when leaving the laptop, but after a few weeks it was difficult to find unlocked, unattended laptops.
People were motivated to lock their own laptop as well as to watch out for unlocked laptops of colleagues.


text:
Q: Como obtener el id del usuario logeado en spring boot Estaba siguiendo un tutorial de spring security utilizando angular para el frontend, pero al momento de tratar de obtener información del usuario en la que se necesite el id, como por ejemplo al momento de obtener una tarjeta que se relacione con el usuario a partir del id de este ultimo, lo que hacen es guardar los datos del usuario en el sessionStorage para luego utilizar el dato del id para hacer la petición, pero el problema esta en que si dos usuarios tienen los mismos roles, por ejemplo el rol ROLE_USER, si cambian ese id del sessionStorage pueden obtener los datos de otro usuario.
Este es uno de los controllers donde se necesitaba el id
@PostMapping("/myAccount")
public Accounts getAccountDetails(@RequestBody Customer customer) {

    Accounts accounts = accountsRepository.findByCustomerId(customer.getId());
    if (accounts != null ) {
        return accounts;
    }else {
        return null;
    }
}

Para intentar resolver este problema he intentado varias cosas, primero utilize la anotacion @CurrentSecurityContext para obtener el username y usar el customerRepository para obtener el id y poder continuar con la request.
@PostMapping("/myAccount")
public Accounts getAccountDetails(@CurrentSecurityContext(expression = "authentication") Authentication authentication,
        @RequestBody Customer customer) {

    List<Customer> customer2= customerRepository.findByEmail(authentication.getPrincipal().toString());
    if (customer2.size()>0) {
        Accounts accounts = accountsRepository.findByCustomerId(customer2.get(0).getId());
        if (accounts != null) {
            return accounts;
        }
    }
    return null;
}

Luego intente otras cosas, como cambiar el valor del principal a una implementación del userDetails que tiene una variable para que cuando al obtener el principal me devuelva el objeto y de esa manera obtener el id que necesito.
@PostMapping("/myAccount")
public Accounts getAccountDetails(
        @CurrentSecurityContext(expression = "authentication") Authentication principal) {
    int id = 0;
    if (principal.getPrincipal() instanceof SecurityCustomer) {
        SecurityCustomer securityCustomer = (SecurityCustomer) principal.getPrincipal();
        id = securityCustomer.getId();
    }

    Accounts accounts = accountsRepository.findByCustomerId(id);
    if (accounts != null) {
        return accounts;
    } else {
        return null;
    }
}

Lo ultimo que pensé, pero no he implementado, es pasar el dato del id a través del jwt y utilizarlo siempre que lo necesite para alguna request.
Pero al preguntarle a la persona que creo el tutorial acerca de esto me dice que siempre es bueno pedir el id habiéndolo guardado en el frontend para que no exista un gran acoplamiento entre el backend y el frontend y que si se cambia de backend en algún momento todo siga funcionando bien.
Talvez la solución pueda darse desde el frontend y los datos del usuario pueda guardarlos de una forma mas segura donde no sean modificables por el usuario.
No se si existe alguna solución simple para esta cuestión, pero he estado intentándolo solucionar de buena manera durante un par de días porque las soluciones que he obtenido no me convencen y apreciaría la ayuda.

A: Usar un token JWT añadido en un header es una buena solución:

*

*la información para identificar el usuario va en ese token, así como cualquier información que necesites en el frontend (los roles asociados, por ejemplo). De ese modo el usuario no necesita tener el id como algo visible y nadie puede suplantarle.

*los usuarios no pueden trastear con el mismo porque va firmado: pueden decodificarlo pero no modificarlo.
Sobre la afirmación de que es bueno que el usuario tenga en su lado el ID que tiene asignado, no estoy totalmente de acuerdo, hay aplicaciones que no muestran ese valor nunca y dar al usuario un sustituto temporal:

*

*El usuario con identificador A inicia sesión: se genera un valor pseudoaleatorio (por ejemplo un UUID) y se guarda en un "diccionario" en backend como "Id de sesión".

*Ese id se devuelve al usuario dentro de un token JWT con fecha de caducidad.

*El id de sesión se usa para cada llamada identificando al usuario, añadiéndolo también en la respuesta. De ese modo se puede actualizar automáticamente cuando caduque simplemente añadiendo el nuevo en una de las respuestas.

De ese modo nadie puede "robar" al usuario su ID, como mucho se le puede robar la sesión.
Además, el usuario no tiene pistas de cómo es su ID, con lo que no puede intentar acceder como otro usuario adivinando como generar otro ID válido o intentar calcular el número de usuarios (si el ID es un número autoincrementado)


text:
Q: Spring MVC - Ajax call returns an HTTP Status 415 – Unsupported Media Type I would like to submit form data to the controller but even though I see in HTTP request that the parameters are being send I get a 415 HTTP error.
Here is my JQuery/AJAX call to the controller:
$.ajax({
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            dataType: "json",
            type: 'POST',
            url: "calculate",
            data : JSON.stringify(data),
            success : function(response){
                alert("OK");
            },
            error : function(){
                alert("Error");
            }
        });

And here is my controller:
@RequestMapping(value = "calculate", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody void calculate (@RequestBody QueryElements queryElements, HttpServletRequest request) throws IOException {
    System.out.println("OK");
}

Now what happens is that if I remove the @RequestBody in the controller I see in debug that the controller is being called, but obviously I need to keep the annotation.
Here is the HTTP request:
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:593
Content-Type:application/json; charset=UTF-8
Cookie:JSESSIONID=AD8FEA2E46709554189D687A7C65929D
Host:localhost:9082
Origin:http://localhost:9082
Referer:http://localhost:9082/cheexport/export?
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
X-Requested-With:XMLHttpRequest
{"bindListregInc":"","bindListregEsc":"","bindListprovInc":"","bindListprovEsc":"","bindListcomInc":"","bindListcomEsc":"","bindListcapInc":"","bindListcapEsc":"","bindListsitInc":"","bindListsitEsc":"","stringaInclusa":"","stringaEsclusa":"","consenso":"","clausola1c":"","sponsor":"","bindListcontrInc":"","bindListcontrEsc":"","bindListcliInc":"","bindListcliEsc":"","nomeContratto":"","customQuote":"","campiHeaderHidden":""}

A: Perhaps you have a void calculate method when you expect a JSON.
Try to return something:
@RequestMapping(value = "calculate", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody ResponseEntity<?> calculate (@RequestBody QueryElements queryElements, HttpServletRequest request) throws IOException {
    return ResponseEntity.ok("OK");
}

A: At your @RequestMapping annotation you should add consumes="application/json"
Like this:
    @RequestMapping(value = "someUrl", consumes = {MediaType.APPLICATION_JSON_VALUE})
This going to tell Spring that Method accepts applicatin/json requests.
Or you could try to use @RestController instead of @Controller
Also try to add "contentType" to the JS code.
    $.ajax({
        url: "/api1/tax",
        data: JSON.stringify(requestData),
        type: method,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            setTimeout(reloadTable, globalTimeout);
        },
        error: function (error) {
            console.log(error);
        }
    });


text:
Q: get last inserted/added item from QMap I have following data structure:
typedef QMap<QPair<QString, QString>, QString> UeTypeLoggedUsersData;

The purpose of this data structure is to store logged users information.
Now, I can insert data with insert(), remove data with remove(), iterate over it with iterator and it works perfectly. But, how do I get last added record from QMap? I've been reading docs but I simply cannot find wanted information. The data is orders by the key, here is sample debug output:
"c85bc9f7-704f-418e-98af-a1528622dd42" "1" ""
"c85bc9f7-704f-418e-98af-a1528622dd42" "10" ""
"c85bc9f7-704f-418e-98af-a1528622dd42" "12" ""
"c85bc9f7-704f-418e-98af-a1528622dd42" "4" ""
"c85bc9f7-704f-418e-98af-a1528622dd42" "7" ""
"c85bc9f7-704f-418e-98af-a1528622dd42" "9" ""

However, from debug process I know (in this situation), the record
"c85bc9f7-704f-418e-98af-a1528622dd42" "4" ""
was last added to data structure. How do I, as I asked before, get last added record in this data structure?

A: In my opinion, you wouldn't need such complex and potentially hard to manage data structure. You could define your own class called UserData and then in order to store them you can define a QList<UserData>.
I think you would need a bag of user data, not an ordered list. If so, QList exactly fits your requirement.

*

*QList::first() returns first item.

*QList::last() returns last item.

Avoiding duplicates
To avoid duplicate entries, I suggest that in your UserData class, overload the == operator so that semantically defines which two instances of this class are equal. Afterward, you can use contains method of QList to check whether an item already exists in the list or not.
class UserData {
    public:
        bool operator == (const UserData &another){
            return this.key == another.key;
        }

    private:
        QString key;
}

Now, you can check for duplicates like this:
if(!mList.constains(userData)){
    mList.append(userData);
}

A: Actually you can't.
QMap in Qt implementation of red-black-tree-based dictionary. Such as hash-table where key, value pairs stores arbitrarily sorted by keys. So it provides fast lookup of the value associated with a key. It doesn't store/contains any internal information about values inserted by key in time manner.
If you need such information you should use more complex structure for this. For example:
typedef QHash<QString, QStringList> UeTypeLoggedUsersData;

So you can use "c85bc9f7-704f-418e-98af-a1528622dd42" as key. As i see you have regular data structure, so you can store value as key subpart and data as values of QStringList:
QString key = "c85bc9f7-704f-418e-98af-a1528622dd42";
if (myHash.contains(key)) {
    myHash[key] << "10";
    myHash[key] << "some data";
} else {
    QStringList usersData;
    usersData << "10"
    usersData << "some data"
    myHash[key] = usersData;
}

So it more complex but you always can get the latest added value.

A: QMap is a sorted container - new entries are not inserted chronologically but based on the key. So, last() would not refer to the last inserted but to the element with the "largest" key.
The simplest way would be to keep track of the last inserted element manually, insert() returns an iterator, so you can make a wrapper around QMap that stores that iterator after each insert.


text:
Q: "most" means "very" in a formal setting From the Cambridge Dictionary

Which aspects of the job do you most enjoy?

"most" means "very" in a formal setting.
so, the quotation is appropriate for a job interview but might not be suitable for a more casual situation, like new friends in a pub. For that case, which word could be the alternative?
Is my understanding correct?

A: There are two usages of "most" which can be confused.
"This job is the most exciting (job) ever!"
This uses "most" in its superlative meaning: "much, more, most".
The other usage is the one you are thinking of:
"I find this job most exciting!"
which does indeed mean: "I find this job very exciting!"
How do you tell which one is being used?
If you see "most" without it being "the most" and without it being given in comparison with something else, it is most likely to mean "very".
Exercise for the student: at the end of the sentence above, which usage of "most" is being used? Be warned: it is subtle!
Finally, to answer your original question:
"Which aspects of the job do you most enjoy?"
uses "most" in its superlative meaning: "the most enjoyable aspects of the job."


text:
Q: Find and Group All Records on the Same Month, 1 year apart I'm trying to group some records by First Name, Last Name, and Date by Month. Here is my query for grouping by first/last name so far:
SELECT `fundraiser_report`.`first_name` AS `first_name`,
       `fundraiser_report`.`last_name`  AS `last_name`,
       Count(*)                         AS `count`
FROM   `fundraiser_report`
GROUP  BY `fundraiser_report`.`first_name`,
          `fundraiser_report`.`last_name`
ORDER  BY `fundraiser_report`.`first_name` ASC,
          `fundraiser_report`.`last_name` ASC

Here is an example of what the data would look like:
first_name|last_name|end_date
Hunter    |Cole     |11/37/2019
Hunter    |Cole     |11/20/2018
Hunter    |Cole     |11/13/2020
Andrew    |Barn     |11/37/2019
Andrew    |Barn     |11/20/2018
Andrew    |Barn     |11/13/2020
Anthony   |Jones    |3/11/2010

All 7 of these records would need to be returned in a format like this:
Hunter |Cole  |3
Andrew |Barn  |3
Anthony|Jones |1

A: Please use the equivalent of EXTRACT(month FROM sysdate) in mysql
(edited, replaced sysdate with end_date)
SELECT fundraiser_report.first_name AS first_name,
       fundraiser_report.last_name  AS last_name,
       EXTRACT(month FROM end_date) AS month
       Count(*) AS count
FROM   fundraiser_report
GROUP  BY fundraiser_report.first_name,
          fundraiser_report.last_name,
          EXTRACT(month FROM end_date)
ORDER  BY fundraiser_report.first_name ASC,
          fundraiser_report.last_name ASC


text:
Q: Web Search API for 25000-50000 Entries I have 20000-50000 entries in an excel file. One column contains the name of that company. Ideally, I would like search the name of that company, and whatever is the first result, I would select the URL associated with it. I am aware that Google (which my ideal choice) provides a AJAX Search API. However, it also has a 1000 search limit per registrant. Is there a way to get over 20000 searches without making 20 accounts with Google, or is there an alternative engine I could use?
Any alternative ways of approaching this problem are also welcome (i.e. WhoIs look-ups).

A: Google AJAX Search has no such limit of 1000. Yahoo Search does. Google AJAX Search limits you to getting 64 results per search but otherwise has no limit.
From Google AJAX Search API - Class Reference:

Note: The maximum number of results
  pages is based on the type of
  searcher. Local search supports 4
  pages (or a maximum of 32 total
  results) and the other searchers
  (Blog, Book, Image, News, Patent,
  Video, and Web) support 8 pages (for a
  maximum total of 64 results).

A: Approaches that avoid using an external search service ...
Approach 1 - put the information content of the XML into a database and search using SQL/JDBC.  Variations of the same using Hibernate, etc.
Approach 2 - read the XML file as an in-memory data structure as a Java collection, and do the searching programmatically.  This will use a bit of memory depending on how much information is in the XML file, but you only need to figure out how to parse / load the XML, and access the collection.
However, it would help if you explained the context in which you are trying to do this.  Is it a browser plugin?  The client side of a web app?  The server side?  A desktop application?


text:
Q: ReactNative; How to call new component to open new screen? I want to open new screen from Nextpage.js ,after "onPress" worked, everything still same, NextPage not show on screen but not error. How should I do?
import NextPage from './NextPage';

function onClick() {
   <NextPage/>
}

<TouchableHighlight onPress = {onClick}>
        <View style={[styles.itemContainer, { backgroundColor: item.code }]}>
          <Text style={styles.itemName}>{item.name}</Text>
          <Text style={styles.itemCode}>{item.code}</Text>
        </View>
</TouchableHighlight>

A: you can't call a screen like that. If you want to navigate to any other screen in your case NextPage, you should define it in your navigation stack first. After that, you can call function navigation.navigate("NextPage") to navigate to next page.
Navigator file:
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import * as React from 'react';
import Home from '../screens/Home';
import Next from '../screens/Next';

const Stack = createStackNavigator();

function App({initialRouteName = 'Home'}) {
  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Home"
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Next" component={Next} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Suppose you are navigating from Home to NextPage
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

export default function Home(props) {
  function onClick() {
    props.navigation.navigate('NextPage');
  }

  return (
    <TouchableHighlight onPress={onClick}>
      <View style={[styles.itemContainer, {backgroundColor: item.code}]}>
        <Text style={styles.itemName}>{item.name}</Text>
        <Text style={styles.itemCode}>{item.code}</Text>
      </View>
    </TouchableHighlight>
  );
}

const styles = StyleSheet.create({});


text:
Q: Get Eticket and segment from PNR When I get PNR from consolidator, I want to use API to get eticket and segment.
Please advise API to do that
Thank you

A: You need to use Retrieve Itinerary (https://developer.sabre.com/docs/soap_apis/management/itinerary/Retrieve_Itinerary). It gives you the ticket number/s, corresponding segments and also refrences in case you price EMD-A to those tickets


text:
Q: Does one definition rule apply to dynamically loading shared libraries at runtime? If I load a dll or so library at runtime using dlopen() on unix or LoadLibrary() on windows, do i need to ensure that the symbols in the library do not have the same names as symbols in my program? Also is it possible to load multiple shared libraries that define the same functions?
Edit: I am specifically asking about runtime dynamic linking.

A: Objects in a shared library loaded by dlopen do not appear in the namespace of the main program.  You need to call dlsym with the name of the object as a string to get a pointer to it.
Using your example of having two libraries dynamically loaded having a global with the same name:
void *lib1 = dlopen("lib1.so", RTLD_LAZY);
int *lib1_global1 = dlsym(lib1, "global1");

void *lib2 = dlopen("lib2.so", RTLD_LAZY);
int *lib2_global1 = dlsym(lib2, "global1");

Here, both lib1.so and lib2.so contain a global variable of type int named global1.  Because the dlsym function returns a pointer to the variable/function in question, you can handle this case with no conflict.


text:
Q: GO: manipulating random generated float64 I was wondering if we can specify to the random generator to how many numbers should be generated after the point decimal?
Example of default behaviour:
fmt.Println(rand.float64())

Would print out the number 0.6046602879796196
Desired behaviour:
fmt.Println(rand.float64(4))

Would then print out the number 0.6047.
Does this functionality already exist in GO or would I have to implement it myself ?
Thank you!

A: It sounds like only the string representation is important to you, and the fmt package does provide that for you:
fmt.Printf("%1.4f", rand.Float64())

So yes, you would still need to wrap this call to specify the number of digits after the decimal point.
func RandomDigits(number int) string {
    return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
}

A: I don't know of such function, however it is easy to implement by yourself (play):
// Truncate the number x to n decimal places
//
// +- Inf -> +- Inf; NaN -> NaN
func truncate(x float64, n int) float64 {
    return math.Trunc(x * math.Pow(10, float64(n))) * math.Pow(10, -float64(n))
}

Shift the number n decimal places to the left, truncate decimal places, shift the number n places to the right.
In case you want to present your number to the user then you will, at one point, convert the number
to a string. When you do that, you should not use this method and instead use string formatting as pointed
out by Tyson. For example, as floating point numbers are imprecise there might be rounding errors:
truncate(0.9405090880450124,3) // 0.9400000000000001


text:
Q: Manual JSON array with Coldfusion - works until I replace with Dynamic Values For reasons beyond my control, I need to manually create a JSON structure to post to an API.  I've done so as follows;
<cfsavecontent variable="JSONData">
{"data":[{"Last_Name":"#lastname#",
"First_Name":"#firstname#",
"$gclid":"#zc_gad#",
"Email":"#email#",
"Phone":"#phonenumber#",
"Lead_Source":"PPC",
"Build_Cost_text":"#buildcost#",
"Estimated_Sales_Value_text":"#estsalesvalue#",
"Stage_of_Build_Work":"#stageofbuildingwork#",
"Work_Starting_Date_text":"#workstartdate#",
"No_Of_Units_text":"#numofunits#",
"Address_of_Development":"#devaddress#",
"Do_you_require_a_quote_for_building_control1":"#bcquote#",
"Gross_Floor_Area_text":"#grossfloorarea#",
"Development_Use":"#devuse#",
"Please_share_any_additional_information":"#additionalinfo#",
"Product_Type":"Warranty","Company":"#company#"}]}
</cfsavecontent>

(The actual code doesn't have linebreaks - it's just a bit harder to read!)
I then use that to post to the API;
<cfhttp method="POST" url="APIurl" result="postresult">
<cfhttpparam type="header" name="Authorization" value="oauthtokenvalue">
<cfhttpparam type="header" name="content-type" value="application/json" />
<cfhttpparam type="body" value="#JSONData#" />
</cfhttp>

If, instead of populating it with dynamic values, eg "#lastname#" is hardcoded as "Smith", it works just fine.
However, as soon as I add the dynamic tags, I get the following error;
Can't cast Complex Object Type Struct to String

Changing the cfhttpparam (for the sake of testing) to;
<cfhttpparam type="body" value="#SerializeJSON(JSONData)#" />

Makes no difference either.
If it matters, above this is the cfquery that retrieves the record(s), then this is wrapped in a cfoutput query - and aside from the dynamic references, that's the only difference between the 'working' code and non-working code.

A: SaveContent saves whatever you are outputting to a string. The code you are showing may not be outputting anything. Instead, it's possible that you are creating a struct. To make sure you are outputting the JSON, add a  tag as follows:
<cfsavecontent variable="JSONData">
<cfoutput>
{"data":[{"Last_Name":"#lastname#",
"First_Name":"#firstname#",
...
}]
}
</cfoutput>
</cfsavecontent>

But, a better way to do this would be to use SerializeJSON(). I can't think of a reason why you wouldn't be able use it. For example:
<cfscript>
myQuery = queryExecute(...);
myData = {
    "data": []
}
for (record in myQuery) {
    arrayAppend(myData.data, {
        "last_Name": record.lastName,
        "First_Name": record.firstName
        ...
    });
}
WriteOutput(SerializeJSON(myData));
</cfscript>

Either way, you need to view your string to debug, which should give you a better idea of what the problem is. I would add a <cfdump var="#jsonData#"> after you've created your string to see what it looks like. You could also output
#EncodeForHTML(jsonData)#
 or
#HTMLEditFormat(jsonData)#
 to see it.
But the bigger question is why you need to build the json manually. I know you say it's for reasons beyond your control. Perhaps you're using an old version of ColdFusion?? It doesn't matter what version of CFML you're using, you should still be able to loop over a query and append a struct of the record's values to an array, and then output them using SerializeJSON(). If your issue is an old version of SerializeJSON() that is buggy, there are UDFs out there that work around some of the old problems with SerializeJSON(), or you could write your own that would be better than building a string.


text:
Q: Wrong project in Google SDK I want to build a TTS application and I am using the Google TTS engine. However, when trying the examples such as
curl -H "Authorization: Bearer "$(gcloud auth print-access-token) -H "Content-Type: application/json; charset=utf-8" --data "{
  'input':{
    'text':'I\'ve added the event to your calendar.'
  },
  'voice':{
    'languageCode':'en-gb',
    'name':'en-GB-Standard-A',
    'ssmlGender':'FEMALE'
  },
  'audioConfig':{
    'audioEncoding':'MP3'
  }
}" "https://texttospeech.googleapis.com/v1/text:synthesize"

I get Error code 403 telling me that Cloud Text-to-Speech API has not been used in project 32555940559 before or it is disabled. Now the problem is that it mentions the project number 32555... but I want to use another project which has the TTS API switched on. Now you might suggest that I switch to the correct project, but I have done that -- when I type gcloud config list, it tells me that I am using the correct project (with project number different from the 32555...).
Where is the problem? Why is it trying to use a different project from the one that I am currently using?

A: You need to use "gcloud auth app-default print-access-token" (and use a dedicated service account as specified in the docs).
32555940559 is a CLOUDSDK_CLIENT_ID that comes with gcloud. And app-default has its own client_id as well. It's still now clear how Google API distinguishes between the two, unless it checks for hard-coded app-default client ID (from gcloud SDK).
It's also not clear how gcloud command line still manages to use speech API without a dedicated service account.

A: On a related note, since I had this same issue (API has not been used in project  before or it is disabled "32555940559") in a Python virtual environment using gcloud SDKs (not curl).
Solved by running:
gcloud auth application-default login

(using gcloud auth login did not solve it).
For gcloud, the root cause might also be related to missing:
GOOGLE_CLOUD_PROJECT or GOOGLE_APPLICATION_CREDENTIALS environment variables.


text:
Q: Loading local CSV into snowflake After 4 days of trying everything to load data into snowflake, nothing seems to work at all.
Now as my last option I want to load a local CSV file into snowflake in order to be able to follow the tutorial I am watching.
Unfortunately even this step seems to be a hard one in snowflake. I have seen, that I need to create an internal stage for this. Therefore I went to the Stage and created a "Snowflake Managed", which I think should be an internal stage. I called that Stage "MY_CSV_STAGE".
Internal Stage option on snowflake:

Then I went back to the worksheet and tried the following command:
PUT file://C:\Users\User\Downloads\Projekte/csv_dateien_fuer_snowflake.csv @MY_CSV_STAGE AUTO_COMPRESS=TRUE;

Now by trying to run the command I am just receiving a weired error, which I don't understand:
Error Message:

I really would like to understand what exactly I am doing wrong. I have also read on other places, that I should maybe need Snowsql to import data from local to snowflake. But the installation of the Snowsql I did not figure out.
How can I write this command line in snowflake in order to be able to import the CSV file?


text:
Q: Using composite key of Latitude and longitude vs auto increment as Primary Key in case of area under city Relational DB Suppose we need to save following data in database
County          latdecdeg   londecdeg         State
---------------------------------------------------
Allegheny       40.5254     -80.07213889        PA
Allegheny       40.5526     -80.1159            PA
Allegheny       40.5191     -80.13090556        PA
Allegheny       40.5134     -80.13508889        PA
Allegheny       40.5228     -80.17644722        PA
Allegheny       40.496      -79.939375          PA
Beaver          40.6957     -80.36681667        PA
Berks           40.2485     -76.03885833        PA
Berks           40.2979     -75.89966111        PA
Blair           40.5622     -78.32684722        PA
Blair           40.6001     -78.31262222        PA

So is it a good idea to use a combination of Lat and log as primary key ?
OR It is better to have one more column as auto increment primary key .
Also the query will be made on the basis of county and and all its lat and long need to be fetched.

A: You should use an auto-increment primary key.
One of the purposes of a primary key is to provide a key for foreign key references.  In most cases an integer column is the best choice.  In addition, you don't specify what these are, but multiple addresses can be at the same location (the metro in Naples Italy has two subways that are vertically aligned along the side of a hill, for instance).
Further, you never want to use floating point numbers as a primary key.  And that even extends to fixed point decimal numbers.
Add an additional column to identify each row uniquely.

A: For the first part of your question, one should  use Auto increment as it's the best way to define primary key of a table since it's managed by the db itself.
For the second part regarding querying on the basis of some columns, Indexing should be beneficial for the purpose.


text:
Q: Database Design - Application Integration with Other Systems I'm currently integrating external applications in my app ex SalesForce.com. My question pertains to properly designing tables for data capturing custom fields.
So for SalesForce all companies have an Organization ID but then they can also have custom fields for capturing data. I've looked at two options for handling this.

*

*Let them create their fields serialize the names as keys in an array. Then connect the values into that array and re serialize.

*Create 10+ columns in the db that allow for custom values(field names) and then map the users data to those fields.

Which one of these approaches is more efficient and maintainable for the long run?

A: It's not clear from your question whether you need these custom fields on a per-user or per-table basis.  If it's per table, then I'd create a "sibling" table for each table that required the additional fields.  Give it the same primary key columns as the main table, plus a sequence number column and columns for a field name and value.  I'd make them both character columns and plan to convert to/from the actual field type, but if you want to create a separate column for each data type and only use one, that's your call.  Then, whenever you fetch a row from the main table, you also fetch all the rows with the same key from the sibling table, and order the returned columns by sequence number.  You can add additional columns to the sibling table as required; e.g., you may want to add a flag to indicate that certain fields are required.
If you want to create all the entries in the sibling table for each row inserted into the main table, then you might want to have a "template" or "prototype" row with a special key in the main table, so you can easily get all the custom fields.  This also permits you to specify default values for the custom fields, just store them in the prototype entries.


text:
Q: Remove image solid background with c sharp I'm trying to find some info about removing an image background "automagically" if possible in .NET.
Actually I could not find much data and I don't event know if it's possible or are there any API components available.
Any ideas?

A: Establish a rule, for example that the pixel at [0,0] must be the 'transparent' color (the background).  Load the image as a Bitmap (let's call it bmp), and then do something like this:
bmp.MakeTransparent(bmp.GetPixel(0, 0));

A: Homer, for the file formats you suggest, there is no easy way of defining what the 'background' is. For instance, say you have some colorful text on a white background. I'm assuming you'd want to make the white transparent? There is nothing in the file format to say "this layer or color is the background". There may be heuristics for trying to determine the background color, but there will probably be no library to do something like image.MakeBGTransparent().


text:
Q: Unable to install matplotlib Problem: Unable to install matplotlib v 2.02 in Python 3.3 on Windows 10 environment
C:\Python33>pip install matplotlib

The pip installer completes most of the task and then gives me this error
Command "python setup.py egg_info" failed with error code 1 in c:\users\xxx\appdata\local\temp\pip-build-3ob70y\matplotlib\

C:\Python33>pip install --upgrade setuptools

Requirement already up-to-date: setuptools in c:\python33\lib\site-packages

I have tried the following

*

*uninstalling and reinstalling

*doing this at the root rather than Python33 folder

*manually installing maplotlib. this seemed to work but it then found two missing files (__ and cycler) . I installed those separately with pips but then it complained about six.moves being missing

*consulting Can't install via pip because of egg_info error

*consulting several other articles on web. Some suggested a conflict between the requirements of python 2 and pythono 3. However it seems the packages are supposed to work with both
Here is the detailed pip error message
Successfully uninstalled matplotlib-2.1.0rc1

 C:\Python33>pip install matplotlib
    Collecting matplotlib
    Using cached matplotlib-2.0.2.tar.gz
    Complete output from command python setup.py egg_info:

    ======================================================================
    Edit setup.cfg to change the build options>

    BUILDING MATPLOTLIB
                matplotlib: yes [2.0.2]
                    python: no  [Requires Python 3.4 or later (in the 3.x
                            series)]
                  platform: yes [win32]>

    REQUIRED DEPENDENCIES AND EXTENSIONS

                     numpy: yes [version 1.7.1]
                       six: yes [The installed version of six is 1.3.0 but a >                        the  minimum required version is 1.10. pip/easy >
                           install will attempt to install a newer version.]
                  dateutil: yes [using dateutil version 2.1]
               functools32: yes [Not required]
              subprocess32: yes [Not required]
                      pytz: yes [pytz was not found. pip will attempt to
                             install it after matplotlib.]
                    cycler: yes [using cycler version 0.10.0]
                   tornado: yes [using tornado version 4.4.2]
                 pyparsing: yes [using pyparsing version 2.2.0]
                    libagg: yes [pkg-config information for 'libagg' could
                            not be found. Using local copy.]
                  freetype: no  [The C/C++ header for freetype (ft2build.h)
                            could not be found.  You may need to install the
                            development package.]
                       png: no  [The C/C++ header for png (png.h) could not
                          be found.  You may need to install the development
                            package.]
                     qhull: yes [pkg-config information for 'qhull' could
                             not be found. Using local copy.]

    OPTIONAL SUBPACKAGES

               sample_data: yes [installing]
                  toolkits: yes [installing]
                     tests: no  [skipping due to configuration]
            toolkits_tests: no  [skipping due to configuration]

    OPTIONAL BACKEND EXTENSIONS
                    macosx: no  [Mac OS-X only]
                    qt5agg: no  [PyQt5 not found]
                    qt4agg: no  [PySide not found; PyQt4 not found]
                   gtk3agg: no  [Requires pygobject to be installed.]
                 gtk3cairo: no  [Requires cairocffi or pycairo to be
                                installed.]
                    gtkagg: no  [Requires pygtk]
                     tkagg: yes [installing; run-time loading from Python
                                 Tcl /     Tk]
                     wxagg: no  [requires wxPython]
                       gtk: no  [Requires pygtk]
                       agg: yes [installing]
                     cairo: no  [cairocffi or pycairo not found]
                 windowing: yes [installing]

    OPTIONAL LATEX DEPENDENCIES
                    dvipng: yes [version 1.15]
               ghostscript: yes [version 9.19]
                     latex: yes [version MiKTeX 2.9]
                   pdftops: yes [version 0.46.0]

    OPTIONAL PACKAGE DATA
                      dlls: no  [skipping due to configuration]

      ================================================================
                            * The following required packages can not be
                              built:
                            * python, freetype, png

    ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in
    c:\users\xxx\appdata\local\temp\pip-build-3ob70y\matplotlib\

A: As the official version of Matplotlib in Python package index https://pypi.python.org/pypi/matplotlib/, it supports only the following Python versions:

*

*Python :: 2.7

*Python :: 3.4

*Python :: 3.5

*Python :: 3.6

So, you can not install matplotlib 2.1.0rc1 (which is the version you get using pip install matplotlib) in Python 3.3.


text:
Q: Should it be possible to have more than one DocuSign account (DEMO) with the same email address? I have a DocuSign integration scenario that has resulted in what look to be multiple DS accounts created using the same email address but different passwords.  I can login w\ the same email address, use two different passwords, and end up in two entirely different accounts.

A: Yes this is by design.  The DocuSign platform uniquely identifies accounts based on user email and user name combinations.  So creating multiple user accounts under the same email address is allowed.
One other thing to add here, there is also an option in DocuSign called
AnySigner

which allows you to send signature requests to AnySigner recipients which means all you send to is an email address (i.e. no username) and anyone who has access to that email account can sign and complete.  This is a popular option for when you need something signed by anyone in a given department.  For instance, you need a form signed by someone in your Human Resources department which has a common email they use.


text:
Q: HttpUtility.ParseQueryString changes the actual string for hebrew letters HttpUtility.ParseQueryString("tap=%d7%a6%d7%95%d7%a4%d7%94", Encoding.GetEncoding("ISO-8859-8"))

returns this result:
tap=%uf7b5%u00a6%uf7b5%u0095%uf7b5%u00a4%uf7b5%u0094

Tried several encodings, but all returns a different string that was sent.
how can I keep the original formatting of the string ?
The original string decodes (by Url Decode tool set on utf8) to this hebrew string:
צופה

A: It seems like your query string is already encoded, so specifying an Encoding will try to re-encode it again.
If you use the other overload which does not anticipate an Encoding then it will work fine:
var col = HttpUtility.ParseQueryString("tap=%d7%a6%d7%95%d7%a4%d7%94");
foreach (string key in col)
    Console.WriteLine($"{key}: {col[key]}");

The output will be
tap: צופה


text:
Q: FileInputStream/DataInputStream So, we got an assignment to make a guessing game. The program has to generate a number and the user has to guess. After the users guesses right, the program shows the "Highscore" (how many times the user had to guess before he got it right).
Then we should save this highscore in a text-file, so that it is saved on the computer, and if you restart the computer it will not be lost. What I am struggeling with is how the program is supposed to read the file I saved.
This is my "write-code":
try {
    FileOutputStream write = new FileOutputStream
    DataOutputStream out = new DataOutputStream(write);
    out.writeBytes(""+highscore);
    write.close();}
catch(IOException ioException ){
    System.err.println( "Could not write file" );
    return;}

Which works fine, but I don't know how to read it again.
My "read-code": (I just guessed, I don't know if this would work)
try{
    FileInputStream read = new FileInputStream
    DataInputStream in = new DataInputStream(read);
    in.readBytes(""+highscore);
    JOptionPane.showMessageDialog(null, "Your highscore is" + highscore);
catch(IOException ioException ){
    System.err.println( "Could not read file" );
    return;}

Now, I dont know if the in.readBytes(""+highscore); command is correct. I just guessed (I thought if out.writeBytes(""+highscore); worked then surely read has to work too)
If readBytes is the correct command then I get this error :
The method readBytes(String) is undefined for the type DataInputStream
What am I supposed to do?
Some information: The highscore is and int.

A: For example, if highscore is an int, you'll want to write an int to the file. You can do that with
DataOutputStream out = new DataOutputStream(write);
out.writeInt(highscore);

and read it with
DataInputStream in = new DataInputStream(read);
int highscore = in.readInt();

The class DataInputStream does not have a readBytes(). That is why your program does not compile.
The whole point of DataIOStream classes is to read and write

primitive Java data types from an underlying [...] stream in a
  machine-independent way.

So use the methods corresponding to the data type of highscore.


text:
Q: Fulltext SQL Server database search using standard modifiers ( + , - , "" , etc.) I'm using SQL Server FreeTextTable to do some relevance searching in a project. It works really nice for most standard searches, such as:

*

*sofa chair - to search for one/and or both

*"sofa chair" - to search for the phrase 'sofa chair'

I'd like to add some boolean search capabilities, too, such as:

*

*sofa and chair - to search for both sofa as well as chair

*sofa -chair - to search for sofa but not chair

*"green sofa" or "red chair" to search for either 'green sofa' or 'red chair'

Will I need to do a LIKE/NOT LIKE phrase in the search and then do a FreeTextTable for ranking? Is there some other way to do it?

A: I think LIKE/NOT LIKE is the easiest way to do it. Take the string you're parsing for the search, like for "OR"'s and "AND"'s, and build your query dynamically. Similarly, if you encounter a '-' build a NOT statement. I don't think it will be too difficult.
If you want to check out some of the advanced options available for SQL searches, I know MySQL supports regex strings, you can read all about it here:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html


text:
Q: Symfony 2 Email Validator Null Value I have implemented a forgotten password form and validate the provided email using Symfonys email constraint however it appears that it fails to recognise an empty or null value as an invalid email address even if I set the host and MX records check to true. To me that makes no sense. Am I missing something here or is that expected behaviour??
$email = $request->request->get('email');

$emailValidator = new Email();
$emailValidator->message = 'Invalid email address';

// use the validator to validate the value
$errorList = $this->get('validator')->validateValue(
        $email,
        $emailValidator
    );

A: Look at the source of the validator: if an empty string or null is passed, it does nothing. In other words, empty values will always succeed.
So yep, it's expected behavior though there's a ticket about changing it.
<?php
/**
 * @author Bernhard Schussek <[...]>
 *
 * @api
 */
class EmailValidator extends ConstraintValidator
{
    /**
     * {@inheritDoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;
        $valid = filter_var($value, FILTER_VALIDATE_EMAIL);

        if ($valid) {
            $host = substr($value, strpos($value, '@') + 1);

            // Check for host DNS resource records
            if ($valid && $constraint->checkMX) {
                $valid = $this->checkMX($host);
            } elseif ($valid && $constraint->checkHost) {
                $valid = $this->checkHost($host);
            }
        }

        if (!$valid) {
            $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
        }
    }

    // ...
}

You'll need to use a combination of NotBlank and Email
<?php
use Symfony\Component\Validator\Constraints as Assert;

$emailValidator = new Assert\Email();
$emailValidator->message = 'Invalid email address';

$validator->validateValue($the_email, array(
    new Assert\NotBlank(),
    $emailValidator,
));


text:
Q: How to gpg encrypt with ssh public key? I have a public key in a file called key.pub, and the contents look like:
ssh-rsa AAAAB...<snip>...t+f klahnakoski

I would like to to use it to encrypt a file with gpg.  What is the sequence of shell commands required?
I imagine the sequence looks something like:

*

*convert key to gpg-friendly format

*invent some credentials to sign key with

*invent a user to facilitate adding key to keyring

*perform the encryption

Thank you!

A: RSA keys can only be used to encrypt a proportion of their key length. e.g. a 2048 bit RSA key can only be used to encrypt about 245 bytes.
See:
https://security.stackexchange.com/questions/33434/rsa-maximum-bytes-to-encrypt-comparison-to-aes-in-terms-of-security
So to encrypt / decrypt large amounts of data (files) you would use a symmetric key which was encrypted using a public key, not the public key itself.
Also, you wouldn't add a symmetric key to a public SSH key, because the the symmetric key is a secret, and the public SSH key isn't a secret. The symmetric key should be added to the private SSH key.
It goes something like the following:
To convert the file format, install the monkeysphere tool set (Ubuntu)
sudo apt-get install monkeysphere

Use the pem2openpgp tool to convert the private key to gpg format. Pipe to gpg for import.
pem2openpgp userid-ssh@example.com < id_rsa | gpg --import

# Check it's there
gpg --list-secret-keys

Edit the trust level you have in the key.
gpg --edit-key userid-ssh@example.com
gpg> trust

Add the trust level you need (ultimate for example)
The key imported is only suitable for creating certificates, not for signing or encryption.
Encryption
The key is an RSA key and can't be used to encrypt / decrypt large amounts of data. If you want to do that you have to add a symmetric encryption subkey. When you encrypt, GPG will use this subkey rather than the original SSH key.
gpg> addkey
Please select what kind of key you want:
   (3) DSA (sign only)
   (4) RSA (sign only)
   (5) Elgamal (encrypt only)
   (6) RSA (encrypt only)
Your selection? 6

Now you can encrypt and decrypt using the identity based on the SSH key.
gpg -vv -r userid-ssh@example.com -e -a unencrypted_file.txt

So how useful is this?
Well, it makes more sense to use GPG to generate and manage your SSH keys as authentication subkeys rather than trying to do it the other way round. In fact it can be integrated into SSH instead of ssh-agent.

A: Probably ssh-vault could give you some ideas, it follows the same principle of PGP and using the public ssh keys to encrypt the password only.


text:
Q: dealing with missing properties on nested object while destructring I need to destructure a nested object. what is the best way to avoid exceptions when some of the nested properties are missing, while assigning those who do exist?
const data = {
  title: 'hello',
  // nest: {
  //   road: 5
  // }
};

const { title, nest: { road = '' } } = data;

console.log(road);
/** i want it to return '' or undefined.
 *  actually it returns: Cannot match against 'undefined' or 'null'
 *
*/
console.log(title)
/** i want it to return 'hello'
 * actually: never got there as there was an exception.
 */

A: You can assign in a parent object level to empty object (or with value) even if it has further nested object destruction:
const { title, nest: { road = '<default road>' } = {} } = data;

const data = {
  title: 'hello',
   //nest: {
   //  road: 5
   //}
};

const { title, nest: { road = '<default road>' } = {} } = data;

console.log(title);
console.log(road);

And also, you are doing it wrong, if you are destructing using
{title: englishTitle} = {title: 1234}

then, you should use englishTitle to get the value 1234, and not title, or use
{title} = {title: 1234}

and use title to get 1234


text:
Q: Why hybrid GIS application gets GPS position only from Google & not from the device I have built a GIS application using Leaflet on the web, after I put this web application to run on Android as a hybrid GIS application I made the application work with offline basemap (offline usage only) but the GPS finder can't get the position it trys to retreive it fom the Internet and not from the device.
is it because my GIS application isn't Native android ?

A: Android GPS works native in hybrid apps, it just needs some settings within app. I'm absolute amateur with Android apps, I learned how to use Android Studio only for the purpose of writing hybrid Andriod app that uses Leaflet.
Below are GPS related excerpts from my hybrid app that worked for me.
Manifest:
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...

Code:
...
import android.webkit.GeolocationPermissions;
...
public class MainActivity extends AppCompatActivity {
  public class MyWebChromeClient extends WebChromeClient {
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin,
                            GeolocationPermissions.Callback callback) {
      // Always grant permission since the app itself requires location
      // permission and the user has therefore already granted it
      callback.invoke(origin, true, false);
    }
  }
...
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setDomStorageEnabled(true);
...

After installing app on Android you also have to allow it to use GPS.


text:
Q: Getting a string from a in specific h2 header I have html which have couple headers. Single one looks like this:

                    text

How I can get the 'text' only if there is class=product-name in the h2?
I tried some ways to do this and none of them worked.


text:
Q: Conditionals in Helm template I'm trying to define a helm template with an if conditional, but I'm not being able to achieve it. The JSON template are inside the files directory inside my helm-chart and it is like that:
{
  "default_project": "{{ .Values.ss_api_ob }}",
       "roaming": {
          "xxx": "false",
          "xxx": "xxx.json",
          "xxx": "xx.json",
          "xxx": "xxx.json",
          "xxx": "correspondences.json",
         if  "{{- eq .Values.myvar "es" -}}"
          "xxxx": {{ '[["xxx", "xxx"], ["xxx", "xx"], ["xx", "xxxx"], ["xx", "xx"]]' }},
          {{- else -}}
         "xxx": {{ '[["yyy", "yyy"], ["yyy", "yyy"], ["yyy", "yyy"]]' }},
         {{- end -}}
          "xxxx": "http://{{ .Values.kongService }}:9800/xxxx",
          "xxx": "http://{{ .Values.kongService }}:9800/xxxxx",
          "xxxx": "http://{{ .Values.kongService }}:9800/xxxx"
        },
}

myvar = es so the json file should define the first choice. But when I try to install it I'm getting an error like something is wrong:
Error: template: api/templates/configmap.yaml:7:7: executing "api/templates/configmap.yaml" at <tpl (.Files.Glob "files/*").AsConfig .>:  parse error at (api/templates/configmap.yaml:5): unclosed action

I have checked my JSON template but I don't find where is the problem. Any idea?

A: *

*Your if is outside the action.

*The action is unnecessarily quoted.

The following ought to work:
{
  "default_project": "{{ .Values.ss_api_ob }}",
       "roaming": {
          "xxx": "false",
          "xxx": "xxx.json",
          "xxx": "xx.json",
          "xxx": "xxx.json",
          "xxx": "correspondences.json",
          {{- if eq .Values.myvar "es" -}}
          "xxxx": {{ `[["xxx", "xxx"], ["xxx", "xx"], ["xx", "xxxx"], ["xx", "xx"]]` }},
          {{- else -}}
          "xxx": [["yyy", "yyy"], ["yyy", "yyy"], ["yyy", "yyy"]],
          {{- end -}}
          "xxxx": "http://{{ .Values.kongService }}:9800/xxxx",
          "xxx": "http://{{ .Values.kongService }}:9800/xxxxx",
          "xxxx": "http://{{ .Values.kongService }}:9800/xxxx"
        },
}


text:
Q: UIColor -initWithRed:green:blue:alpha: memory leak? I have this situation:
UIColor *color = [[UIColor alloc] initWithRed:0/255.f green:156/255.f blue:255/255.f alpha:1];
self.lightBlue = color;
color = nil;
[color release];

And receive memoery leak in UIColor *color = [[UIColor alloc] initWithRed:0/255.f green:156/255.f blue:255/255.f alpha:1];
The situation from Instruments:

Any ideas?

A: You are setting your local variable 'color' to nil and then doing [nil release] which does nothing.
If you really need 'color = nil', you should do it after the release.

A: The leaks tool shows you where something that is leaking, was allocated.
So what it's saying is, after you assigned these values they were never released - which seems like it means your navigation controller is not being released when it should be. Don't release the object, you don't own it and you will eventually get crashes. UIColor is probably just caching these colors for you, and Instruments has no way of knowing this so it reports them as leaks (basically stuff that got created and you don't have a reference to anymore but hasn't been deallocated).
Try running instruments for some time (using the simulator) and then sending a memory warning to see if UIColor will purge its cache. Either way, there isn't anything you can really do to fix leaks happening inside core frameworks, so don't try. Just make sure you're not actually leaking them somehow (like retaining them at some point and never releasing them).
Bottom line is if the above code is all that you are doing, color is most definitely not leaking. If you are retaining that object anywhere else without releasing it, it is leaking.
Never release an object that you don't remember retaining. EVER. But I suspect that you just are retaining it somewhere, and don't even notice it.


text:
Q: what are some drawbacks to using clone & pop to iterate through an array rather than using a for loop? it looks like this method of iteration is much much faster than a for loop:
var arr = window.arr.slice(0),
    fruit = arr.pop();
while (fruit) {
 fruit = list.pop();
}

as evidenced in this jsperf test: http://jsperf.com/loop-iteration-length-comparison-variations/7
I know I'm taking a memory hit by cloning the array but if i delete the clone right after i loop through it, what else should i be weary of?

A: The main drawback is here:
fruit = arr.pop();
while (fruit) {

If fruit evaluates to false (i.e. is null, undefined, 0, and so on) the loop will stop. That is nasty for sparse arrays, e.g.
var arr = [0,,,,2];

will only loop over the last member, then attempt to evaluate arr[arr.length - 2], find it returns undefined (it doesn't exist) so the loop ends. This is avoidable in a for loop as you can test if the property exists first (if necessary):
for (var i=0, iLen=arr.length; i<iLen; i++) {

  if (i in arr) {
    // arr has a property i so do stuff with arr[i]
  }
}

So the pop method might be fast, but can only be reliable if you are certain that none of the values evaluate to false, or the loop is terminated by keeping a counter:
var fruit,
    i = arr.length;
do {
  fruit = arr.pop();
} while (--i)

so you might as well do
do {
  fruit = arr[--i];
} while (i);

and not bother with the copy.


text:
Q: multi-part form post with binary data on Android 4.0 using HTML5 and Angular First, let's just be clear: there is no form, there is not file input. The image files I need to upload is obtained via the cordova camera API. No user file picking of any kind. I mention this explicitly because most of these sort of questions involve the user utilizing a form with a file input element and picking a file. This is NOT what I need to do.
Secondly tech in use is:

*

*Android 4.0

*Angular 1.3.x

*Cordova

In other words, a hybrid HTML5 application on Android 4.0
I have code working on android 4.3 - no problems.
Unfortunately, the Blob constructor is not supported on 4.0, which is the start of my problems.
Using the deprecated BlobBuilder API (which IS available on 4.0), I seem to be able to get a Blob constructed.
BUT, the binary image data just does not make it into the request to the server (I have created a dummy receiver Servlet, that just simply dumps the received POST body to console - all other fields are present, but the file field has no binary content).
Blob creation code:
    try {
          imgBlob = new Blob ([data],{type:'image/' + imageExt});
        }
        catch (e) {
          $log.info('Apparently Blob constructor not supported, attempting fallback to BlobBuilder API');
          window.BlobBuilder = window.BlobBuilder ||
                     window.WebKitBlobBuilder ||
                     window.MozBlobBuilder ||
                     window.MSBlobBuilder;

          $log.debug('Selected BlobBuilder: ' + window.BlobBuilder);

         if(e.name === 'TypeError' && window.BlobBuilder){
           $log.debug ('We got exception TypeError');
           var bb = new BlobBuilder();
           bb.append(data);
           imgBlob = bb.getBlob('image/' + imageExt);

         }
         else if(e.name === 'InvalidStateError'){
           $log.debug ('We got exception InvalidStateError');
           // InvalidStateError (tested on FF13 WinXP)
           imgBlob = new Blob( data.buffer, {type : 'image/'+imageExt});
         }
         else{
           $log.error ('We\'re screwed, blob constructor unsupported entirely');
         }
        }

The data paramaters is an ArrayBuffer object. As far as I can tell, it DOES contain the correct image data.
The actual upload code:
     var uploadUrl ='https://uploadReceiverUrl' ,
        requestData =  {
                file: {val:imgBlob,contentDisposition:imgMetaData.uuid + '.' + imageExt},
                imageid: imgMetaData.uuid,
                formId: imgMetaData.formId,
                key: theKey,
                hmac: hmac,
                userId: imgMetaData.userId
        },
        headers = {
            'Content-Type':undefined
        };

        $http({
            method : 'POST',
            url : uploadUrl,
            headers : headers,
            data:requestData,
            transformRequest: FormDataObject
        })
        .success (function (data,status) {

            //Handle success by deleting image - this is fine.
        })
        .error (function (data, status) {
            $log.warn ('UploadService.uploadImage():: failed. Status ' + status + ', data: ' + data);
        });

The mentioned transformRequest function is very simple. Essentially:
  function (data) {
    var fd = new FormData();

    angular.forEach(data, function (value, key) {

    if ( typeof value === 'object' ) {

        fd.append(key, value.val, value.contentDisposition);

    }

    else {
        fd.append(key, value);
        $log.debug ('FormDataObject:: Added to FormData (' + key + ') with val (' + value + ')' );
    }
}}

SO I am either missing something very stupid or small, OR there is some crucial support not available in Android 4.0 that I have so far failed to discover.
Halp?


text:
Q: Sort array Alphabetically- Angularjs I have my result showing here

    {{o.title}}

which shows

    aaa
    ggg
    ccc
    bbb

I have a select dropdown. I should able to sort my result alphabetally after  i select 'Alphabetical' option
<select ng-model="filt">
    <option value="-1">vsf</option>
    <option>Alphabetical</option>
    <option>sccc</option>
</select>

Initially i have put orderBy:'title'. but this should happen after i select dropdown. how to achieve this ?

A: You can try this:

A: <select ng-model="filt">
  <option>Alphabetical</option>
  <option>k</option>
</select>

{{o.title}}

A: It is better if you do the filtering and sorting in controller.
You can change the Array.prototype.sort() function as per your requirement
Controller
$scope.data=[{
    "title" : "gggg"
},{
    "title" : "cccc"
},{
    "title" : "zzzz"
},{
    "title" : "aaaa"
}];
$scope.sortvalue = "None";

$scope.changeSortOrder = function()
{
  if($scope.sortvalue == "Alphabetically")
  {
    $scope.data.sort(function(a, b){
      if(a.title  b.title) return 1;
      return 0;
    });
  }
}

HTML

      {{o.title}}

     <select ng-model="sortvalue" ng-change="changeSortOrder()">
      <option value="None">Select an option</option>
      <option value="Alphabetically">Alphabetically</option>
     </select>

FULL EXAMPLE
Here is a list of examples that uses Array.prototype.sort() to sort arrays

A: Try this way :

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.data = [{
        "title" : "aaa"
    },{
        "title" : "ggg"
    },{
        "title" : "ccc"
    },{
        "title" : "bbb"
    }];
});

  <select ng-model="filt">
    <option value="-1">vsf</option>
    <option value="title">Alphabetical</option>
    <option>sccc</option>
  </select>

   {{o.title}}

A: Very simple..
You want to sort Alphabetically.. means u have to pass value as 'title' to your option 'Alphabetical'.
because based on 'title' the result will sort
<select ng-model="filt">
    <option value="-1">vsf</option>
    <option value="title">Alphabetical</option>
    <option>sccc</option>
</select>

Then in your div

orderBy: filt will execute only for your option value='title'. That is where sorting happens


text:
Q: run jquery code after new elements load I have link with id="#knav1". After click in div with id="navldesc" load select element with class="selnav1".
$("#knav1").click(function(){
$("#navldesc").load('/const/api.php?nvsload=y&komplektn=kompl1');
});

But next script not working:
$(".selnav1").change(function(){
alert('ewfew');
});

How to i fix this problem?

A: use .on() for dynamically loaded element's like this
$(document).on('change','.selnav1',function(){
  alert('ewfew');
});


text:
Q: Divisibility Number Theory problem, explanation needed I can't understand the solution of the following problem:
$x$,$y$,$z$ are pairwise distinct natural numbers show that $(x-y)^5$ + $(y-z)^5$ + $(z-x)^5$ is divisible by $5(x-y)(y-z)(z-x)$. No need to explain the div. by 5.
The sol. says:
$(x-y)^5$ + $(y-z)^5$ + $(z-x)^5$ is $zero$ for $x=y$, $y=z$, $z=x$. So the terms $(x-y)$, $(y-z)$, $(z-x)$ can be factored out.
This is the 106th problem chap. 6 form "Problem solving strategies" by A. Engel
If you have alternative solution pls feel free to post it.

A: For example, the given expression is divisible by $x-y$ if and only if $y$ is a root of the polynomial regarded as a function of $x$. But substituting $x=y$ indeed gives zero, so that $x-y$ must be a factor.

A: Let $x-y=a$ and $y-z=b$.
Thus, $z-x=-(a+b)$ and $$\sum_{cyc}(x-y)^5=a^5+b^5-(a+b)^5=-5a^4b-10a^3b^2-10a^2b^3-5ab^4=$$
$$=-5ab(a^3+2a^2b+2ab^2+b^3)=-5ab(a+b)(a^2-ab+b^2+2ab)$$ and we are done!


text:
Q: OpenGL: Is it supported to render into an FBO in one context, then use the FBO's texture in another? I have the following OpenGL setup for troubleshooting frame buffer issues:

*

*I render a cube into a frame buffer.

*I use the target texture from this frame buffer to draw a textured quad, which displays the cube in my viewport.

This works OK when both stages of the process are done in the same context, but breaks if stage 1 is done in a different context to stage 2 (note that these contexts are both shared and both on the same thread). In this case, I only ever see the cube displayed when I resize my viewport (which recreates my frame buffer). The cube is sometimes corrupted or fragmented, which leads me to believe that all I'm seeing is parts of memory that were used by the texture before it was resized, and that nothing is ever displayed properly.
The reason I have to have this setup is that in my actual application I'm using Qt OpenGL widgets, which are forced to use their own individual contexts, so I have to render my scene in its own dedicated context and then copy it to the relevant viewports using shareable OpenGL resources. If I don't do this, I get errors caused by VAOs being bound/used in other contexts.
I've tried the following unsuccessful combinations (where the primary context is where I use the texture to draw the quad, and the secondary context where the "offscreen" rendering of the cube into the frame buffer takes place):

*

*Creating the frame buffer, its render buffer and its texture all in the secondary context.

*Creating the frame buffer and the render buffer in the secondary context, creating the texture in the primary context, and then attaching the texture to the frame buffer in the secondary context.

*Creating the frame buffer, its render buffer and two separate textures in the secondary context. One of these textures is initially attached to the frame buffer for rendering. Once the rendering to the frame buffer is complete, the first texture is detached and the second one attached. The previously attached texture containing the content of the rendering is used with the quad in the primary context.

In addition, I can't use glBlitFramebuffer() as I don't have access to the frame buffer the QOpenGLWidget uses in the application (as far as I've tried, QOpenGLWidget::defaultFramebufferObject() returns 0 which causes glBlitFramebuffer to give me errors).
The only way I have managed to get the rendering to work is to use a QOpenGLFrameBuffer and call takeTexture() when I want to use the texture with the quad. However, doing it this way means that the QOpenGLFrameBuffer creates itself a new texture and I have to destroy the old one once I've used it, which seems very inefficient.
Is there anything I can do to solve this problem?

A: I've got a project that uses a texture like that. You need to call glFinish() after drawing and before using the texture from QOpenGLFramebufferObject::texture(). That was our problem on some of the OSes.


text:
Q: Why does my sieve not perform well for finding primes? I wrote two prime finder functions and the sieve only performs about 10% better.  I'm using two optimizations for the simple version.

*

*Don't check even numbers

*Only check up to the square root or j * j <= i. ( equivalent )

and one optimization for the sieve version

*

*Only check up to the square root or i * i <= n. ( equivalent )

What optimizations can I add to the sieve?
My sieve is pretty slow.  I don't want to do a bitwise implementation yet, I want to understand if this implementation offers any benefits.
Or if I missed an implementation point.
The inner for loop in the pseudocode here looks interesting / odd
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
I don't know how to interpret it. (update: the OP seems to indicate in the comments that it was an issue with incorrect formatting after copy-pasting the pseudocode from Wikipedia, and with the corrected formatting it is clear now)
Here it is:

algorithm Sieve of Eratosthenes is: input: an integer n > 1.
output: all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
    if A[i] is true
        for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
            A[j] := false
return all i such that A[i] is true.

// prime-2
// 2 optimizations - odds and square root
function prime2(n){
  const primes = [2];
  not_prime: for(let i = 3; i < n; i += 2){
    for(let j = 2; j * j <= i; j++){
      if(i % j === 0){
        continue not_prime;
      }
    }
    primes.push(i);
  }
  return primes;
}

// prime-3
// sieve implementation
function prime3 (n) {
  const primes = [];
  const sieve = (new Array(n)).fill(true);
  for (let i = 2; i * i <= n; i += 1) {
    if (sieve[i]) {
      for (let j = i + i; j < n; j += i) {
        sieve[j] = false;
      }
    }
  }
  makePrimes(sieve, primes, n);
  return primes;
};
function makePrimes(sieve, primes, n){
  for (let i = 2; i < n; i++) {
    if(sieve[i]) {
      primes.push(i);
    }
  }
}

A: What you see is an expression of the differences in theoretical run time complexities, i.e. the true algorithmic differences between the two algorithms.
Optimal trial division sieve's complexity is O(n1.5/(log n)2)(*)  whereas the sieve of Eratosthenes' complexity is O(n log log n).
According to the empirical run time figures posted by Scott Sauyet in the comments,
   1e6      279ms      36ms
   1e7     6946ms     291ms
   -------------------------
   n^       1.40       0.91

the empirical orders of growth are roughly ~n1.4 and ~n in the measured range, which is a good fit.
So your genuine sieve does perform well. The trial division sieve performs as expected. The algorithmic nature of a code will always beat any presence or absence of any secondary optimizations, if we increase the problem size enough.
And comparing performances by measuring them at just one problem-size point is never enough. So even if you see just 10% difference over the "simpler one", if you test at bigger sizes, the difference will be bigger.

If you want some pointers about what can be further improved in your code, do note that you start the inner loop from i+i instead of from i*i, for starters.
Another common optimization is to special-case 2, start from 3 and increment the candidates by 2 and use the inner loop increment of 2*i instead of just i, to achieve instant 2x speedup. This is the simplest form of wheel factorization optimization, which can be further applied, with diminishing returns though for each additional prime. But using 2-3-5-7 is common and should give about another 2x speedup, if memory serves.
Last but not least, make it segmented.

(*) that's π(n)* π(√n) coming from primes, and no more than that, from the composites.


text:
Q: How to get CQL change detail via cassandra 3.1 trigger? In cassandra 2.2, we can iterate update to get the cell change value:
for (Cell cell : update)
    {
        // Skip the row marker and other empty values, since they lead to an empty key.
        if (cell.value().remaining() > 0)
        {
            Mutation mutation = new Mutation(indexKeySpace, cell.value());
            mutation.add(indexColumnFamily, cell.name(), key, System.currentTimeMillis());
            mutations.add(mutation);
        }
    }

In cassandra 3.0, the ITrigger interface was changed, and the current object is change to "Partition update":
public Collection<Mutation> augment(Partition update)

If anyone know what's the proper way to extract the detail change value of each cell?


text:
Q: How do I make Dynamic Student Admission Form? We have a college where 3000 students are admitted every year. I would like to make an admission form.
The question is, I will import the student data such as name, registration number, and subject in advance, if the student inputs his registration number in the form, his information will be filled automatically.
Is it possible? If possible, how?