text:
Q: Ranking algorithm of different weighted resources I have a list of items that represent cells, now i query each cell value to get a set of possible categories that this cell might belong to, these categories are weighted. For Example:
Microsoft is: {Software=83.543266, Video Game Platform=132.297455, Degree=71.624733, Organization=208.17038, Programming Language=66.998901, File Format=67.159828}

apple is: {Physicist=50.008327, Organism Classification=145.239532, Video Game Platform=86.5653, Computer=60.457172, Organization=199.53299, Record label=53.477039}

Banana is: {Musical Group=27.214769, Organism Classification=136.063583, Writer=27.566528, Musical instrument=29.285137, Organization=36.962833, TV Program=32.693085}

Blackberry is: {Software=23.69421, Organism Classification=64.572891, Operating System=90.257011, City/Town/Village=16.836142, Computer=34.484653}

The weights that i get for each result are independent at cell level, so Microsoft having a very high confidence as an organization does not relate to the confidence score of Apple organization confidence.
Now i have two problems, the first is to compare two different cells and compute a similarity score, for example how similar apple is to Microsoft having these possible categories for each.
Second, i want to deduce a global common category for the column that represents these cells, for example if i run a simple algorithm that will calculate the number of categories occurrences and the average of their confidences will not be accurate.
I will appreciate any help.

A: For the first question, a cosine of the angle between the two (aligned) category vectors of two given items is often used as a measure of similarity.
I don't quite understand the second question. Are you referring to some sort of dimensionality reduction / latent factor approach applied to the category vectors?


text:
Q: Google analytics Referrer Campaign I want to add the Referrer Campaign analytics in my app, i have gone through the following links links
Do I need to just add the following declaration in the manifest
OR
I need to create my own receiver to handle the task of sending my referrer data to google analytics??
<service android:name="com.google.android.gms.analytics.CampaignTrackingService" />
    <receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
              android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>

PLease help
Thanks in advance

A: You only need to add the service and the receiver definition to your application manifest. The implementation for both is provided by the Google Play Services library.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I fix this Anaconda issue? Anaconda navigator will not open because of an import error.
I tried searching for solutions but nothing has worked so far. I updated anaconda and reinstalled it and that did not work. After I initially installed Anaconda, I created a virtual environment in PyCharm and then both programs actually stopped working. There seems to be a file in PyQt5 that is lacking permissions but I am not sure how to solve that problem or troubleshoot.
Image is embedded in the link. It says " File "C:\Users\user\anaconda3\lib\site-packages\qtpy\QtCore.py", line 15, in
from PyQt5.QtCore import *
ImportError: DLL load failed while importing QtCore: Access is denied."


text:
Q: WPF Read cells from DataGrid with list I am writing a code in C# with WPF and I want to read the Item/Value of the selected Cell/Row.
Here is the code behind the DataGrid!
Thanks and Greets!
class Zeiten
{
    public string Linie { get; set; }
    public string Von { get; set; }
    public string Abf { get; set; }
    public string Nach { get; set; }
    public string Ank { get; set; }

    public Zeiten(string Linie, string Von, string Abf, string Nach, string Ank)
    {
        this.Linie = Linie;
        this.Von = Von;
        this.Abf = Abf;
        this.Nach = Nach;
        this.Ank = Ank;
    }
}

var items = new List<Zeiten>();
items.Add(new Zeiten(linie, Properties.Settings.Default.StarName, result.ToString("H:mm"), ziel, result2.ToString("H:mm")));
ZeitList.ItemsSource = items;

A: To work with WPF, I suggest you to use MVVM, and use MVVM Light Toolkit to make things easy to you.
But if you want to keep using code-behind, you can define SelectionChanged event in DataGrid.
So in XAML you must have SelectionChanged defined, like that:
<DataGrid x:Name="dataGrid" SelectionChanged="Selector_OnSelectionChanged"/>

And in you code-behind you must have the code for this event, like that:
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var grid = (DataGrid)sender;
    Zeiten selectedItem = (Zeiten)grid.SelectedItem;
    MessageBox.Show("Selected value");
    MessageBox.Show("Linie: " + selectedItem.Linie);
    MessageBox.Show("Von: " + selectedItem.Von);
    MessageBox.Show("Abf: " + selectedItem.Abf);
    MessageBox.Show("Nach: " + selectedItem.Nach);
    MessageBox.Show("Ank: " + selectedItem.Ank);
}


text:
Q: Transferring duplicates in column to another page using a collection I am trying to move items within a column onto another page if a duplicate with specific criteria.
My code stops at my second if statement and I can't figure out how to search the collection with my new rows value. I feel like I almost got it but don't know how to fix it.
Sub duplicates ()

Dim tasks as collection
Set tasks = new collection

Dim row, m as long
Dim task as variant

Row = 9
M= 3

 Do until trim(sheets("itemreport").range("k" & row).value) =""

 If trim(sheets("itemreport").range("f" & row).value) = "credited"     then

  If trim(sheets("itemreport").range("k" & row).value = tasks(item)      then 'Part I am having trouble on
       Sheets("credited").range("r" & m) =  trim(sheets("itemreport").range("k" & row).value)
       M = m +1

       Else: tasks.add (trim(sheets("itemreport").range("k" & row).value)
End if
End if

Row = row + 1

Loop

A: May Try
Sub duplicates()
Dim Tasks As Collection
Set Tasks = New Collection
Dim Rw, m As Long, i As Long
Dim Task As Variant
Dim WsSrc As Worksheet, WsTrg As Worksheet
Dim DupFound As Boolean
Set WsSrc = ThisWorkbook.Sheets("itemreport")
Set WsTrg = ThisWorkbook.Sheets("credited")

Rw = 9
m = 3
With WsSrc
Do Until Trim(.Range("k" & Rw).Value) = ""
    If Trim(.Range("f" & Rw).Value) = "credited" Then
        DupFound = False
            For i = 1 To Tasks.Count
                If Trim(.Range("k" & Rw).Value) = Tasks(i) Then  'Part I am having trouble on
                WsTrg.Range("r" & m) = Trim(.Range("k" & Rw).Value)
                m = m + 1
                DupFound = True
                Exit For
                End If
            Next i
            If DupFound = False Then
            Tasks.Add Trim(.Range("k" & Rw).Value)
            End If
     End If
Rw = Rw + 1
Loop
End With
End Sub


text:
Q: How do I implement a trait for all lifetimes of the struct? I reduced my problem to this minimum reproducible example (playground):
use std::marker::PhantomData;

pub trait D<'a> {
    type A: A + 'a;
    type B: B + 'a;
}

pub trait A {
    fn a(self);
}

pub trait B {
    fn b(self);
}

pub struct AA {}

impl A for AA {
    fn a() {}
}

pub struct BB<'a> {
    phantom: PhantomData<&'a u8>,
}

impl<'a> B for BB<'a> {
    fn b() {}
}

impl<'a: 'd, 'd> D<'d> for E<'a> {
    type A = AA;
    type B = BB<'a>;
}

#[derive(Clone)]
pub struct E<'a> {
    phantom: PhantomData<&'a u8>,
}

pub struct S<D_T>
where
    D_T: for<'d> D<'d>,
{
    a: D_T,
}

pub enum R<'a> {
    RR(S<E<'a>>),
}

I'm getting
error: implementation of `D` is not general enough
  --> src/lib.rs:48:8
   |
3  | / pub trait D<'a> {
4  | |     type A: A + 'a;
5  | |     type B: B + 'a;
6  | | }
   | |_- trait `D` defined here
...
48 |       RR(S<E<'a>>),
   |          ^^^^^^^^ implementation of `D` is not general enough
   |
   = note: `D<'0>` would have to be implemented for the type `E<'a>`, for any lifetime `'0`...
   = note: ...but `D<'_>` is actually implemented for the type `E<'1>`, for some specific lifetime `'1`

I have a small idea why it's happening, but is there a way to have BB with a reference in this case? Most of the things here are from a library I don't control so I cannot change them.

A: The struct S would need D to be implemented for D_T for all lifetimes, which would also include 'static. Now, S is used in enum R with type E, with a generic lifetime 'a. If 'a is anything but 'static, type B of struct D could not possibly be implemented containing a non-static reference. This simply can not work, and something needs changing.
The first option would be to make enum R use 'static lifetime in E, but that would be rather unpractical.
Another option would be to remove the D_T: for<'d> D<'d> requirement from S, adding an additional lifetime argument, and adding phantom data to the structure.
If neither of them are possible, and I am not missing anything, there is not much you can do without resorting to runtime checks, and making the BB type not be lifetime bound (using reference counting). You would need to use either Rc<BB> as B, or have a Rc<SomeType> inside the BB. The former would look something like this:
impl<'d> D<'d> for E {
    type A = AA;
    type B = Rc<BB>;
}

#[derive(Clone)]
pub struct E {
    ref_counted: Rc<BB>
}

pub struct BB {

}

impl B for Rc<BB> {
    fn b(mut self) {
        if let Some(bb) = Rc::get_mut(&mut self) {
            //code with BB's MUTABLE REFERENCE
        }
    }
}

pub struct S<D_T>
where
    D_T: for<'d> D<'d>,
{
    a: D_T
}

pub enum R {
    RR(S<E>),
}

The B implementation uses a mutable reference of the underlying value in the method, if you would like to consume the value inside ref_counted instead, you would have to try something like this:
impl B for Rc<BB> {
    fn b(mut self) {
        match Rc::try_unwrap(self) {
            Ok(bb) => {
                //code with BB's VALUE
            },
            Err(bbrc) => {
                //we can not consume the value in self, because
                //there was a reference held somewhere else in the code
                //here lies code with BB's reference counted pointer
            }
        }
    }
}


text:
Q: Retrieve data from Firebase before adding to a map I'm building an application where a user can store companies information (like name, address, latitude, longitude to a Firebase real-time database).
With that information, those companies are then presented in a map as annotations.
My viewDidLoad is shown below
override func viewDidLoad() {
    super.viewDidLoad()

    // Definitions
    let autenticacao = Auth.auth()
    let idUsuarioLogado = (autenticacao.currentUser?.uid)!
    let database = Database.database().reference()
    let usuarios = database.child("usuarios")
    let clinicas = database.child("clinicas")

    // Map - User location
    self.mapa.delegate = self
    self.gerenciadorLocalizacao.delegate = self
    self.gerenciadorLocalizacao.desiredAccuracy = kCLLocationAccuracyBest
    self.gerenciadorLocalizacao.requestWhenInUseAuthorization()
    self.gerenciadorLocalizacao.startUpdatingLocation()

    // retrieve user information
    usuarios.child(idUsuarioLogado).observe(DataEventType.value) { (snapshot) in
        let dados = snapshot.value as? NSDictionary

        let emailUsuario = dados?["email"] as! String
        let nomeUsuario = dados?["nome"] as! String
        let perfilUsuario = dados?["perfil"] as! String
        let idUsuario = snapshot.key

        let usuario = Usuario(email: emailUsuario, nome: nomeUsuario, uid: idUsuario, perfil: perfilUsuario)
        print("User profile \(perfilUsuario)")
    }

    // Clinicas listeners
    clinicas.observe(DataEventType.childAdded) { (snapshot) in
        let dados = snapshot.value as? NSDictionary
        //print("Dados na leitura \(dados)")
        let clinica = Clinica()
        clinica.identificador = snapshot.key
        clinica.nome = dados?["nome"] as! String
        clinica.endereco = dados?["endereco"] as! String
        clinica.cidade = dados?["cidade"] as! String
        clinica.cep = dados?["cep"] as! String
        clinica.estado = dados?["estado"] as! String
        clinica.latitude = dados?["latitude"] as! String
        clinica.longitude = dados?["longitude"] as! String
        clinica.urlImagem = dados?["urlImagem"] as! String
        clinica.idImagem = dados?["idImagem"] as! String
        self.clinicasR.append(clinica)
    }

    // add annotations to the map
    for oneObject in self.todasAnotacoes {
        print("Oneobj \(oneObject)")
        let umaAnotacao = MinhaAnotacao()
        var oneObjLoc: CLLocationCoordinate2D = CLLocationCoordinate2DMake(oneObject.objLat, oneObject.objLong)
        umaAnotacao.coordinate = oneObjLoc
        umaAnotacao.title = oneObject.objName
        umaAnotacao.subtitle = oneObject.objDesc
        umaAnotacao.category = oneObject.objCat
        self.anotacaoArray.append(umaAnotacao)
        self.mapa.addAnnotations(self.anotacaoArray)
    }
}

My viewDidLoad is "structured" in 4 main blocks (even though they run in a different order given they are asynchronous):

*

*Definition;

*Retrieve user profile;

*Retrieve companies information (name, latitude, longitude);

*Add annotations to the map.

As those are asynchronous functions, they run in different order and this is what is causing trouble to me.
note: There is still one piece missing here that is to feed all annotations to the variable todasAnotacoes which I'll do once I can retrieve data before triggering add annotation "block".
As annotation info comes from the firebase database, I should only have it executed once the clinicas.observe(DataEventType.childAdded) { (snapshot) in is concluded.
As is today, the sequence Xcode runs is:

*

*Definitions

*Add annotations;

*retrieve data from firebase with companies details

I've tried adding the add annotation block to the closure, adding a dispatchqueue but none of those really worked. I also did a lot os search in stackoverflow but I couldn't find anything that i can use (or I wasn't able to understand).
So, in summary I need to run the add annotations after retrieving all data from Firebase.
Any ideas on how I could do that?
EDIT 1 - Final code with the suggested updates
override func viewDidLoad() {
    super.viewDidLoad()

    // Retrieving Logger user data and hidding "add" button if applicable
    ProgressHUD.show("Carregando...")
    let autenticacao = Auth.auth()
    let idUsuarioLogado = (autenticacao.currentUser?.uid)!
    let database = Database.database().reference()
    let usuarios = database.child("usuarios")
    var isUserLoaded = false
    var isClinicsLoaded = false

    usuarios.child(idUsuarioLogado).observe(DataEventType.value) { (snapshot) in
        let dados = snapshot.value as? NSDictionary

        let emailUsuario = dados?["email"] as! String
        let nomeUsuario = dados?["nome"] as! String
        let perfilUsuario = dados?["perfil"] as! String
        let idUsuario = snapshot.key

        let usuario = Usuario(email: emailUsuario, nome: nomeUsuario, uid: idUsuario, perfil: perfilUsuario)
        isUserLoaded = true
        if (isUserLoaded && isClinicsLoaded) {
            self.addAnnotationsToMap();
        }
        //print("\(usuario.email) e \(usuario.nome) e \(usuario.uid) e \(usuario.perfil)")
    }

    // Option to code above
    /*if Auth.auth().currentUser != nil {
     if let uid = (Auth.auth().currentUser?.uid) {

     let database = Database.database().reference()
     let usuarios = database.child("usuarios").child(uid)

     usuarios.observe(.value) { (snapshot) in
     let dados = snapshot.value as? NSDictionary

     let emailUsuario = dados?["email"] as! String
     let nomeUsuario = dados?["nome"] as! String
     let perfilUsuario = dados?["perfil"] as! String
     let idUsuario = snapshot.key

     let usuario = Usuario(email: emailUsuario, nome: nomeUsuario, uid: idUsuario, perfil: perfilUsuario)
     print("Got here \(usuario.email) e \(usuario.nome) e \(usuario.uid) e \(usuario.perfil)")
     if perfilUsuario != "admin" {
     self.navigationItem.rightBarButtonItems?.remove(at: 1)
     print("Disable + Button")
     }

     }
     }
     }*/

    // Map - User location
    self.mapa.delegate = self
    self.gerenciadorLocalizacao.delegate = self
    self.gerenciadorLocalizacao.desiredAccuracy = kCLLocationAccuracyBest
    self.gerenciadorLocalizacao.requestWhenInUseAuthorization()
    self.gerenciadorLocalizacao.startUpdatingLocation()
    let clinicas = database.child("clinicas")

    // Clinicas listeners
    clinicas.observe(DataEventType.value) { (snapshots) in
        for child in snapshots.children {
            let snapshot = child as! DataSnapshot

            print("Clinicas Mapeadas - end")
            let dados = snapshot.value as? NSDictionary
            //print("Dados na leitura \(dados)")
            let clinica = Clinica()
            clinica.identificador = snapshot.key
            clinica.nome = dados?["nome"] as! String
            clinica.endereco = dados?["endereco"] as! String
            clinica.cidade = dados?["cidade"] as! String
            clinica.cep = dados?["cep"] as! String
            clinica.estado = dados?["estado"] as! String
            clinica.latitude = dados?["latitude"] as! String
            clinica.longitude = dados?["longitude"] as! String
            clinica.urlImagem = dados?["urlImagem"] as! String
            clinica.idImagem = dados?["idImagem"] as! String

            self.clinicasR.append(clinica)
            self.todasAnotacoes.append((objLat: Double(clinica.latitude) as! CLLocationDegrees, objLong: Double(clinica.longitude) as! CLLocationDegrees, objName: clinica.nome, objDesc: clinica.endereco, objId: clinica.identificador))
        }
        isClinicsLoaded = true
        if (isUserLoaded && isClinicsLoaded) {
            self.addAnnotationsToMap();
        }
    }

    /* NOT IN USE FOR NOW
     let latitude = Double(-23.623558)
     let longitude = Double(-46.580787)
     let localizacao: CLLocationCoordinate2D = CLLocationCoordinate2D.init(latitude: latitude, longitude: longitude)
     let span: MKCoordinateSpan = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01)
     let regiao = MKCoordinateRegion.init(center: localizacao, span: span)
     self.mapa.setRegion(regiao, animated: true)*/

    ProgressHUD.dismiss()
}

// add annotations to the map
func addAnnotationsToMap() {
    anotacaoArray = []
    for oneObject in self.todasAnotacoes {
        for oneObject in self.todasAnotacoes {
            // print("Oneobj \(oneObject)")
            let umaAnotacao = MinhaAnotacao()
            var oneObjLoc: CLLocationCoordinate2D = CLLocationCoordinate2DMake(oneObject.objLat, oneObject.objLong)
            umaAnotacao.coordinate = oneObjLoc
            umaAnotacao.title = oneObject.objName
            umaAnotacao.subtitle = oneObject.objDesc
            umaAnotacao.identicadorMapa = oneObject.objId
            self.anotacaoArray.append(umaAnotacao)
            print("Annotation added \(todasAnotacoes.count) - end")

        }
        self.mapa.addAnnotations(self.anotacaoArray)
        self.todasAnotacoes = []
        self.anotacaoArray = []

        // print("Annotations added 2 - end")

    }
}

A: The second observer in your code is using .childAdded, which means that closure gets called for each individual child node under clinicas. This makes it hard to know when you're done with clinics, so I recommend first switching that observer over to .value, with something like:
clinicas.observe(DataEventType.value) { (snapshots) in
  for child in snapshots.children {
    let snapshot = child as! DataSnapshot

    let dados = snapshot.value as? NSDictionary
    //print("Dados na leitura \(dados)")
    let clinica = Clinica()
    clinica.identificador = snapshot.key
    clinica.nome = dados?["nome"] as! String
    clinica.endereco = dados?["endereco"] as! String
    clinica.cidade = dados?["cidade"] as! String
    clinica.cep = dados?["cep"] as! String
    clinica.estado = dados?["estado"] as! String
    clinica.latitude = dados?["latitude"] as! String
    clinica.longitude = dados?["longitude"] as! String
    clinica.urlImagem = dados?["urlImagem"] as! String
    clinica.idImagem = dados?["idImagem"] as! String
    self.clinicasR.append(clinica)
  }
  // At this point we're done with all clinics
}

As you'll have notice this code now uses a loop to iterate over snapshots.children. So we're processing all child nodes of clinicas in one closure, which makes it much easier to know when we're done.

Now with the above change we have two closures that get called individually, and you have some code that you want to run when both of them are done. There are a few ways to synchronize this code.
The first way is what you've already tried: putting the clinicas.observe block into the closure of usuarios.child(idUsuarioLogado).observe(. Now that the clinics observer uses .value, you'll find that this is much easier to get working.
But I'd like to show an alternative below, where we use two simple flags to determine if both closures are done. For this you will have to put the code that runs after the data is loaded into a separate function, something like this:
func addAnnotationsToMap() }
  for oneObject in self.todasAnotacoes {
    ...
  }
}

Now in each of the two closures, we're going to set a flag when they're done. And then at the end of each of the closures, we'll detect whether both flags are set, and then call the new function if we have all data we need.
So at the start of viewDidLoad we define our two flags:
let isUserLoaded = false
let isClinicsLoaded = false

And then at the end of loading the user:
usuarios.child(idUsuarioLogado).observe(DataEventType.value) { (snapshot) in
    let dados = snapshot.value as? NSDictionary

    let emailUsuario = dados?["email"] as! String
    let nomeUsuario = dados?["nome"] as! String
    let perfilUsuario = dados?["perfil"] as! String
    let idUsuario = snapshot.key

    let usuario = Usuario(email: emailUsuario, nome: nomeUsuario, uid: idUsuario, perfil: perfilUsuario)

    isUserLoaded = true
    if (isUserLoaded && isClinicsLoaded) {
      addAnnotationsToMap();
    }
}

And similar code (setting the isClinicsLoaded flag) to the other closure.
With these in place, you'll start loading the user data and clinics when the code runs, and then whichever one of them completes last, will call the new addAnnotationsToMap function.

Another alternative is to use a DispatchGroup, which is an Apple-specific construct that can also make this much simpler. Read more about it in this answer (and the links from there): Wait until swift for loop with asynchronous network requests finishes executing


text:
Q: SBT `session save` - [info] No session settings defined I try SBT following tutorial steps:

$ mkdir foo-build
$ cd foo-build
$ touch build.sbt
$ sbt
...
sbt:foo-build>
...
sbt:foo-build> compile
sbt:foo-build> run
[info] Packaging ~/Development/projects/research/scala/foo-build/target/scala-2.12/foo-build_2.12-0.1.0-SNAPSHOT.jar ...
[info] Done packaging.
[info] Running example.Hello
Hello
[success] Total time: 0 s, completed Aug 4, 2018, 12:10:41 PM
sbt:foo-build> scalaVersion
[info] 2.12.6
sbt:foo-build> session save
[info] No session settings defined.

following documentation, I expect

Save the session to build.sbt
We can save the ad-hoc settings using session save.

sbt:foo-build> session save
[info] Reapplying settings...
build.sbt file should now contain:
ThisBuild / scalaVersion := "2.12.6"

but it is not with message [info] No session settings defined..
Is any ideas how to resolve this issue?

A: If I follow the steps you provided, you did not made changes to your build. Looks like you have forgotten this step :
set ThisBuild / scalaVersion := "2.12.6"

Hence the message [info] No session settings defined..


text:
Q: How to divide a LINQ query in small group to avoid Timeout expired exception? I have LINQ query as following
HashSet<Guid> temp1 ; // Getting this value through another method

var Ids = temp1.Except((from temp2 in prodContext.Documents
                        where temp1.Contains(temp2.id)
                        select temp2.id)).ToList();

Here, temp1 has around 40k values. I'm getting timeout error sometimes, How can I divide this query using while or any other loop so that it won't give me timeout error.
I tried to set Connect Timeout in connection string and for database context but nothing works.
Any suggestion please

A: This is one of those unusual operations that is likely to be a query that can more effectively be performed in memory by the application rather than by the database.  Instead of trying to send all of the id values you have in your set to the DB, have it find all of the items with those IDs, and then send them all back to you, it's very plausibly better to just get all of the document ids and filter them on the application side of things.
var documentIds = prodContext.Documents.Select(doc => doc.id);
var Ids = temp1.Except(documentIds).ToList();

Now, depending on how many documents you have, even that could theoretically time out.  If it would, then you'll need to paginate the fetching of all of the document IDs.  You can use the following method to paginate any query to avoid fetching the entire result set all at once:
public static IEnumerable<IEnumerable<T>> Paginate<T>(
    this IQueryable<T> query,
    int pageSize)
{
    int page = 0;
    while (true)
    {
        var nextPage = query.Skip(page * pageSize)
            .Take(pageSize)
            .ToList();
        if (nextPage.Any())
            yield return nextPage;
        else
            yield break;
        page++;
    }
}

This allows you to write:
var documentIds = prodContext.Documents.Select(doc => doc.id)
    //play around with different batch sizes to see what works best
    .Paginate(someBatchSize)
    .SelectMany(x => x);
temp1.ExceptWith(documentIds);

A: Here's a way to do it where it combines both pagination and caching.
This way it only caches the one page size at a time to prevent memory overloading and prevent the time out. I hope this works.
int pageSize = 1000;

HashSet<Guid> temp1;

List<Guid> idsFromTable = new List<Guid>();

var Ids = temp1.ToList();
for(int i = 0; true; i++)
{
    //Cache the table locally to prevent logic running while selecting on page size
    idsFromTable.AddRange(prodContext.Documents.Skip(pageSize * i).Take(pageSize).Select(x=> x.id));

    if(idsFromTable.Any())
    {
        //Then use the cached list instead of the datacontext
        Ids = Ids.Except(idsFromTable).ToList();
        idsFromTable.Clear();
    }
    else
        break;
}

A: Similarly to Servy's answer you might want to try paginating the queries as opposed to just pulling them all in. The efficiency of this depends on the DB you are using, I certainly got some mileage out of it on Informix. In this case the logic would look like this
HashSet<Guid> ids... //Got from another method
List<Guid> validIds = new List<Guid>();

const Int32 BUFFERSIZE = 1000;
var validationBuffer = new List<Guid>(BUFFERSIZE);

foreach(var g in ids)
{
    validationBuffer.Add(g)
    if(validationBuffer.Count == BUFFERSIZE)
    {
         validIds.AddRange(
             prodContext.Documents
                 .Select(t => t.id)
                 .Where(g => validationBuffer.Contains(g)));
         validationBuffer.Clear();
    }
}

//Do last query
validIds.AddRange(
    prodContext.Documents
        .Select(t => t.id)
        .Where(g => validationBuffer.Contains(g)));

var missingIds = ids.Except(validIds);


text:
Q: What are the solutions for com.couchbase.client.java.query.dsl.Sort issue? This is one of error getting class,
import com.bookingsite.acme.config.document.paymentoption.PaymentGatewayConfiguration;
import com.bookingsite.acme.config.dto.paymentgatewaysearchrequest.PaymentGatewayConfigSearchRequestDTO;
import com.bookingsite.acme.config.dto.paymentgatewaysearchrequest.PaymentOptionsDTO;
import com.couchbase.client.java.query.dsl.Sort;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
public class PaymentGatewaySearchData {

    private String searchQuery;
    private Sort sort;
    private int offset;
    private int limit;
    private int totalCount;

    private List<PaymentGatewayConfiguration> paymentGatewaySearchResponseList;

    private PaymentGatewayConfigSearchRequestDTO paymentGatewayConfigSearchRequestDTO;

    private List<PaymentOptionsDTO> paymentOptions;

}

I Upgraded Spring boot version to 2.7.4 and currently we using Couchbase to SDK3 version.After that getting this error.
other used methords
public Sort getOrderByQuery(
            PaymentTemplateConfigSearchFilterRequestDTO paymentTemplateConfigSearchFilterRequestDTO) {

        if (validateOrderBy(paymentTemplateConfigSearchFilterRequestDTO)) {
            if (paymentTemplateConfigSearchFilterRequestDTO.getSortDirection().equals(SortDirectionDTO.DESCENDING)) {
                return Sort.desc(paymentTemplateConfigSearchFilterRequestDTO.getSortBy().getAction());
            } else {
                return Sort.asc(paymentTemplateConfigSearchFilterRequestDTO.getSortBy().getAction());
            }

        } else {

            return Sort.desc(N1QlQueryConstants.TEMPLATEMODIFIEDDATE);

        }

    }

What would be the best possible options?

A: I imagine the compiler is complaining that com.couchbase.client.java.query.dsl.Sort does not exist.
This Couchbase Forum post explains why the classes in com.couchbase.client.java.query.dsl from SDK 2 were not carried forward to SDK 3.
If you wish to continue using the DSL classes, the recommendation is to copy the relevant source code from SDK 2 into your project.
UPDATE: There's now a GitHub repo with the "missing" experimental Query DSL classes from SDK 2, adapted for SDK 3. Now it really should be as simple as copying these classes into your project: https://github.com/couchbaselabs/couchbase-java-sdk2-migration-kit

A: QueryDSL is back in spring-data-couchbase.
Can you please open an issue for this?
https://github.com/spring-projects/spring-data-couchbase/issues


text:
Q: Ubuntu 13.04 Installation on Lenovo U410 dual boot with Windows 8 I've just bought an Lenovo U410 and want to dual boot Ubuntu 13.04 (or the LTS, not that worried) and the included Windows 8. I've seen that previously the SSD cache/Raid arrangement of the U410 causes problems for dual booting, but all the threads I've seen are about Win7 and 12.10.
My question is is there any difference in trying to work with 13.04 and Windows 8? And does anyone have a step-by-step for how to do this (a verbose one because it's a while since I've installed Ubuntu on anything!).
Many thanks
Marcus.

A: Each new version of Ubuntu is working better with UEFI. Also the vendors are fixing the bugs they had in UEFI as they only tested with Windows.
If your model is an Ultrabook, you have UEFI as a new way to install, dual video which may require some effort and Intel SRT or RAID that adds issues.
If you are primarily a Windows user you proably want to keep the Intel SRT as it provides some speed up to Windows. Some with larger SSD just install Ubuntu to SSD and have a faster Ubuntu but then Windows is just running from hard drive like Windows 7 did.
You must turn off the permanent hibernation or fast boot and remove the RAID meta-data. Turning Intel SRT back on will create the RAID on the SSD if that is what you want.
Always backup efi partition and your Windows install first. Make a Windows repair flash drive.
Fast Startup off/hibernation
http://www.eightforums.com/tutorials/6320-fast-startup-turn-off-windows-8-a.html
Force removal of hiberfil from Ubuntu
http://www.hecticgeek.com/2013/01/mount-windows-8-partition-ubuntu-hybrid-boot/
Remove RAID:
sudo dmraid -E -r /dev/sda
sudo dmraid -E -r /dev/sdb

Bumblebee:
https://wiki.ubuntu.com/Bumblebee
Also shows Windows 8 screens
Installing Ubuntu Alongside a Pre-Installed Windows with UEFI
Shows install with screen shots.
https://help.ubuntu.com/community/UEFI
Boot Repair -Also handles LVM, GPT, separate /boot and UEFI dual boot. required for UEFI & grub bug fixes
https://help.ubuntu.com/community/Boot-Repair


text:
Q: MS Excel VBA - Looping through columns and rows Hello stackoverflow community,
I must confess I primarily code within MS Access and have very limited experience of MS Excel VBA.
My current objective is this, I have an "Expense Report" being sent to me with deductions, this report has many columns with different account names that may be populated or may be null.
My first step will be to start on the first record (Row 14; Column A-K contains personal info regarding the deduction) then skip to the first deduction account (deduction accounts start at column L and span to column DG) checking if each cell is null, if it is then keep moving right,If there is a value present, I need to copy it into an external workbook "Payroll Template" starting at row 2 (Column J for the deduction itself), as well as copy some personal info from the original row in the "Expense Report" related to that deduction (currRow: Column C,E,F from "Expense Report" to "Payroll Template" Columns B,C,D).
Then move to the right until the next cell contains a value, and repeat this process on a new row in the "Payroll Template". Once the last column (DG) has been executed I want to move to the next row (row 15) and start the process again all the way until the "LastRow" in my "Used Range".
I greatly appreciate any feedback, explanations, or links that may point me towards my goal. Thank you in advance for taking the time to read though this!
Current state of code:
`< Sub LoadIntoPayrollTemplate()
Dim rng As Range
Dim currRow As Integer
Dim UsedRng As Range
Dim LastRow As Long

Set UsedRng = ActiveSheet.UsedRange
currRow = 14

Set wb = ActiveWorkbook '"Expense Report"
Set wb2 = MyFilepath '"Payroll Template"

'Copied from another procedure, trying to use as reference
LastRow = rng(rng.Cells.Count).Row
Range("A14").Select
Do Until ActiveCell.Row = LastRow + 1
    If (ActiveCell.Value) <> prev Then

        currRow = currRow + 1

    End If

    ActiveCell.Offset(1, 0).Select
Loop

With Worksheets("Collections")
    lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    Set rng = .Range(.Cells(14, 12), Cells(lstRow, 111))
End With

End Sub>`

A: The following code may do what you are after:
Sub LoadIntoPayrollTemplate()
    Dim currRowIn As Long
    Dim currColIn As Long
    Dim currRowOut As Long
    Dim wb As Workbook
    Dim wb2 As Workbook

    Set wb = ActiveWorkbook '"Expense Report"
    Set wb2 = Workbooks.Open(Filename:=MyFilepath & "\" & "Payroll Template.xlsx")
    'or perhaps
    'Set wb2 = Workbooks.Open(Filename:=wb.path & "\" & "Payroll Template.xlsx")

    With wb.ActiveSheet
        currRowOut = 1
        For currRowIn = 14 To .UsedRange.Row + .UsedRange.Rows.Count - 1
            For currColIn = 12 To 111
                If Not IsEmpty(.Cells(currRowIn, currColIn)) Then
                    currRowOut = currRowOut + 1
                    'I'm not sure which worksheet you want to write the output to
                    'so I have just written it to the first one in Payroll Template
                    wb2.Worksheets(1).Cells(currRowOut, "J").Value = .Cells(currRowIn, currColIn).Value
                    wb2.Worksheets(1).Cells(currRowOut, "B").Value = .Cells(currRowIn, "C").Value
                    wb2.Worksheets(1).Cells(currRowOut, "C").Value = .Cells(currRowIn, "E").Value
                    wb2.Worksheets(1).Cells(currRowOut, "D").Value = .Cells(currRowIn, "F").Value

                End If
            Next
        Next
    End With

    'Save updated Payroll Template
    wb2.Save

End Sub


text:
Q: How to upgrade node js to a specific version in windows 10 I want to upgrade node js to v10.15. How can I do it with or without command prompt in Windows-10.

A: You should have a look at NVM for Windows. It should allow you to install any node version

A: I want to upgrade node js to v10.15
Go to Previous Releases | Node.js. There you will see download options for all previous versions, including 10.15:

Click on "Downloads":

You probably want to download either node-v10.15.0-x64.msi or node-v10.15.0-x86.msi  depending on whether you have a 32 or 64 bit version of Windows 10.
Run the msi installer to install version 10.15.


text:
Q: JS contact form works in Chrome but not IE or FireFox I have the following JS for my contact form:
$(document).ready(function(){
$("#contactForm").on('submit', function(e){
    e.preventDefault();

    if(!$("#name").val() || !$("#email").val() || !$("#message").val()){
        $("#incompleteMessage").fadeIn().delay(2000).fadeOut();
    }else{
        $("#sendingMessage").fadeIn();
        $.ajax( {
            url: "php/mail.php",
            type: "POST",
            data: $("#contactForm").serialize(),
            success: function(){
                $("#sendingMessage").fadeOut();
                $("#successMessage").fadeIn().delay(2000).fadeOut();
                $("#name").val( "" );
                $("#email").val( "" );
                $("#message").val( "" );
            }
        });
    }
    return false;
});
})

This JS works fine in Chrome but seems to have issues in FF and IE. It appears that it doesn't enter the success function and just sits on sending message. This is causing multiple form submissions as users keep clicking.
Can anyone see a problem with the JS or suggest a fix?


text:
Q: Unable to access the radio button group from within the anonymous inner class I am a beginning programmer. Posting a small portion of a GUI application I have created. The problem is that I want the group of Radio buttons and some text boxes to be clear when a button is clicked but the button group is not accessible from within the actionListener for the button. I understand the problem of scope very well but it is necessary to perform this action through the button. Please help me.
               ButtonGroup bg = new ButtonGroup();
               bg.add(rbtn1);
               bg.add(rbtn2);
               bg.add(rbtn3);
               bg.add(rbtn4);

               JButton clrBtn= new JButton("Clear");
               clrBtn.setForeground(SystemColor.textHighlight);
               clrBtn.setFont(new Font("Verdana", Font.BOLD, 18));
               clrBtn.setBounds(198, 353, 98, 36);
               frame.getContentPane().add(clrBtn);

               clrBtn.addActionListener(new ActionListener() {
                      @Override
                      public void actionPerformed(ActionEvent e) {
                             String v = "";
                             textField.setText(v);
                             textField_1.setText(v);
                             textField_2.setText(v);
                             txtKdfj.setText(v);
                        }
                 });


text:
Q: GeoServer WCS geotiff style not loading in ArcMAP I have published a GeoTIFF file using GeoServer's (2.4.5) WCS service.
I also defined a colormap style on GeoServer.  I know the style works, because, when I load the map through WMS the colormap is there and the legend image is also generated.
But when I try to load it into ArcMAP or QGis using WCS, I just get a stretched gray scale.
Opening the same GeoTIFF file directly from the catalog in arcmap, lets me calculate the statistics and histogram, and then I can define and edit a colormap for that layer, but this option to calculate the statistics for the WCS raster is not available.
I also tried to create a classified or unique value colormap in the symbology tab at the properties dialog, but those options are not available for the WCS, only for the file opened directly.
How can I make ArcMap take into account the style information I created using GeoServer or, alternatively, how can I make ArcMap let me create and use a classified colormap for this WCS raster.
Thanks to anyone who tries to help.

A: According to what can be read from ArcGIS` help site (Adding a WCS service to ArcMap), there is no statistical information in the WCS layer that ArcMap can use to provide renderers other than stretched and discrete for WCS raster display.  A WCS layer is different from a file raster layer in this respect.
WMS layers, however, can include style information, which is set up at the map server level.


text:
Q: Is it possible to create a generic mathematical function without using the num_traits crate? I would like to define a square root function, that is generic over all numerical types that can be casted into an f32. I am aware, that my current approach can suffer precision issues, but I am mainly interested in the concept for how I can create such a function.
Here is my current approach:
fn integer_sqrt<T>(num: T) -> T where T: From<f32>, f32: From<T>{
    f32::from(num).sqrt().into()
}

The function itself does compile, but it is hardly of any use, because when I for example try to call the function using an u32, I get the following compilation errors:
error[E0277]: the trait bound `u32: From<f32>` is not satisfied
 --> src/main.rs:2:28
  |
2 |     let res = integer_sqrt(25u32);
  |               ------------ ^^^^^ the trait `From<f32>` is not implemented for `u32`
  |               |
  |               required by a bound introduced by this call
  |
  = help: the following implementations were found:
            <u32 as From<Ipv4Addr>>
            <u32 as From<NonZeroU32>>
            <u32 as From<bool>>
            <u32 as From<char>>
          and 2 others
note: required by a bound in `integer_sqrt`
 --> src/main.rs:6:42
  |
6 | fn integer_sqrt<T>(num: T) -> T where T: From<f32>, f32: From<T>{
  |                                          ^^^^^^^^^ required by this bound in `integer_sqrt`

error[E0277]: the trait bound `f32: From<u32>` is not satisfied
 --> src/main.rs:2:15
  |
2 |     let res = integer_sqrt(25u32);
  |               ^^^^^^^^^^^^ the trait `From<u32>` is not implemented for `f32`
  |
  = help: the following implementations were found:
            <f32 as From<i16>>
            <f32 as From<i8>>
            <f32 as From<u16>>
            <f32 as From<u8>>
note: required by a bound in `integer_sqrt`
 --> src/main.rs:6:58
  |
6 | fn integer_sqrt<T>(num: T) -> T where T: From<f32>, f32: From<T>{
  |                                                          ^^^^^^^ required by this bound in `integer_sqrt`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to 2 previous errors

I do understand why I get these errors, however I do not understand why <f32 as From<u32>> and <u32 as From<f32>> are not implemented, when I can easily cast between them using as.
Here is a Playground illustrating the problem.
Is there any way to achieve the desired behaviour without using the num-traits crate?

A: I usually solve this with macro and custom trait:
pub trait IntSqrt {
    fn isqrt(self) -> Self;
}

macro_rules! impl_int_sqrt {
    ($($t:ty)*) => {
        $(
            impl IntSqrt for $t {
                #[inline]
                fn isqrt(self) -> Self {
                    (self as f64).sqrt() as Self
                }
            }
        )*
    };
}

impl_int_sqrt!(i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize);

#[cfg(test)]
#[test]
fn test() {
    assert!(1i8.isqrt() == 1);
    assert!(2i16.isqrt() == 1);
    assert!(3u32.isqrt() == 1);
    assert!(4usize.isqrt() == 2);
    assert!(5.isqrt() == 2);
    assert!(6.isqrt() == 2);
    assert!(7.isqrt() == 2);
    assert!(8.isqrt() == 2);
    assert!(9.isqrt() == 3);
}


text:
Q: 2 empty pages in the beginning of my Latex paper Using the following packages and settings, two empty pages resulted in the beginning of my paper, the paper including the title is started from the third page. In the first page, I have just "1.5em 0pt". How can I remove the two empty pages?
%\documentclass[8pt]{llncs}
\documentclass[runningheads,a4paper,fleqn]{llncs}
%\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{mathptmx}
\usepackage[T1]{fontenc}
%\usepackage[english,turkey]{babel}
\usepackage{amssymb}
\setcounter{tocdepth}{3}
 \usepackage{graphicx}
\usepackage[export]{adjustbox}
\usepackage{subfiles}
%\usepackage{caption}
\usepackage{mdframed}
\usepackage{pifont}
%\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{float}
\usepackage{graphicx}
\usepackage{multirow}
%\usepackage{algorithmicx}
%\usepackage{amssymb,booktabs}
\usepackage{amsmath}
%\usepackage[belowskip=-1pt,aboveskip=0pt]{mathtools}
\usepackage{changepage}
\usepackage{array}
\usepackage{enumitem}
\usepackage{color}
\usepackage{algpseudocode}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{setspace}
\setlist{nosep}

%\usepackage[ruled,noend]{algorithm2e} %to put 2 algorithm side by side
%for space of refernces%%%%%%%%%%%%
%\usepackage{natbib}
%\setlength{\bibsep}{-3pt}

%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[font=scriptsize,skip=-8pt, belowskip=0pt,aboveskip=1pt]{caption}
\usepackage{subcaption}% http://ctan.org/pkg/subcaption
\captionsetup{compatibility=false}
\sloppy

\DeclareMathSizes{6}{6}{6}{6}
\newcommand{\cmark}{\ding{51}}%
\newcommand{\xmark}{\ding{55}}%
\newcommand\fplus{\mathrel+}

%% Save the class definition of \subparagraph
\let\llncssubparagraph\subparagraph
%% Provide a definition to \subparagraph to keep titlesec happy
\let\subparagraph\paragraph
%% Load titlesec
\usepackage[compact]{titlesec}
%% Revert \subparagraph to the llncs definition
\let\subparagraph\llncssubparagraph
\titlespacing\section {0pt} {12pt plus 0pt minus 2pt} {0pt plus 0pt minus 2pt}
\titlespacing\subsection {0pt} {0pt plus 0pt minus 2pt} {0pt plus 0pt minus 2pt}
\titlespacing\subsubsection {0pt} {0pt plus 0pt minus 2pt} {0pt plus 0pt minus 2pt}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage[utf8]{inputenc}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage[T1]{fontenc}
%\usepackage[english,turkey]{babel}
\usepackage{amssymb}
\setcounter{tocdepth}{3}
 \usepackage{graphicx}
\usepackage[export]{adjustbox}
\usepackage{subfiles}
\usepackage{mdframed}
\usepackage{pifont}
\usepackage{algorithm}
\usepackage{algpseudocode}
%\usepackage[font=footnotesize]{caption}
\usepackage{graphicx}
\usepackage{multirow}
%\usepackage{algorithmicx}
%\usepackage{amssymb,booktabs}
\usepackage{amsmath}
\usepackage{changepage}
\usepackage{array}
\usepackage{enumitem}
\usepackage{color}
%\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\setlist{nosep}
\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\usepackage{algpseudocode}%http://ctan.org/pkg/algorithmicx

\sloppy

\DeclareMathSizes{6}{6}{6}{6}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\setlength\floatsep{10 pt}
%\setlength\textfloatsep{7.5 pt}
%\setlength\intextsep{7.5 pt}

%\doi{10.475/123_4}

% ISBN
%\isbn{123-4567-24-567/08/06}

%Conference
%\conferenceinfo{PLDI '13}{June 16--19, 2013, Seattle, WA, USA}

%\acmPrice{\$15.00}

%\conferenceinfo{WOODSTOCK}{'97 El Paso, Texas USA}

%space of equations
\makeatletter
\g@addto@macro\normalsize{%
  \setlength\abovedisplayskip{0pt}
  \setlength\belowdisplayskip{0pt}
  \setlength\abovedisplayshortskip{0pt}
  \setlength\belowdisplayshortskip{0pt}
}
\makeatother
%psace of section titles

\begin{document}

\mainmatter
% first the title is needed
\title{}
\author{}

\maketitle

A: The issue here is that algpseudocode and algorithmic are not compatible, as illustrated by the following minimal example:
\documentclass{article}

\usepackage{algpseudocode}
\usepackage{algorithmic}

\begin{document}
Lorem ipsum
\end{document}

For this specific reason, if you wish to use algorithmic-like input, the algorithmicx bundle provides the algcompatible package. From the algorithmicx package documentation (section 2.1 The package):

algcompatible is fully compatible with the algorithmic package, it should be used only in old documents

You should therefore avoid loading both algpseudocode and algorithmic, but instead just load algcompatible or algorithmic.

A: After doing disable of \usepackage{algorithmic} and enable of \usepackage{algorithm,algpseudocode}, the problem of showing "1.5em 0pt" at the First blank page is solved now. Tahnks all


text:
Q: Displaying Ajax Sample Results as the Form Loads I've set up a box to display results from an Ajax form, showing water data from US Geological Survey and using a Google chart.  Works great, but I want users to see some sample results when they first load the form instead of an empty box. Not sure how to do it. Here's the code for the form:

Current River Levels

<form>
<select name="users"; onchange="showUser(this.value); drawChart(this.value)";>
<option value="01598500">North Branch at Luke, MD</option>
<option value="01603000">North Branch at Cumberland, MD</option>
<option value="01610000">Potomac River at Paw Paw, WV</option>
<option value="01613000">Potomac River at Hancock, MD</option>
<option value="01619500">Antietam Creek at Sharpsburg, MD</option>
<option value="01638500">Potomac River at Point of Rocks, MD</option>
<option value="01648000">Rock Creek at Sherrill Drive, DC</option>
<option value="01646500">Little Falls, DC</option>
</select>
</form>

##

Select a site or visit our interactive map.

The entire project is located here: http://www.riverexplorer.com/potomax/json_test_20.php

A: Trigger the onchange event when the document is ready.
$(function(){
    $('select[name="users"]').trigger('change');
 });


text:
Q: Netty: how to calculate client request queuing time We have Netty based HTTP server (build on Spring WebFlux) and need to implement a kind of client request statistics (request processing time per type, request queuing time, etc). Could you please advice what is the right way to calculate request queuing time in Netty, i.e. the time between the moment request is accepted by the input socket and passed to the corresponding handler.

A: You should create a WebClient from configured WebClient.Builder that has predefined metrics. For example:
@Configuration
public class WebClientConfiguration {

  @Bean
  public WebClient webClient(WebClient.Builder webClientBuilder) {
    return webClientBuilder
      .build();
  }
}


text:
Q: R: error in mle initial value in 'vmmin' is not finite nll <- function(lambda, kappa){
  logit=function(x) {log(x/(1-x))}
  a=c(1-exp(-(15/lambda)^kappa), 1-exp(-(25/lambda)^kappa), 1-exp(-(35/lambda)^kappa))
  a=logit(a)
  mu = c(0.1, 0.2, 0.3)
  mu = logit(mu)
  cov = matrix(c(0.18830690, 0.00235681, 0.00071954, 0.00235681, 0.00736811, 0.00110457, 0.00071954, 0.00110457, 0.00423955), nrow =3)
  L1 = dmvnorm(a, mu, cov)

  a=c(1-exp(-(25/lambda)^kappa), 1-exp(-(35/lambda)^kappa), 1-exp(-(45/lambda)^kappa))
  a=logit(a)
  mu = c(0.4, 0.1, 0.9)
  mu = logit(mu)
  cov = matrix(c(2.7595442, 0.0045178, 0.0010505, 0.0045178, 0.00972309, 0.0015120, 0.0010505, 0.0015120, 0.0088425), nrow =3)
  L2 = dmvnorm(a, mu, cov)
  -sum(log(L1*L2))
}

> mle(nll, start = list(lambda = 1, kappa = 1))
Error in optim(start, f, method = method, hessian = TRUE, ...) :
  initial value in 'vmmin' is not finite

I'm trying to find the lambda and kappa values that maximize the function above.
My original likelihood function returns L1*L2, but because the mle function requires the negative log-likelihood to be passed in, I modified the function to return -sum(log(L1*L2)) instead.
However, I ran into the above error. And I've also tried specifying dmvnorm(... ,log = TRUE) but that didn't solve the problem.

A: *

*L1 and L2 are both scalars. Assuming we're going to pass log=TRUE to dmvnorm so they are each log-likelihoods, do you mean just -(L1+L2) in the final line?

*by specifying debug(nll) and nll(lambda=1,kappa=1) , then stepping through the code, waiting til we find an infinite value, and then backtracking, we see that 1-exp(-(45/lambda)^kappa) is exactly 1 (exp(-45) is less than 1e-16, the smallest value for which 1+x is > 1, so that the final element of logit(a) is infinite ...

So if I make dmvnorm(...,log=TRUE) in both places, change the last line to return(-(L1+L2)), and change the initial value of lambda to 10, I get a finite value for nll(10,1) (4474), and stats4::mle(nll,start=list(lambda=10,kappa=1)) gives:
Coefficients:
   lambda     kappa
40.622673  4.883857


text:
Q: 'Such' in place of a demonstrative pronoun. Such a configuration or such configuration? I read some explanations about the use of 'such' as a determiner, but I still could not figure this out. If, in scientific/formal writing, I want to use 'such' instead of 'this' to specify a previously mentioned noun, do I need the article a? E.g.:

By adding a correct constant voltage on one of the plates, the AC goes to zero. In such configuration, the DC-voltage is the same as the original potential difference between the materials.

Which one would be correct: such a configuration or such configuration?


text:
Q: Kullback-Leibler divergence functional derivate of push forward measure I am given two metric measure (MM) spaces $(X, \mu, d_{X})$, $(Y, \nu, d_{Y})$, where $X, Y \in \mathbb{E}^{2}$ Euclidean. I would like to minimize the Kullback-Leibler divergence between $\mu$ and $\nu \circ \phi^{-1}$ by optimizing $\phi : Y \rightarrow X$, diffeomorphism. The problem is the following
\begin{equation}
J[\phi] = KL(\mu || \nu \circ \phi^{-1})= \int \log{\left( \frac{d \mu}{d \nu \circ \phi^{-1}} \right)} d\mu \rightarrow min_{\phi}
\end{equation}
To do so I am planning to compute the functional derivative of $J[\phi]$, however I end up with the following expression, which seems hard to variate. In the following $\varepsilon \cdot h = \delta \phi$ is the variation and $\varepsilon \in \mathbb{R}, h \in L^{1}$. Based on my calculations and pushforward by diffeomorphism
\begin{equation}
\left[ \frac{d}{d \varepsilon} J[\phi + \varepsilon \cdot h] \right]_{\varepsilon = 0} = \left[ \frac{d}{d \varepsilon} \int \log \left( \frac{d \mu}{d \nu} \right) d \mu + \int\log(|\det(J_{\phi + \varepsilon \cdot h})|) d \mu \right]_{\varepsilon = 0},\ (1)
\end{equation}
where $J_{\phi}$ is the Jacobian of the diffeomorphism $\phi$. Deriving $(1)$ further one arrives at the following
\begin{equation}
\frac{\delta J[\phi]}{\delta \phi} = (J_{\phi}^{-1})^{T} = (J_{\phi}^{T})^{-1}
\end{equation}
The problem here is, I can't see how this will minimize the KL divergence between $\mu$ and $\nu$. This rather proves that the KL divergence is unchanged when one of the measures is transformed with a diffeomorphism, since if $\phi$ is a diffeomorphism it will be a volume preserving measurable mapping, ending in $\det{(\phi)} =1$.
I have been thinking going on an alternative way with the conjugate of the KL divergence as the following
\begin{equation}
KL(\mu || \nu \circ \phi^{-1})=1 + \sup_{g}\left\{\int g d\mu - \int e^{g} d \nu \circ \phi^{-1} \right \} \text{, g is Borel measurable.}
\end{equation}
Anyone has an idea or approach to minimize the KL divergence between two measures, by a push-forward of one of the measures?


text:
Q: Implementar un CountDown Timer en un servicio Tengo un botón que al presionarse comienza una cuenta atrás, y deseo que esta cuenta se mantenga hasta que termine aun cuando la app se cierre o se cambie de Activity. Tengo entendido que una forma de hacerlo es usar un servicio en segundo plano, pero he leído pero no lo logro entender como implementarlo. Gracias !
Clase para el servicio
package com.example.ash.carritosbeta1;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.TimeUnit;

public class ServicioTimer extends Service {

    String FORMAT = "%02d:%02d:%02d";
    private static String TAG = "Servicio";
    public static final String PAQETE = "com.example.ash.carritosbeta1"; //ejemplo com.proyecto.MainActivity
    Intent bi = new Intent(PAQETE);

    CountDownTimer cdt = null;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Comienza el timer...");
        cdt = new CountDownTimer(9000, 1000) {
            public void onTick(long millisUntilFinished) {
                @SuppressLint("DefaultLocale") String tiempo = ""+String.format(FORMAT,
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

                //con esto se envia el tiempo
                bi.putExtra("Tiempo", tiempo);
                sendBroadcast(bi);
            }
            public void onFinish() {
                //se envia el tiempo finalizado
                bi.putExtra("Fin", "Tiempo terminado!");
                sendBroadcast(bi);
            }
        }.start();
    }

    @Override
    public void onDestroy() {
        cdt.cancel();
        Log.i(TAG, "Timer cancelado");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Activity
public class tiempo_carro1 extends AppCompatActivity {
    private static String TAG = "Servicio";
    TextView contador;
    Button inicar, pausar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tiempo_carro1);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       getSupportActionBar().setDisplayShowHomeEnabled(true);

        contador=(TextView)findViewById(R.id.mostrar);
        contador.setText("00:00:00");
        inicar=(Button)findViewById(R.id.iniciar);
        inicar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //inicia el servicio
                startService(new Intent(tiempo_carro1.this, ServicioTimer.class));

            }
        });
        pausar=(Button)findViewById(R.id.Reinicar);
        pausar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }
    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //aqui obtienes los datos enviados por el servicio
            //obtienes el tiempo que lleva
            if (intent.getExtras() != null) {
                if (intent.hasExtra("Tiempo")) {
                    String tiempo = intent.getStringExtra("Tiempo");
                    contador.setText(tiempo);
                } if (intent.hasExtra("Fin")) {
                    //se recibe que se ha finalizado el contador
                    String tiempo = intent.getStringExtra("Fin");
                    contador.setText(tiempo);
                    inicar.setEnabled(true);
                    //cierras el servicio ya que no es necesario mantenerlo, sera creado al pulsar el boton nuevamente
                    stopService(new Intent(tiempo_carro1.this, ServicioTimer.class));
                }
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(br, new IntentFilter(ServicioTimer.PAQETE));
        Log.i(TAG, "Broadcast registrado");
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(br);
        Log.i(TAG, "Broadcast desligado");
    }

    @Override
    public void onStop() {
        try {
            unregisterReceiver(br);
        } catch (Exception ignored) {}
        super.onStop();
    }
    @Override
    public void onDestroy() {
        stopService(new Intent(tiempo_carro1.this, ServicioTimer.class));
        Log.i(TAG, "Termina el servicioo");
        super.onDestroy();
    }
}

A: Paso a explicarte la manera en la que yo lo haría, el funcionamiento es el siguiente; Se crea un servicio como bien has indicado, el cual se hará cargo de ejecutar la cuenta atrás, éste sera ejecutado desde la actividad al presionar el botón. En la misma actividad, se crea una "escucha" usando un BroadcastReceiver el cual recibirá la información que del servicio tal como el tiempo transcurrido, o cuando finaliza. Si la actividad se cierra, se elimina la escucha de dicho broadcast, si es destruida, se termina el servicio; Estos últimos comportamientos puedes modificarlos según tu preferencia.
La implementación podría ser de la siguiente manera:
SERVICIO:
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.TimeUnit;

public class ServicioTimer extends Service {

String FORMAT = "%02d:%02d:%02d";
private static String TAG = "Servicio";
public static final String PAQETE = "nombre_de_tu_paquete.nombre_atividad"; //ejemplo com.proyecto.MainActivity
Intent bi = new Intent(PAQETE);

CountDownTimer cdt = null;

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "Comienza el timer...");
    cdt = new CountDownTimer(9000, 1000) {
        public void onTick(long millisUntilFinished) {
            String tiempo = ""+String.format(FORMAT,
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                    TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                            TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            //con esto se envia el tiempo
            bi.putExtra("Tiempo", tiempo);
            sendBroadcast(bi);
        }
        public void onFinish() {
            //se envia el tiempo finalizado
            bi.putExtra("Fin", "Tiempo terminado!");
            sendBroadcast(bi);
        }
    }.start();
}

@Override
public void onDestroy() {
    cdt.cancel();
    Log.i(TAG, "Timer cancelado");
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
}

ACTIVITY:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private static String TAG = "Servicio";

TextView contador;
Button iniciar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    contador = (TextView) findViewById(R.id.contador);
    iniciar = (Button) findViewById(R.id.iniciar);
    iniciar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            iniciar.setEnabled(false);
            //inicia el servicio
            startService(new Intent(MainActivity.this, ServicioTimer.class));
        }
    });
}

private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //aqui obtienes los datos enviados por el servicio
        //obtienes el tiempo que lleva
        if (intent.getExtras() != null) {
            if (intent.hasExtra("Tiempo")) {
                String tiempo = intent.getStringExtra("Tiempo");
                contador.setText(tiempo);
            } if (intent.hasExtra("Fin")) {
                //se recibe que se ha finalizado el contador
                String tiempo = intent.getStringExtra("Fin");
                contador.setText(tiempo);
                iniciar.setEnabled(true);
                //cierras el servicio ya que no es necesario mantenerlo, sera creado al pulsar el boton nuevamente
                stopService(new Intent(MainActivity.this, ServicioTimer.class));
            }
        }
    }
};

@Override
public void onResume() {
    super.onResume();
    registerReceiver(br, new IntentFilter(ServicioTimer.PAQETE));
    Log.i(TAG, "Broadcast registrado");
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(br);
    Log.i(TAG, "Broadcast desligado");
}

@Override
public void onStop() {
    try {
        unregisterReceiver(br);
    } catch (Exception e) {}
    super.onStop();
}
@Override
public void onDestroy() {
    stopService(new Intent(MainActivity.this, ServicioTimer.class));
    Log.i(TAG, "Termina el servicio");
    super.onDestroy();
}
}

MANIFEST:
<service android:name=".ServicioTimer"/>

Obviar algún pequeño detalle como que coloques tu FORMAT y lo ordenes a tu preferencia y necesidades, me he tomado la libertad de agregar pequeños comentarios en el código y Logs para que te ayuden a identificar las cosas, cualquier duda puedes dejar un comentario y la intentaré solventar lo antes posible.
EDITO:
Para complementar mi respuesta, agrego un link al código en GitHub, esta solventado el tema de la persistencia si la aplicación es cerrada, y al re-abrirla continue la cuenta regresiva.

A: Si no les corre debe ser por la ruta que le pusieron al servicio en el manifes o puede ser uno de los posibles errores ya que a mi me paso, lo metí dentro de una carpeta donde manejo todas las clases por lo que no me lograba encontrar el servicio y aun así me corría la aplicación pero no me mostraba la cuenta regresiva


text:
Q: VBNet Error: Collection was modified; enumeration operation may not execute This is what happened: on the form load of my application i created a background worker to bind collection (records from database filled in the dataset) on my control. but the problem is when the i updated the records on the database it throws an error if i run this procedure again.
    If xControl.InvokeRequired Then
        Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding)
        Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute.
    Else
        Using ds As DataSet = New DataSet()
            Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString)
                dbAdapter.Fill(ds)
            End Using

            Dim dvm As DataViewManager = New DataViewManager(ds)
            Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0))
            For Each iBind As Binding In xControl.DataBindings
                xControl.DataBindings.Remove(iBind)
            Next
            xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey)
            xControl.Properties.DataSource = iDataList
            xControl.EditValue = Nothing
            txtStatus.Text = "Ready"
        End Using
    End If

A: You have to avoid updation in collection while iterating it using For Each. Use simple For loop instead of For Each.

A: You can't use a For Each loop to remove items from a diction or KeyValuePair, but you can use a regular for loop, get the key and use the key to remove the item from the list.
      For i As Integer = 0 To oDictionary.Count - 1
        Dim sKey = m_oDictionary.ElementAt(i).Key
        m_oDictionary.Remove(sKey)
      Next

A: Solved by adding:
xControl.DataBindings.Clear()
If xControl.InvokeRequired Then
    Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding)
    Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute.
Else
    Using ds As DataSet = New DataSet()
        Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString)
            dbAdapter.Fill(ds)
        End Using

        xControl.DataBindings.Clear() 'HERE

        Dim dvm As DataViewManager = New DataViewManager(ds)
        Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0))
        For Each iBind As Binding In xControl.DataBindings
            xControl.DataBindings.Remove(iBind)
        Next
        xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey)
        xControl.Properties.DataSource = iDataList
        xControl.EditValue = Nothing
        txtStatus.Text = "Ready"
    End Using
End If

A:         Dim index As Integer = 0
opnieuw:
        For Each F In openbestand.file
            If F.Contains("~$") Then
                openbestand.file.Remove(openbestand.file(index))
                openbestand.path.Remove(openbestand.path(index))
                GoTo opnieuw
            Else
                index = (index + 1)
            End If
    Next

A: If you are going to use a loop, you need to ensure that the index is less than the Count, since the count decreases every time a key element is removed:
Dim i As Integer

For i = 0 To dictionary1.Count - 1
    If i <= dictionary1.Count - 1 Then
        Dim sKey = dictionary1.ElementAt(i).Key
        dictionary1.Remove(sKey)
    End If
Next


text:
Q: How can I stop a recordset being returned by a SQL Server stored procedure if an error is encountered after the SELECT Hoping someone can help. I'm trying to stop a stored procedure from returning a recordset that has been selected, if an error is encountered later in the stored procedure. I've included some pseudo code below to show what I'm doing. Basically, the SELECT [Foo] is returning a recordset if the  or COMMIT actions fail and [Tran1] is rolled back. The client does not support multiple recordsets and the  has to come after the SELECT so I'm looking for a command to place in the CATCH block that effectively cancels the SELECT [Foo] and instead enables me to return the recordset created by SELECT -1 AS [Error_Code]
BEGIN TRANSACTION           [Tran1]
    BEGIN TRY
        SET NOCOUNT ON;

        <Do some Update>

        SELECT          [Foo]
        FROM            [Bar]

        <Do some Insert>

        COMMIT TRANSACTION  [Tran1]
    END TRY

    BEGIN CATCH
        ROLLBACK TRANSACTION    [Tran1]
        SELECT          -1      AS  Error_Code
    END CATCH


text:
Q: Internet explorer window.resize fails after using document.write This may be a bug in internet explorer (IE9), wondering if it is known or there is a workaround.
It can be reproduced by opening up the dev console, and executing each of these commands,
window.onresize = function() { alert("onresize"); }

At this point, when you resize the window, the event fires as expected. Now execute,
document.write("test");

After this point window.resize will be null.
That's probably expected since document.write calls document.open which clears everything.
However, even if you add back an event handler, it will never fire,
window.onresize = function() { alert("onresize"); }

A: You have to write the whole script block into the new document. For example:
document.write("
some html

This is because when you call document.write it creates a new document with an "empty" url. Where as your original document comes from a different Url (for example, "http://www.yoursite.com/Page1.aspx". The site for the empty Url is not the same as the site of the original Url. And a browser does not allow script in pages from one site calls script in pages from another site (to avoid cross site script attack). Thus it is not possible for you to call a function defined in "http://www.yoursite.com/Page1.aspx" from a page with null Url. As such you have to write the script code itself into the new document.


text:
Q: How to remove ftp network? I have a dual boot with Windows 7 and Ubuntu 18.04.
Since the begining I had Windows Network , but few days ago a new network called MACHINE appeared (machine is the name of my laptop). I dont know why. I had given my laptop to my cousin for a day , so i thought that maybe he knew but he also has no idea.(See the attatched image) Any advice on how to remove this network.

Also on running "nmap 192.168.1.1" , I get following result

A: It's probably your router, based on it's IP. Many residential routers support ftp and telnet. The reverse name _gateway supports this
Thus, you will have to check the manual of the router for how to disable said services on the router. It has nothing to do with Ubuntu.
You can verify this by running the command ip route and verify that it has a line saying
default via 192.168.1.1 dev ...


text:
Q: I did not understand this question based on ratio and proportion The mileage of a car is 16 km per litre, if the fuel is totally unadulterated. If due to adulteration the mileage reduces by 25%, by what percentage does the cost of maintaining the car per kilometre increase?( Assume that maintenance cost is equal to fuel cost)
When there is no adulteration then mileage is 16 km per litre but when there is adulteration then new mileage is $3/4*16=12$
$4/16*100=25$
But the answer is 33.33. How?

A: Driving 48 km previously took 3 liters of fuel; now it takes 4 liters.
The additional liter is one third of the previous cost.

When you go from speaking about "distance per amount of fuel" to "fuel per fixed distances", the numbers -- and therefore also the ratios -- are replaced by their reciprocals.
So a decrease to $\frac34$ of the former number corresponds to an increase to $\frac43$ of the latter number.
$\frac34$ is $25\%$ less than $1$, but $\frac43$ is $33\frac13\%$ more than $1$.

A: Initially you pay $x$ for $16km$
Now we pay $x$ for $12km$, equivalently, you pay $\frac43x$ for $16km$.
Percentage of cost increase is $$\frac{\text{percentage of change}}{\text{initial  amount}}=\frac{\frac43x-x}{x}=\frac13$$


text:
Q: @PostFilter on a wrapped list? In Spring Security, is it possible to apply @PostFilter to a method that doesn't return a list but a wrapped list, for instance ResponseEntity<List<String>> ?
I mean
@PostFilter("filterObject != DISCARD_STR")
ResponseEntity<List<String>> getStringList();

Will not work, will it ? Because the method don't return a list so filtered object can't be bind to the list elements.
Is there a solution to filter the inner list ?

A: Actually you can do it by using @PostAuthorize and editing the object.
@PostAuthorize("@myService.filter(returnObject.getBody())")
ResponseEntity<List<String>> getStringList();

MyService.java :
@Service
public class MyService {

    public boolean filter(List<String> list) {
        list.remove(DISCARD_STR)
    }

}


text: Q: Detecting if popup was dismissed I have 2 views in my storyboard: a view, then a popup view. What i want to happen is when the user finishes filling out the information on the popup, and pressed the close, for the original view controller to detect if the popup was dismissed. I hope this makes sense! Thanks!


text:
Q: Don't make "destroy all my hat customizations" the default option I prefer wearing different hats on different sites. Different topics call for different personalities. Also I don't want to wear a hat on a site where I haven't earned it.
Can we please have the "only on this site" checkbox ticked by default? The current situation is that we have a big button for "destroy all my hat customizations, no undo, sucks to be you" and a small checkbox for "do the obvious thing and affect just the profile I clicked on". That's backwards.
Even better, pushing a hat to all profiles shouldn't be done from some random profile, it should be a button (with confirmation) on http://winterbash2014.stackexchange.com/. But at least don't make it so easy to do accidentally.

A: I'm going to argue that you are not the majority case, so the default will continue to be "wear on all sites". I have however made one change: We now remember if you've previously checked "only on this site" and keep it checked the next time you open your hat rack. This setting is stored in localStorage, so it's per-site (and per-browser).


text:
Q: catalyst request object json input Sample code:
sub record_put :Private {
    my ( $self, $c, @args ) = @_;

    $c->log->info( join ', ', %{ $c->request->headers } ) ;
    $c->log->info( $c->request->body ) ;

    $c->response->body( $c->request->body ) ;
}

Here's the log data:
[info] user-agent, Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36, connection, keep-alive, accept, application/json, text/javascript, */*; q=0.01, accept-language, en-US,en;q=0.8, x-requested-with, XMLHttpRequest, origin, http://localhost:3000, accept-encoding, gzip,deflate,sdch, content-length, 125, host, localhost:3000, ::std_case, HASH(0xaec0ba0), content-type, application/json, referer, http://localhost:3000/test
[info] /tmp/PM2C6FXpcC

Here's a snippet of text from the Catalyst::Request document:
$req->body

Returns the message body of the request, as returned by HTTP::Body: a string, unless Content-Type is application/x-www-form-urlencoded, text/xml, or multipart/form-data, in which case a File::Temp object is returned.

The File::Temp manpage does not help.  Even the 'object' overloads its stringification, I can't see how to extract the contents.

A: Here's what I used:
  my $rbody = $c->req->body;
  if ($rbody) {
    # Post requests are stored on the filesystem under certain obscure conditions,
    # in which case $rbody is a filehandle pointing to the temporary file
    if (ref $rbody) {           # a filehandle
      $content = join "", readline($rbody);
      close $rbody;
      unlink "$rbody";  # filehandle stringifies to name of temp file
    } else {                    # a string
      $content = $rbody;
    }
  }

The thing you get back from the body method represents a temporary file, and can be treated like a filehandle or like a string.  if you treat it like a filehandle, it reads from the temporary file; if used like a string, its value is the name of the temporary file.  I used the seldom-seen builtin function readline, which is the same as the more common <…> operator.
I don't expect the else path to ever be taken, but it's there defensively, because you never know.
Added 2014-06-09: You need the explicit close; otherwise the code has a file descriptor leak.  Catalyst devs claim that it should be cleaning up the handle automatically, but it doesn't.

A: if you are just trying to parse JSON, the newest stable Catalyst has a method 'body_data' that does this for you (see: http://www.catalystframework.org/calendar/2013/6)


text:
Q: Filter on a nested aggregate SUM function not working I have these two tables (the names have been pluralized for the sake of the example):
Table Locations:
idlocation varchar(12)
name       varchar(50)

Table Answers:
idlocation varchar(6)
question_number varchar(3)
answer_text1    varchar(300)
answer_text2    varchar(300)

This table can hold answers for multiple locations according a list of numbered questions that repeat on each of them.
What I am trying to do is to add up the values residing in the answer_text1 and answer_text2 columns, for each location available on the Locations table but for only an specific question and then output a value based on the result (1 or 0).
The query goes as follows using a nested table Answers to perform the SUM operation:
select
l.idlocation,

'RESULT' = (
              case when (
                select
                sum(cast(isnull(c.answer_text1,0) as int)) +
                sum(cast(isnull(c.answer_text2,0) as int))
                from Answers c
                where b.idlocation=c.idlocation and c.question_number='05'
              ) > 0 then
                           1
              else
                           0
              end
            )

from Locations l, Answers b
where l.idlocation=b.idlocation and b.question_number='05'

In the table Answers I am saving sometimes a date string type of value for its field answer_text2 but on a different question number.
When I run the query I get the following error:

Conversion failed when converting the varchar value '27/12/2013' to data type int

I do have that value '27/12/2013' on the answer_text2 field but for a different question, so my filter gets ignored on the nested select statement after this: b.idlocation=c.idlocation, and it's adding up apparently more questions hence the error posted.
Update
According to Steve's suggested solution, I ended up implementing the filter to avoid char/varchar considerations into my SUM statement with a little variant:
Every possible not INT string value has a length greater than 2 ('00' to '99' for my question numbers) so I use this filter to determine when I am going to apply the cast.
'RESULT' =
           case when (
          select sum(
                          case when len(c.answer_text1) <= 2 then
                             cast(isnull(c.answer_text1,'0') as int)
                          else
                             0
                          end
                         ) +
               sum(
                           case when len(c.answer_text2) <= 2 then
                              cast(isnull(c.answer_text2,'0') as int)
                           else
                              0
                           end
                          )
        from Answers c
                   where c.idlocation=b.idlocation and c.question_number='05'
        ) > 0
           then
                1
           else
                0
           end

A: Your query appears correct enough, which means you have a Question 05 record with a datetime in either the answer_text1 or answer_text2 field.
Give this a shot to figure out which row has a date:
select *
from Answers
where question_number='05'
  and (isdate(answer_text1) = 1 or isdate(answer_text2) = 1)

Furthermore, you could filter out any rows that have dates in them
where isdate(c.answer_text1) = 0
  and isdate(c.answer_text2) = 0
  and ...

A: This is an unfortunate result of how the SQL Server query processor/optimizer works. In my opinion, the SQL standard prohibits the calculation of SELECT list expressions before the rows that will contribute to the result set have been identified, but the optimizer considers plans that violate this prohibition.
What you're observing is an error in the evaluation of a SELECT list item on a row that is not in the result set of your query. While this shouldn't happen, it does, and it's somewhat understandable, because to protect against it in every situation would exclude many efficient query plans from consideration. The vast majority of SELECT expressions will never raise an error, regardless of data.
What you can do is try to protect against this with an additional CASE expression. To protect against strings with the '/' character, for example:
... SUM(CASE WHEN c.answer_text1 IS NOT NULL and c.answer_text1 NOT LIKE '%/%' THEN CAST(c.answer_text1 as int) ELSE 0 END)...

If you're using SQL Server 2012, you have a better option: TRY_CONVERT:
...SUM(COALESCE(TRY_CONVERT(int,c.answer_text1),0)...

In your particular case, the overall database design is flawed, because numeric information should be stored in number-type columns. (This, of course, may not be your fault.) So redesign is an option, putting integer answers in integer-type columns and non-integer answer_text elsewhere. A compromise, if you can't redesign the tables, that I think will work, is to add a persisted computed column with value TRY_CONVERT(int,c.answer_text1) (or its best equivalent, based on what you know about the actual data in the table - perhaps the integer value of only columns containing no non-digit character and having length less than 9).

A: Another option similar in nature to Steve's excellent answer is to filter your Answers table with a subquery like so:
select
        l.idlocation,

        'RESULT' = (
                      case when (
                        select
                        sum(cast(isnull(c.answer_text1,0) as int)) +
                        sum(cast(isnull(c.answer_text2,0) as int))
                        from (select answer_text1, answer_text2, idlocation from Answers where question_number ='05') c
                        where b.idlocation=c.idlocation
                      ) > 0 then
                                   1
                      else
                                   0
                      end
                    )

        from Locations l, Answers b
        where l.idlocation=b.idlocation and b.question_number='05'

More generally, though, you could just have this query like this
select locations.idlocation, case when sum(case when is_numeric(answer_text1) then answer_text1 else 0 end) + sum(case when is_numeric(answer_text2) then answer_text2 else 0 end) > 0 then 1 else 0 end as RESULT  from locations
inner join answers on answers.idlocation = locations.idlocation
where answers.question_number ='05'
group by locations.idlocation

Which would produce the same result.


text:
Q: How to connect to particular ip & port in android I am new in socket programming.
I want to get connected to particular IP (e.g.: 184.267.345.65) & port (e.g.: 53) in Android so how could it be possible?
Thanks in advance.

A: Socket s = new Socket("184.267.345.65", 53)

See here, here and here for complete example code

A: URLConnection connection = null;
URL url = null;
InputStream is = null;
String mUrl="IP ADDRESS AND PORT NUMBER";

try {
url = new URL(mUrl);

    connection = url.openConnection();
    connection.setRequestProperty("Accept", "SPECIFY ACCEPT TYPE");
is = connection.getInputStream();
String data=convertStreamToString(is);

} catch (Exception e) {
    Log.i("Exception while reading inputstream  From URL :"+mUrl, e.getMessage());
    e.printStackTrace();
}


text:
Q: Attaching checkboxes to an array of images (for delete images) inside form in Ruby On Rails, using Refile gem I'm looking at this documentation, and I'm having trouble coming up with a solution in creating checkboxes to my images, but associated to the form?
If you see below, my images are looped inside the form...
edit view
<%= simple_form_for @project, html: { multipart: true } do |f| %>

  <% @project.project_images.each do |img| %>
    <%= attachment_image_tag(img, :file, :fit, 1000, 430) %>
  <% end %>

  <%= f.attachment_field :trip_images_files, multiple: true %>
  <%= f.button :submit %>
<% end %>

I can add <%= f.check_box :remove_project_images %> inside the .each loop?
  <% @project.project_images.each do |img| %>
    <%= attachment_image_tag(img, :file, :fit, 1000, 430) %>
    <%= f.check_box :remove_project_images_files %>
  <% end %>

Actually, at the time of writing this.. I'm getting undefined method 'remove_project_images_files', now I'm not even sure at all.


text:
Q: How can I perform a regex in Python? I am using Python to create an excel file from a csv file. I am trying to get it to where if the data for the cell begins with a "=" then print it as a function in excel... but i'm not having any luck. I tried to perform a regex on the string to see if it starts with a "=" but it isn't working. Here is what I have so far in Python:
import xlwt
import re

string = '=HYPERLINK("http://www.google.com";"Google")'

if re.match("^=", string) == True:
    formData = re.sub('=', '', string)
    sheet.write(row_count,col-1, Formula("'" + formDta + "'"),style)

Is this not the right approach, or am I just have the wrong syntax? Any suggestions on how I can make this work?

A: You don't really need regex for this. Something like: if string.startswith('='): do something would be fine.
That said, here's an excerpt from the Python documentation for the re module:

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Which is to say that if you're using re.match(), the ^ start-of-line anchor is not necessary.
EDIT: @aix is correct about the behaviour of re.match() - it will only match the pattern to an entire line (not part thereof.)

A: The problem is that you're comparing against True. Python's True is a boolean object. re.match() returns a match object. When Python compares the two, the types don't match, and the if test fails.
The idiomatic way to do a regexp test in python is with:
if re.match(regexp, string):

Python treats most non-False, non-None values as true, for the purposes of if and while tests. The above code uses that behavior - if the regex matches, a match object is returned and the test passes. If the regex does not match, None is returned and the test fails.

A: s = '=HYPERLINK("http://www.google.com";"Google")'

if s.startswith('='):
   ...

The reason your code doesn't work is that re.match() only returns True if the entire input string matches the regex. In your case, only the first character does. You could either use re.search(), or change the regex to "^=.*". However, I think that startswith() is a better approach.
P.S. I've renamed your variable so that it doesn't shadow the standard string module.


text:
Q: AttributeError: 'ballcl' object has no attribute 'ballX' I'm creating a Pong game as a fun project to learn python and pygame. I am currently having an issue, mentioned above.  Please ignore my slop that is code lol. The relevant code:
ballVelX = 5
ballVelY = 5
ballWidth = 15
ballHeight = 15
ballX = 450
ballY = 300

class ballcl:
    def __init(self, ballX, ballY, ballVelX, ballVelY, ballWidth, ballHeight):
        self.ballX = ballX
        self.ballY = ballY
        self.ballVelX = ballVelX
        self.ballVelY = ballVelY
        self.ballWidth = ballWidth
        self.ballHeight = ballHeight

    def ball(self):
        ball = pygame.draw.rect(screen, white, [self.ballX, self.ballY, self.ballWidth, self.ballHeight])

        ball
        #ball movement
        self.ballX += self.ballVelX

ballOb = ballcl()
gameRunning = True

while gameRunning:

    ballOb.ball()

The error i receive is:
Traceback (most recent call last):
  File "d:/Ping/Main.py", line 67, in <module>
    ballOb.ball()
  File "d:/Ping/Main.py", line 49, in ball
    ball = pygame.draw.rect(screen, white, [self.ballX, self.ballY, self.ballWidth, self.ballHeight])
AttributeError: 'ballcl' object has no attribute 'ballX'

A: See Classes. The name of the constructor of a class is __init__ rather than __init:
class ballcl:
    def __init__(self, ballX, ballY, ballVelX, ballVelY, ballWidth, ballHeight):
        # [...]


text:
Q: Trying to use Append To File raises AttributeError exception I am trying to append data stored in a variable to a file. The file was successfully created and the data is stored in the variable; however, I continue to get the AttiributeError:
AttributeError: 'NoneType' object has no attribute 'replace'

here are my results
KEYWORD ${FileA} = OperatingSystem . Create File metrics/Live_RTT.txt, ${MT_Com_RTT_LB_Live_Topics}
00:00:05.233 KEYWORD Selenium2Library . Click Element ${BLANK_CANVAS}
00:00:05.129 KEYWORD Selenium2Library . Click Element //div[@title='${device1}']
00:00:05.063 KEYWORD Selenium2Library . Click Element //div[@title='${device2}']
00:00:00.045 KEYWORD ${MT_Com_RTT_LB_Live_Topics} = Selenium2Library . Get Text xpath=${REAL_TIME_TRENDING_TOPICS}
00:00:00.001 KEYWORD BuiltIn . Log ${MT_Com_RTT_LB_Live_Topics}
Documentation:

Logs the given message with the given level.
Start / End / Elapsed:  20181028 21:37:34.971 / 20181028 21:37:34.972 / 00:00:00.001
21:37:34.971    INFO    Available Topics
Active Energy Delivered + Received
Active Energy Into the Load
Active Energy Out of the Load
Active Power
Active Power A
00:00:00.001 KEYWORD OperatingSystem . Append To File ${FileA}, ${MT_Com_RTT_LB_Live_Topics}
Documentation:

Appends the given content to the specified file.
Start / End / Elapsed:  20181028 21:37:34.972 / 20181028 21:37:34.973 / 00:00:00.001
21:37:34.973    FAIL    AttributeError: 'NoneType' object has no attribute 'replace'

A: Looking at the library's source, the exception most probably is raised in the normalize_path() method, which does this string replacement:
    path = os.path.normpath(os.path.expanduser(path.replace('/', os.sep)))

, where path is the filename - the first argument to the Append To File kw call. The exception says its value is None (e.g. no value set) while it should be some string.
Looking at the log, you're setting this value to the return value of Create File - but that keyword does not return one at all, it simply creates the file you specified in its first argument.
So to resolve - just set the value of ${FileA} yourself, pass it to the two keywords, and do not reassign in the Create File call.


text:
Q: Running dbt vs scheduled queries on bigquery I am trying to see if there are any benefits to running dbt on bigquery as oppose to scheduled queries. Hence, what are the benefits?

A: If DBT runs a simple query, there is no real advantages. But in that case, I won't use Schedule queries, but Cloud Workflows, or Cloud Scheduler that invoque a BigQuery API call (jobs API, with a query job).
However, if you build a complex query, DBT can help you to create and maintain it, even to create temporary working table to get the final table.
But at the end of the day, DBT is simply a SQL query generator and you can schedule the output with the service that you prefer.


text:
Q: Getting eslint(no-unused-vars) in Redux with Typescript I am getting eslint(no-unused-vars) exception while developing React/Redux application with Typescript. Even though the imported variable has been used in the function below.
actions.ts
import { User, FETCH_USERS, FETCH_USERS_SUCCESS } from './types';

export function fetchUsers() {
  return {
    type: FETCH_USERS,
  };
}

export function fetchUsersSuccess(users: User[]) {
  return {
    type: FETCH_USERS_SUCCESS,
    payload: users,
  };
}

types.ts
export const FETCH_USERS = 'FETCH_USERS';
export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';

export interface User {
    id: number;
    email: string;
    firstName: string;
    lastName: string;
    avatar: string
}

export interface Users {
    users: User[];
    isLoading: boolean
}

interface fetchUsers {
    type: typeof FETCH_USERS;
}

interface fetchUsersSuccess {
    type: typeof FETCH_USERS_SUCCESS;
    payload: User[]
}

export type userActionTypes = fetchUsers | fetchUsersSuccess;

reducers.ts
import {
  Users, FETCH_USERS, FETCH_USERS_SUCCESS, userActionTypes,
} from './types';

const initialState: Users = {
  users: [],
  isLoading: true,
};

export default function usersReducer(
  state = initialState,
  action: userActionTypes,
): Users {
  switch (action.type) {
    case FETCH_USERS:
      return {
        ...state,
        isLoading: true,
      };
    case FETCH_USERS_SUCCESS:
      return {
        users: [...state.users, ...action.payload],
        isLoading: false,
      };
    default:
      return state;
  }
}

Getting below exception in actions.ts
'User' is defined but never used.


text:
Q: Unity 2D controller I am having problem with detecting ground (jumping seems to cycle in air) - jump lengths are random and sound seems to cycle. Therefore I guess the ground detection doesn't really work. My code is:
using UnityEngine;
using UnityEngine.EventSystems;

public class PlayerCtrl : MonoBehaviour
{
    bool facingRight = true;
    public AudioSource jumpSoundEffect;
    private bool grounded;

    void Start()
    { }
    void FixedUpdate ()
    {
        grounded = Physics2D.IsTouchingLayers(GetComponent<Collider2D>(), LayerMask.GetMask("Ground"));
    }
    void Update()
    {
        Movement();
    }

    void Movement()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right * 4f * Time.deltaTime);
            if (facingRight == false)
                Flip();
            facingRight = true;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(Vector2.left * 4f * Time.deltaTime);
            if (facingRight == true)
                Flip();
            facingRight = false;
        }
        if (Input.GetKey(KeyCode.Space) && grounded)
        {
            transform.Translate(Vector3.up * 50f * Time.deltaTime);
            jumpSoundEffect.Play ();
        }
    }
    void Flip()
    {
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

A: My guess is that the bool "grounded" is not changing when you press the space key. If you jump, this bool must be false, so it will come back to the ground.


text:
Q: Mod security rule breaking Apache configtest I'm trying to add a mod security rule to implement rate limiting for a certain uri on a web application that is being served by apache.
I'm getting the following error when trying to restart apache:
ModSecurity: No action id present within the rule
Action 'configtest' failed.
The Apache error log may have more information

Specifically - this is what I'm trying to achieve: https://johnleach.co.uk/words/2012/05/15/rate-limiting-with-apache-and-mod-security/
It seems as though that article was written for a previous version of mod_security where the id wasn't required.
I have however altered the rule to include an id (as you can see, I've added id:1234). Therefore I'm not sure why I'm still getting the error.
<LocationMatch "^/login_check">
  SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog
  SecAction "phase:5,deprecatevar:ip.somepathcounter=1/1,pass,nolog"
  SecRule IP:SOMEPATHCOUNTER "@gt 60" "phase:2,id:1234,pause:300,deny,status:509,setenv:RATELIMITED,skip:1,nolog"
  SecAction "phase:2,pass,setvar:ip.somepathcounter=+1,nolog"
  Header always set Retry-After "10" env=RATELIMITED
</LocationMatch>

Not really sure how to debug this. Any input welcomed.

A: SecAction directives also require an id: https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-%28v2.x%29#id

Note : The id action is required for all SecRule/SecAction directives as of v2.7.0

Add a unique id to your SecAction lines too and it should work.