text:
Q: When to use Subject, BehaviorSubject with real example I'm studying Angular, and currently I'm on the topic of Observables. I now understand what are Observables including Subject, BehaviorSubject, ReplaySubject.
But I need a real world example where these can be practically implemented with difference so I can understand when to use which method.
For example, any application in which I can see/compare the implementation of above methods.

A: Here is a practical example and little explanation.  let's say you have an application with many components e.g.: shopping  cart , you have a navigation bar showing items added to the cart. you have products page, grid of items with many add to cart button. product detail page where you have one add to cart button for that product. and finally the order summary page(i.e. the cart page where you have buttons against each product in the list to add + or remove -.
In the above scenario you can use Subjects or BehaviorSubject on the cartService. and all other components subscribing to it via service dependency injection. The add to cart button will invoke the next() function of the service.
In case you want the cart to be pre-populated from the browser local storage (or other mechanism) when the user has left the session by just selecting the items into the cart but did not complete the transaction process. You may use BehaviorSubject to do that initial load to cart.
To extend what @Harun Yilmaz wrote, user logged in status had to be checked from different part of the single page application in that case you can use accordingly, to check if the login status of the user is still valid.
Do not get confused with web streaming and message streaming. message streaming works in conjunction with streams of events. please don't get it wrong. eg: web streaming is where you eg: socket where you make a connection first and then exchange packets of data like streaming.
In angular too it works similar you make a connection by subscribing to the asObservable(). exchange data like streams of message. A BehaviorSubject sends you a welcome message while subject do not send any message until next() is called
You go to a restaurant and the waiter greets you proactively BehaviorSubject waiter greets (how may i help you) you when you call Subject all waiters on the floor are providing service subscribed by the restaurant owner.
hope this helps to understand
UPDATED on 22/06/2020
above mentioned topics are related to reactive programming. which means the application shroud react to a event. events can default browser events like click mouesevent or any custom event that can be emitted. eg. when user do add to cart, place order. It is called reactive because events are uncertain and we do not know when it is going to happen. eg. you subscribe to a youtube channel because you don't know when the creator will post a new video, so you set a kind of event watcher. which will constantly look for that event to occur.
so if i create a sample single page youtube application with no server involved. You will have a creatorcomponent , viewercomponent , publishService.
when the creator publishes a video or releases it, it calls the publishService and wires a message 'new_video_published' who ever are subscribing to this creator will receive the notification and viewerComponent gets to know it.
now if the publishService uses a BehaviorSubject to do the message passing the new subscriber (viewer) will immediately get the latest video released by that creator. If the punlishService uses Subject the new subscriber will not get any immediate message but all messages going forward.
publish.service.ts
... other code ...

    subscribeMes$ = new Subject<string>();
    //OR
    //subscribeMeb$ = new BehaviorSubject<string>('Welcome Message');

newPublish(srting) {
        this._name.next(string);
      }

viewer.component.ts
   //injecting service
subscribedOn_21022020(){
    this.publishService.subscribeMes$.subscribe(n=>{
     this.newVideo =n
    })
}

subscribedOn_23022020(){
    this.publishService.subscribeMes$.subscribe(n=>{
     this.newVideo = n
    })
}

creator.component.ts
this.publishService.newPublish('new video on Rxjs on 22/02/20')

in the above sample we see that when the application first loads on 21-02-2020 in the browser as there no video published(hypothetical event scenario) . the subscribedOn_21022020() will not receive any welcome message when the publish.service.ts uses Subject. In case BehaviorSubject was used they would have received the Welcome message. On 22/02/2020 the creator publishes a video so the subscribedOn_21022020() will receive the new video message ,( in case of BehaviorSubject it would have been be his second message). Now on 23-02-2020 a second user subscribe subscribedOn_23022020() today he will not receive any message immediately but will get new video publish notification anytime in the future as the publish service uses Subject. In case BehaviorSubject was used the second subscriber would have got the 'new video on Rxjs on 22/02/20' message immediately after subscription. and continue to get future videos.

A: You use BehaviorSubject instead of Subject when you want to have an initial (default) value from the stream.
Let's suppose you want to check if the user logged in:

with Subject
isLoggedIn$ = new Subject<boolean>();

.........

isLoggedIn$.subscribe(res => console.log(res))

This subscribe will not fire until isLoggedIn$.next(someValue) is called.

But with BehaviorSubject
isLoggedIn$ = new BehaviorSubject<boolean>(false); // <---- You give 'false' as an initial value

.........

isLoggedIn$.subscribe(res => console.log(res))

This subscribe will fire immediately as it holds false as a value in stream.

So if you want an initial (default) value, you need to use BehaviorSubject.
https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0
What is the difference between Subject and BehaviorSubject?

A: I used behavior subject for sending message between parent and child component and between sibling component.
This is sample for behavior subject, it may help you
https://stackblitz.com/edit/behavior-subject-2019

A: Behavior subject  can be used when you have an initial value. If you are using authService and wanna have initial value as 'null', we use BehaviorSubject.
We cannot use Subject, because subject is hot in nature. That means it is going to emit values even if someone is not listening. That means if we start to subscribe to the subject too late after an event has been emitted, we are not gonna receive that event.
We need to make sure, the instant that components subscribe, they are told whatever the latest value was emitted. That is why we use BehaviorSubject, because it emits the latest value, when a component subscribes.


text:
Q: Reading value from Web.Config that uses configSource files In keeping with the recommendation here we separated our connection string into an xml file. Our web.config:
//old - works
<connectionStrings>
   <add name="DefaultConnection"
        connectionString="Data Source=.\SQLExpress;Initial Catalog=xxx;Integrated Security=True;"
        providerName="System.Data.SqlClient" />
<connectionStrings>
//new - fails
<connectionStrings configSource="connections.config" />

content of connections.config:
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
   <add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;Initial Catalog=xxx;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Both files are located in the project root folder. EntityFramework works fine with both solutions. However when I try to obtain the connection string for some tests it fails to retrieve.This is the code that we use to extract the connection string:
string ConnectionString =
       ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

Reading the connection string direct from web.config works, when we introduce the ConfigSource it fails. What do we need to make it work

A: You need to set the Copy to Output Directory property of your configuration file to either Copy always or Copy if newer.

If you don't do this, your ConnectionStrings.config file will not be copied to the output debug/release folder and so will not be found.

A: Also note that the external file should have the same name as of the section name. Like it should be connectionStrings.config, not connections.config

redpajama_set_name: RedPajamaStackExchange


text:
Q: QlikView licencing and is QlikView server necessary? I have a requirement where I need to inform some clients regarding QlikView licenses.
I also wanted to know if QlikView server is mandatory?
I found this link:
http://www.covaligroup.com/Qlikview-Euro-Pricing/
Any information is welcome.

A: so the first answer is: Contact a local QlikView distribution channel and they will guide you through their licencing processes.
Nevertheless, you have a web page such as:
http://www.qlik.com/legal/license-terms
that shows the exact limitations and capabilities of each of their licences.
Finally, if you want to distribute the models or reports you create using QlikView, the Server is mandatory, since QlikView files cannot be opened in a different computer than the one they were created in, except of course if you are leasing a license from a server, and your QV is no longer flagged as "personal edition"
c ya around

A: Qlik has the Qlikview Desktop Personal Edition for developers or business analyst that uses it for personal information.
When is needed share these information, is necessary use Qlikview server with licensed users.

A: Qlikview server is necessary if you're looking to host your documents on the "Web portal" type interface for clients to access.
I think it also costs about £200.00 per licence, depending on your company size.

A: Qlikview has two version for developer
1) Desktop +ve side is its free but you cannot share
(http://www.qlik.com/us/explore/products/qlikview/free-download-from-here)
2) developer + side you can share with other licence holder however cost will be $1350 per named user. (depends on your agreement with Qlik)
Also note you need to get a reader licence for all user who need to access the file, Sorry cannot help you with cost
Now server is for Hosting and providing a multi user access to your file(QVW). Same can be used to share file across different Platform and device and region . Server most often include Developer licence its addition to Server cost.
Note server doesn't include Publisher or any other tool. Hope that help
More details can
 be found on http://qlik.com

A: Qlik is expensive when it comes to servers and such so make sure to find a distributor like 'Differentia' so you can cut costs on Licenses.
You will need UserCals & DocCals for sharing.


text:
Q: Woocommerce одна функция вместо несколько? сделал добавления товаров через ajax. Дело в том что добавлять продукт и менять количество стало проблемой, когда их много, и решили сделать следующим образом. Просто на js человек будет добавлять , а при клике на кнопку разом все отправится на сервер. Звучит круто, и достаточно быстрее НО!
ajax запрос может отправлять лишь один раз, и второй выполниться когда придется response complete
И за чего ajax функция выглядит следующим образом
var dataActions = [];
    for(var i = 0; i<$allProducts.length; i++){

      var item = $allProducts[i]
      var id = parseFloat($(item).attr('data-id'))
      var quantity = parseFloat($(item).find('.item-quantity').attr('value'))
      var data = {
        action: 'woocommerce_ajax_add_to_cart',
        product_id: id,
        product_sku: '',
        quantity: quantity,
      }
      dataActions.push(data)
    }

    postProducts(dataActions, 0);
    function postProducts(products, index){
      $.ajax({
        type: 'post',
        url: wc_add_to_cart_params.ajax_url,
        data: products[index],
        beforeSend: function (response) {

        },
        complete: function (response) {
          index++;
          if (products.length - 1 >= index) {
            postProducts(products, index);
          }
          else{
            if(window.location.hostname == "site.ru"){
              window.location.href = window.location.href + "?opencheck";
           }
          }

        },

      });
    }

add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');

function woocommerce_ajax_add_to_cart() {

  $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
  $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
  $variation_id = absint($_POST['variation_id']);
  $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
  $product_status = get_post_status($product_id);

  if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {

      do_action('woocommerce_ajax_added_to_cart', $product_id);

      if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
          wc_add_to_cart_message(array($product_id => $quantity), true);
      }

      WC_AJAX :: get_refreshed_fragments();
  } else {

      $data = array(
          'error' => true,
          'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));

      echo wp_send_json($data);
  }

  wp_die();
}

И код работает, действительно работает, но проблема в том что это цикличная функция добавления товаров , если их порядка 8 работает по 8-10 секунд. Скажите можно ли сделать что бы товары добавлялись одним запросом, а не по 8( в зависимости от количество товаров )


text:
Q: why i don't get return value javascript When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN

function createCheckBoxPlatform(data) {
    var platform = "";
    $.each(data, function (i, item) {
        platform += '<input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '' + getOS();
    });
    $('#platform').append((platform));
}

function getOS() {
    $.ajax({
        url: "/QRCNew/GetOS",
        type: "post",
        dataType: "Json",
        success: function (data) {
            var os = '
';
            $.each(data, function (i, item) {
                os += '<input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + ' ';
            });
            os += '
';
            return os;
        }
    });
}

A: I think you have to turn around your logic. The createCheckBoxPlatform loop will have completed before the getOS() ajax call returns, unless it's a synchronous call.
You could split the functions into pieces, gather the getOS data for each data point you have, then construct the checkboxes when your ajax call returns.

A: You can make your ajax call async and have to make no changes to your current logic. But your execution will stop till you don't get the callback to your ajax call.

function getOS() {
    $.ajax({
        url: "/QRCNew/GetOS",
        type: "post",
        dataType: "Json",
        async: true,
        success: function (data) {
            var os = '
';
            $.each(data, function (i, item) {
                os += '<input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + ' ';
            });
            os += '
';
            return os;
        }
    });
}

A: the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value.
Maybe you could first, get the os list and then output what you need, like  this:
function createCheckBoxPlatform(myDatas) {
    $.ajax({
        url: "/QRCNew/GetOS",
        type: "post",
        dataType: "Json",
        success: function (osList) {
            var os = '
';
            $.each(osList, function (i, item) {
                os += '<input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + ' ';
            });
           os += '
';
           $.each(myDdatas, function (i, item) {
               platform += '<input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + ''+os
           });
           $('#platform').append((platform));

        }
    });
}


text:
Q: How to control fps on video without using JMF in Java I'm about to write a program that can take .rgb video file as input, and specify his fps and play it out. But how can I meet this purpose without using JMF package, because I think the meaning of this program is to know how the frame-by-frame works, so I decide it to use BufferedImage as my tool to implement this program, but I still not figure it out how it works on the video (frame-by-frame).
here's the starter code that TA gave us:
I try lots of things, but the delay between two frames is very obvious, I don't know why. is there any efficiency way to play the video frame-by-frame without using any JMF package.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;

public class imageReader {

    public static void main(String[] args) {
        String fileName = args[0];
        int width = Integer.parseInt(args[1]);
        int height = Integer.parseInt(args[2]);

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        try {
            File file = new File(fileName+".rgb");
            InputStream is = new FileInputStream(file);
            //BufferedInputStream bis = new BufferedInputStream(is);

            long len = file.length();  //bytes in one frame (consist of R,G,B frame)
            byte[] bytes = new byte[10000000];

            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }
            System.out.println("\noffset = "+ offset);   //7603200
            System.out.println("numRead = "+ numRead);   //7603200
            System.out.println("file length: " + len);   //7603200
            System.out.println("frame #: "+ (offset/(width*height*3))); //100

            JFrame frame = new JFrame();
            frame.setVisible(true);

            int ind = 0;
            int f = 1;

            while(ind < offset){
                for(int y = 0; y < height; y++){

                    for(int x = 0; x < width; x++){

                        byte a = 0;
                        byte r = bytes[ind];
                        byte g = bytes[ind+height*width];
                        byte b = bytes[ind+height*width*2];

                        int pix = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
                        //int pix = ((a << 24) + (r << 16) + (g << 8) + b);
                        img.setRGB(x,y,pix);
                        ind++;
                    }
                }
                JLabel label = new JLabel(new ImageIcon(img));
                frame.getContentPane().add(label, BorderLayout.CENTER);
                frame.pack();
                System.out.println("frame #: "+ ind);
            }

            System.out.print("end");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Use a label to display the image
        /*JFrame frame = new JFrame();
         *JLabel label = new JLabel(new ImageIcon(img));
         *frame.getContentPane().add(label, BorderLayout.CENTER);
         *frame.pack();
         *frame.setVisible(true);
         **/

    }

}

What is going wrong with this code??


text:
Q: repeat a multi job in jenkins I used jenkins' Multijob plugin and run a test that contain 4 tests in it. Now I want to repeat this test for many times (for example 10 times), but some files are different in them.
Is that any way to config multi jobs to ran some jobs with other config files?
Thanks


text:
Q: LOAD CSV WITH HEADERS in Neo4j with muliti-word headers I am trying to load a csv file with multi word headers but I don't know how to access the field with multi-word header
"Timestamp","Username","Name","Gender","School Education"
"2017/02/14 4:12:48 PM GMT+5:30","gtg13@gmail.com","ran","Male","Yes"
"2017/02/14 4:13:10 PM GMT+5:30","sw.110@gmail.com","she","Female","No"
"2017/02/14 4:13:42 PM GMT+5:30","spj07@gmail.com","moaj","Male","No"

Here the multi-word header is "School Education"

A: You need to use backtick like this
load csv with headers from "file:///Assessment2.csv" as line
return line.`School Education`


text:
Q: How to make quadtree algorithm i'm making an algorithm called Quadtree, so i've tried this code that i made but the output is incorrect
input
8 8
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
0 0 0 1 1 1 1 1
0 0 1 1 1 1 1 1
0 0 1 1 1 1 0 0
0 0 1 1 1 0 0 0
output
0
the code i've tried
#include <iostream>
#include <string>

using namespace std;

int m[128][128];
int nJawaban;
string jawaban[128*128];

bool homogen(int r, int c, int k) {
   int val = m[r][c];
   for (int i = r; i < r+k; i++) {
      for (int j = c; j < c+k; j++) {
         if (m[i][j] != val) {
            return false;
         }
      }
   }
   return true;
}
// i think it's here
void quadtree(int r, int c, int k, string s){
   if (m[r][c] == m[r-1][c-1]) {
      if (m[r][c] == 1) {
         jawaban[nJawaban] = "1" + s;
         nJawaban++;
      }
   } else {
      quadtree(r, c, k/2, s+"0");
      quadtree(r, c+(k/2), k/2, s+"1");
      quadtree(r, c, r+k-1, s+"0");
      quadtree(r, c, r+k-1, s+"1");
   }
}

int main(){
   int r, c;
   scanf("%d %d", &r, &c);

   int maxRc = max(r, c);
   int pow2 = 1;
   while (pow2 < maxRc){
      pow2 *= 2;
   }

   for (int i = 0; i < pow2; i++) {
      for (int j = 0; j < pow2; j++) {
         m[i][j] = 0;
      }
   }

   for (int i = 0; i < r; i++){
      for (int j = 0; j < c; j++){
         scanf("%d", &m[i][j]);
      }
   }

   nJawaban = 0;
   quadtree(0, 0, pow2, "");

   printf("%d\n", nJawaban);
   for (int i = 0; i < nJawaban; i++) {
      printf("%s\n", jawaban[i].c_str());
   }

   return 0;
}

input:
8 8
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
0 0 0 1 1 1 1 1
0 0 1 1 1 1 1 1
0 0 1 1 1 1 0 0
0 0 1 1 1 0 0 0
expected output:
11
112
113
1211
1212
1213
123
130
131
1320
1321
1322
note: some of the var name is written in indonesian language and i'm trying to make this code without (using namespace std) and also fix the code
i've watched youtube video and reading some stackoverflow answer
https://www.youtube.com/watch?v=xFcQaig5Z2A
Efficient (and well explained) implementation of a Quadtree for 2D collision detection
nevertheless i can't correct my mistake but i can point out where the mistake is. My question here is how to correct this mistake or even provide better algorithm
edit: it's still didn't work


text:
Q: Converting terminal printed output to CSV - rows to column I have terminal output as shown below in the screenshot.
How should I dump data into CSV file and that too in separate column for each row?
I am using Ubuntu.


text:
Q: How to calculate tf-idf when working on .txt files in python 3.7? I have books in pdf and I want to do NLP tasks such as preprocessing, tf-idf calculation, word2vec, etc on those books. So I converted them into .txt files and was trying to get tf-idf scores. Previously I performed tf-idf on a CSV file, so I made some changes in that code and tried to use it for .txt file. But I am unsuccessful in my attempt.
Below is my code:
import pandas as pd
import numpy as np
from itertools import islice
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
data = open('jungle book.txt', 'r+')
# print(data.read())
cvec = CountVectorizer(stop_words='english', min_df=1, max_df=.5, ngram_range=(1,2))
cvec.fit(data)
list(islice(cvec.vocabulary_.items(), 20))
len(cvec.vocabulary_)
cvec_count = cvec.transform(data)
print('Sparse Matrix Shape : ', cvec_count.shape)
print('Non Zero Count : ', cvec_count.nnz)
print('sparsity: %.2f%%' % (100 * cvec_count.nnz / (cvec_count.shape[0] * cvec_count.shape[1])))

occ = np.asarray(cvec_count.sum(axis=0)).ravel().tolist()
count_df = pd.DataFrame({'term': cvec.get_feature_names(), 'occurrences' : occ})
term_freq = count_df.sort_values(by='occurrences', ascending=False).head(20)
print(term_freq)
transformer = TfidfTransformer()
transformed_weights = transformer.fit_transform(cvec_count)
weights = np.asarray(transformed_weights.mean(axis=0)).ravel().tolist()
weight_df = pd.DataFrame({'term' : cvec.get_feature_names(), 'weight' : weights})
tf_idf = weight_df.sort_values(by='weight', ascending=False).head(20)
print(tf_idf)

This code is working until print ('Non Zero Count :', cvec_count.shape) and printing:

Sparse Matrix Shape :  (0, 7132)
Non Zero Count :  0

Then it is giving error:

ZeroDivisionError: division by zero

Even if I run this code with ignoring ZeroDivisionError, still it is wrong as it is not counting any frequencies.
I have no idea how to work around .txt file. What is the proper way to work on .txt file for NLP tasks?
Thanks in advance!

A: You are getting the error because data variable is empty or wrong type. Just opening the text file is not enough. You have to read the contents into a string variable and then do the preprocessing on that variable. Try replacing
data = open('jungle book.txt', 'r+')
# print(data.read())

with
with open('jungle book.txt', 'r') as file:
     data = file.read()


text:
Q: OpenStack Rackspace Cloud Files .net SDK I am trying to save an XML file to a non CDN Container from Sydney:
public void Save(XDocument document)
{
    using (MemoryStream ms = new MemoryStream())
    {
        document.Save(ms);
        ms.Position = 0;

        RackspaceCloudIdentity identity = new RackspaceCloudIdentity { Username = "username", APIKey = "xxxxxxxxxxx", CloudInstance = CloudInstance.Default };
        CloudFilesProvider provider = new CloudFilesProvider(identity);

        provider.CreateObject("XMLFiles", ms, "xmlFile1.xml", region: "syd");
    }
}

For a 1MB file, it takes about 50 seconds to upload (very long).
And, trying to download the file back, returns an empty result:
public void Read()
{
    RackspaceCloudIdentity identity = new RackspaceCloudIdentity { Username = "username", APIKey = "xxxxxxxxxxx", CloudInstance = CloudInstance.Default };
    CloudFilesProvider provider = new CloudFilesProvider(identity);

    using (MemoryStream ms = new MemoryStream())
    {
        provider.GetObject("XMLFiles", "xmlFile1.xml", ms, region: "syd");

        // ms.Length is 0
    }
}

I am doing something wrong?

A: Ugh. I introduced this bug in commit 799f37c (first released in v1.1.3.0). I'm looking into the best workaround right now.
Edit: There is no workaround, but I filed issue #116 for the issue, and after the pull request for it is merged, we'll release version 1.1.3.1 of the library to correct the problem.

A: Are you able to access your control panel at mycloud.rackspace.com?
I used my control panel to upload an XML file, then used your code, above, to download the XML file. It worked fine.
I'm going now use the upload code you posted.
Just wanted you to know I'm looking into this.


text:
Q: Why am I getting the wrong GPS distance calculation in my Android app? While commuting to work, I am tracking my coordinates every 1 second. When I get the distance between the two points, and display it in a TextView, I am getting a much higher number than I should be. For example, a 9.5 mile route ends up displaying as somewhere in the ballpark of 14,000 miles. Below is a copy of my code:
GPS Update handler/function:
public void onGPSUpdate(Location location)
{
    //Get Milestone prefs
    SharedPreferences settings = getSharedPreferences("AppPrefs", 0);
    Integer milestone = settings.getInt("milestone", 5);

    //Get current Speed and Distance
    speed = location.getSpeed();

    Float newDistance;
    if(oldLocation == null){
        oldLocation = new Location("Point B");
        oldLocation = location;

        newDistance = 0f;
    } else {
        newDistance = getDistanceInMiles(location, oldLocation);
    }

    // Make sure the user is actually moving and that we have an old location
    // Add new distance to total
       if(roundDecimal(convertSpeed(speed),2) > 0 && oldLocation != null){
            distance = distance + newDistance;
       }

    // Format the distance to 1 decimal
    String formattedDistance = String.format("%.1f", distance);

    setText(R.id.miles_message, formattedDistance + " ");

}

Calculate Miles function:
public float getDistanceInMiles(Location p1, Location p2){
    float[] distance1 = new float[1];

    Double latFn = p1.getLatitude();
    Double lonFn = p1.getLatitude();
    Double newLat = p2.getLatitude();
    Double newLon = p2.getLatitude();

    Location.distanceBetween(latFn,lonFn,newLat,newLon, distance1); //in meters
    float distanceInMeters = distance1[0];
    float distanceInMiles = distanceInMeters * 0.00062137f;
    return distanceInMiles; //in miles
}

Any advice?

A: You have a bug in your code.  You're using the latitude for the longitude and latitude of each point.  Also, there's a built in location function for distance.  Try:
public float getDistanceInMiles(Location p1, Location p2){
    float distanceInMeters = p1.distanceTo(p2);
    float distanceInMiles = distanceInMeters * 0.00062137f;
    return distanceInMiles; //in miles
}

A: Gabe did a great job of spotting a bug in my code. I as using getLatitude() for each of my coordinates instead of getLongitude() and getLatitude(). I also switched his getDistanceInMiles function:
public float getDistanceInMiles(Location p1, Location p2){
    float distanceInMeters = p1.distanceTo(p2);
    float distanceInMiles = distanceInMeters * 0.00062137f;
    return distanceInMiles; //in miles
}

The second bug I found is in my first condition statement where I set the oldLocation. oldLocation is only getting set on first run causing the getdistanceInMiles() function to calculate the distance from your start coordinates to your current coordinates each time instead of the distance between your last coordinates and current coordinates.
Below are the corrected code snippets all together:
public void onGPSUpdate(Location location)
{
    //Get Milestone prefs
    SharedPreferences settings = getSharedPreferences("AppPrefs", 0);
    Integer milestone = settings.getInt("milestone", 5);

    //Get current Speed and Distance
    speed = location.getSpeed();

    Float newDistance;
    if(oldLocation == null){
        oldLocation = new Location("Point B");
        oldLocation = location;

        newDistance = 0f;
    } else {
        newDistance = getDistanceInMiles(location, oldLocation);
        oldLocation = location; //Second correction, make sure to set last coordinates to current coordinates
    }

    // Make sure the user is actually moving and that we have an old location
    // Add new distance to total
       if(roundDecimal(convertSpeed(speed),2) > 0 && oldLocation != null){
            distance = distance + newDistance;
       }

        // Format the distance to 1 decimal
        String formattedDistance = String.format("%.1f", distance);

        setText(R.id.miles_message, formattedDistance + " ");

}

//First, simplified distance function to Gabe's suggestion
public float getDistanceInMiles(Location p1, Location p2){
    float distanceInMeters = p1.distanceTo(p2);
    float distanceInMiles = distanceInMeters * 0.00062137f;
    return distanceInMiles; //in miles
}


text:
Q: Data structure for One column list for storing addresses , better lookup O(1) in C++ I am a beginner in C++. I need to store list of addresses that give a very good performance in terms of lookup and adding new entries.
I first want to see if the address tis already present in the list, if yes , then don't write, else add new entry to that list.
And at the time of certain operation, look if the address is present in the list or not.
Is there any fast access and dynamic growing data structure in terms of memory and space in C++.

A: I would suggest using std::map (usually implemented as some red-black tree) which has a logarithmic complexity so should be enough in practice.
If you had a C++11 standard conforming implementation, you could consider std::unordered_map (usually implemented as some hash-table).
If you don't need any associated data to keys, but just to handle sets of them, considuer std::set or std::unordered_set
And many libraries (Boost, Qt, ...) also implement associative containers.

A: You are looking for boost::unordered_map.


text:
Q: MySQL remove duplicate records, based on custom condition I have a table "fb_products" table with the following columns:
CREATE TABLE IF NOT EXISTS `fb_products` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL DEFAULT '0.00',
  `in_promo` tinyint(1) NOT NULL DEFAULT '0',
  `original_product_id` int(11) DEFAULT '0',
  .........................................
) ENGINE=InnoDB AUTO_INCREMENT=6254 DEFAULT CHARSET=utf8;

I have a search filter in my site using a SELECT, based on several conditions.
If two products have the same "original_product_id" and one of them has "in_promo" = 1 and the other - "in_promo" = 3, I need to select only the record with "in_promo" = 3. Could this be achieved using MySQL query? Here's a sample SQL, generated by the search filter in my site:
SELECT
p.id,
.............
(
    SELECT SUM(quantity) FROM `gensoft_availability` WHERE code = p.code
) AS avail,
(SELECT id FROM `fb_products_products_cats_links` WHERE prod_id =p.id AND cat_id='17' AND p.visible=1 LIMIT 1) as rent_product
FROM
fb_products AS p
INNER JOIN fb_products_products_cats_links AS c ON c.prod_id = p.id AND c.cat_id IN (19,21,26,23,22,24,20,18)
LEFT JOIN fb_products_images_bg AS i ON i.item_id = p.id AND i.default_item = '1'
WHERE p.language = 'bg' AND p.archive = 0 ...

A: I would use NOT EXISTS:
SELECT * FROM fb_products
WHERE
  in_promo=3
  OR
  NOT EXISTS (
    SELECT * FROM fb_products f
    WHERE
      f.original_product_id=fb_products.original_product_id
      AND f.in_promo=3
  )

You can then add multiple conditions, or use this query as a subquery and join
the result with other tables.
Please see a fiddle here.

A: Add order by promo_id DESC limit 1 to your query

A: You could use SELECT MAX(in_promo),original_product_id FROM fb_products GROUP BY original_product_id .


text:
Q: ¿De que manera puedo generar una sincronización de base de datos? Tengo la siguiente duda.
Supongamos que una empresa que emite boletos para excursiones en barco tiene dos puntos de venta en distintos lugares. Actualmente estos dos puntos de venta no tienen ningun tipo de conexiín entre sí, por ende la unica manera de saber si se vendieron todos los boletos es literalmente llamando a quien este en el otro punto para preguntarle cuantos lugares le quedan.
Desarrollé un sistema para generar dichos boletos/pasajes en Delphi XE7. Ahora me falta una manera de sincronizar los puntos de venta.
Mi objetivo es que si yo emito un boleto en el punto de venta "A" y es el boleto "Nº: 0003" cuando el punto de venta "B" emita un boleto este sea el "Nº: 0004".
Y de la misma manera lograr que cuando se llene el barco y no haya mas boletos disponibles los dos sistemas no puedan vender mas boletos en ese viaje.
Basicamente, solucionar esta situacion de tener que llamar al otro punto y preguntarle cuantos boletos quedan.
Investigué un poco sobre la replicación de bases de datos en MySQL (Master-slave) pero por lo visto es unidereccional, por ende uno de los dos puntos de venta no podria modificar la base de datos.
¿Alguna sugerencia de como puedo solucionar este problema?

A: La solución "correcta" (ideal) y las más sencilla (la que menos problemas te va a dar) es que esos 2 puntos de venta trabajen contra la misma Base de Datos.
Lo que tienes que ver, es qué soluciones tienes para conseguir eso. Una VPN parece algo sencillo y que no te debería conllevar cambios en el programa.
Si por temas técnicos esta solución no es posible, hay que evaluar alternativas, pero creo que entonces estás condicionando la solución del problema, no sólo al problema en sí, sino a otros factores externos.
(OBLIGATORIO)
Está claro que necesitas conexión a internet para poder solventar este problema, porque tiene que haber un lugar común donde ambos puntos de venta puedan leer y escribir la información.
Si me dices que la conexión falla, es imposible que puedas comunicar ambos puntos con fiabilidad.
OTRAS OPCIONES (parches):
(0) Utilizar algo como "RAD Server", pero hablando de que estamos desarollando un parche, creo que no vale la pena ni evaluarlo.
(1) Crear un WebService sencillo en un Servidor de Internet, que te vaya dando los boletos y el estado del barco (barco Lleno/Vacío).
En ese caso los clientes se comunican con el WS cada ver que hacen una venta (antes y después), proceso sencillo.
Revisa esta serie de entradas, que explica cómo hacer esto de forma sencilla. Tanto el servidor como los clientes.
(2) Opción que usábamos antes cuando no había WS. Utilizar un FTP/FTPs de los de toda la vida para compartir información, realizando pooling cada x tiempo. Tanto para leer como para escribir. Sincronización manual.
Menos recomendable que la anterior, pero posiblemente más sencilla técnicamente.
(3) Utilizar otros espacios (en internet) para realizar la misma sincronización del punto anterior. Mismo problemas y carencias del anterior. Léase, DropBox, GDrive, OneDrive,...
Puede haber más pero contando que cuanto más abajo en menos recomendable y que ya nos basamos en que son un parche, ya no sigo ni proponiendo...


text:
Q: Determining whether ODE solutions are square-integrable by approximation I saw it claimed that whether or not the solutions to an ODE are $L^2$ could be determined by solving an easier ODE with asymptotically similar coefficients and I'm stuck on determining how. The specific example was that if we want to know about square-integrability near $0$ of solutions to
$$-u'' + 2x^{-2} (1+x)^{-2}u = 0$$
(on say $x \in (0, \infty)$), then we can instead solve
$$-u'' + 2x^{-2}u=0$$
I've solved this easier equation, but I'm stuck trying to prove how that tells us about the solutions to the original.

A: Your equation has the form
$$
u''+p(x)u'+q(x)u=0,
$$
where $p=0$ and $q$ is singular at $x=0$. However,
$$
x^2q(x)=-\frac{2}{(x+1)^2}
$$
is analytic at $x=0$ with
$$
\lim_{x\to 0} x^2q(x)=-2.
$$
Thus, $x=0$ is a regular singular point. By the theorem on the Frobenius method, there is a series expansion about $x=0$ of the form
$$
u=x^r\sum_{n=0}^{\infty}a_nx^n.
$$
To find $r$, we compute the indicial equation
$$
r(r-1)+0r-2=0\to r^2-r-2=0\to r=-1,2.
$$
Thus, one solution, the one corresponding to $r=2$, is square integrable at $x=0$ since, for that solution,
$$
u=\mathcal{O}(x^2)\text{ as }x\to 0.
$$
Note that the solution corresponding to $r=-1$ is not square integrable since it behaves as $1/x$ as $x\to 0$.
Your simplified equation is an Euler equation with the same indicial equation, which is all that matters when determining the behavior of the solution near $x=0$. So, that simplified equation has the solutions $u=x^2$, square integrable, and $u=1/x$, not square integrable.


text:
Q: Exibir somente semana com eventos Fullcalendar O Fullcalendar tem o botão de Prev e Next que avançam e voltam as semanas, se ficar avançando ele vai mostrando as semanas infinitamente, se voltar também.
Eu preciso de uma função que permita exibir somente as semanas que contém eventos marcados.
Por exemplo: Caso eu tenha um evento em 15/02/2014 e outro evento no dia 20/08/2015, os botões prev e next só poderão alternarem nestas duas semanas.
Alguém sabe de alguma função que permita fazer isto no fullcalendar?
Tentei procurar alguma função no docs do site do fullcalendar, más não encontrei nada disto, segue link: http://fullcalendar.io/docs/

A: Segue código:
segue js que pega data inicial e data final cadastrada e limita as setas de prv e next do fullcalendar:
viewRender: function(view,element) {
      var now = moment('<?php print $eventos_agenda[0]->data_clicada ?>');
        var end = moment('<?php print $eventos_agenda[$final]->data_clicada ?>');
                    if ( end < view.end) {
                       $("#botao_passa").addClass('disabled');
                    }
                    else {
                       $("#botao_passa").removeClass('disabled');
                    }
                    if ( view.start < now) {
                       $("#botao_volta").addClass('disabled');
                    }
                    else {
                       $("#botao_volta").removeClass('disabled');
                    }
                },


text:
Q: Converting mapdifference to jsonnode I am comparing two json document and is using mapdifference to get the difference of the two.
Now i want to patch this difference to an existing json, but the difference returned is in the form
/applicant/0/EmployDetail/0/AnnualSalary: 99999868.99
/Notes/0/customNote: OM Application Notes

and so on.
Used the following to generate the difference:
MapDifference<String, Object> difference = Maps.difference(leftFlatMap, rightFlatMap);
difference.entriesOnlyOnRight().forEach((key, value) -> System.out.println(key + ": " + value));

I am expecting it to convert it to a jsonnode.

A: JsonNode jsonDifference = new ObjectMapper().valueToTree(difference.entriesOnlyOnRight());


text:
Q: When are growth series rational? For a finitely generated group $G$ with generating set $S$, one can define the word metric. Using this, we are able to define the sequence $\sigma(n)$ by
 $ \sigma(n) = |\mathcal{S}(e,n)| $, which is the number of elements that are contained in the sphere at a distance $n$ of the identity element (ie. All elements in $G$ that are at a distance precisely $n$ of the identity). Consequently  one can define the growth series $\mathcal{S}(n) = \sum_{n\ge 0} \sigma(n) z^n$. One can then ask if this formal power series is rational (ie. it is the power series associated to a rational function).
I have two questions concerning this:

*

*Why is it interesting to ask this question? (ie. Why is the fact that the formal power series is rational interesting?)

*If one would take two different generating sets $S$ and $S'$, is it possible that the the growth series coming from $S$ is rational and the one coming from $S'$ is not?
Thank you for your help.

A: I don't know how interesting this is to you, but knowing that $S(z)$ is a rational function is a quick way to show that the exponential growth rate $\lim_{n \rightarrow \infty} \sigma(n)^{1/n}$ of the group with respect to $S$  is an integer algebraic number.  So, for example, the only exponential growth rate you can get out of a hyperbolic group is an algebraic number.
I'll note that there do exist exponential growth rates that are not algebraic numbers--in fact, there are uncountably many possible exponential growth rates, as shown by Anna Erschler in
A. Erschler. Growth rates of small cancellation groups. In Random walks and geometry, pages 421–430. Walter de Gruyter GmbH & Co. KG, Berlin, 2004.

A: An answer to your second question: Stoll constructed many 2-step nilpotent groups such that there exist generating sets $S$ and $S'$ such that the growth series with respect to $S$ is rational and with respect to $S'$ is transcendental.  See
M. Stoll, Rational and transcendental growth series for the higher Heisenberg groups, Invent. Math. 126 (1) (1996), 85–109.
As for your first question, I don't know if it is intrinsically interesting, and I am not aware of any applications of these results.  However, what is interesting are the vast array of tools and techniques that are used to study it.  It is a good proving ground for many ideas in geometric group theory (especially those related to things like regular languages).  There is an enormous literature on this topic.  The introduction to my paper
A. Putman,
The rationality of sol manifolds
J. Algebra 304 (1) (2006) 190-215.
summarizes most of the papers concerning it that I am aware of.  It can be downloaded from my webpage here.  The only ones I know about that came out after it are

*

*My student Corey Bregman's paper "Rational Growth and Almost Convexity of Higher-Dimensional Torus Bundles", available here.

*Duchin-Shapiro's paper "Rational growth in the Heisenberg group", available here.


text:
Q: Design being messed-up after deploying on Azure My application looks fine when I run on the localhost via visual studio but it creates mess when I publish it on the AZURE Web App Service. I am using free tier of Azure web app service.
Image of the header of homepage at the local host
Image of the header of homepage at the Azure web app-service
Home page items at the localhost
Home page items at azure web-app-service
Button at the homepage at localhost
Button at azure web-app-service
My link to the site is https://auctionit.azurewebsites.net/

A: Nothing to do with the Azure free tier.
From what you have shown here, this is something to do with the styles. Check your css and inline styles. Make sure all the css and other style related resources are deployed correctly.

A: If you check the console tab, you'll see that some files were not properly loaded. I believe this is why the layout is broken, no problems on Azure side.


text:
Q: How to set condition for onclick validation javascript I am facing one small problem to set the message and clear the message.
I have 2 input where onclick of the button I should check the input fields satisfies the condition else don't show any message
OR
if error message was displaying after condition gets satisfied I should remove the message
but the code below doesn't satisfies if phnum is 10 digit and pincode is less than 7 digit and vise versa
if both field length doesn't satisfy on click of button i should display both the error messages
const inputValidation = () => {
  if (phnum?.length < 10) {
    //phnum must be 10 digit(error message)
    if (picode?.length < 7) {
      //zipcode must be 7 digit (error message)
    } else {
      //remove  zipcode message
    } else {
      //remove phnum message
    }
  }
}

A: *

*Move the clear errors before the ifs

*Move the second if since now you only test picode if phnum is in error

const inputValidation = () => {
  //remove  zipcode message
  //remove phnum message
  if (phnum?.length < 10) {
    //phnum must be 10 digit(error message)
  }
  if (picode?.length < 7) { // removing the else will show both
    //zipcode must be 7 digit (error message)
  }
}


text:
Q: How to change css class generated by javascript i'm using visjs library, it works good, but i cant change css class generated by this libary(vis js) because the divs are generated by the javascript of the library.
how i can change the class of these divs please!!
i tried to use this but it didnt worked:
$( document ).ready(function() {
   $(".vis-item").css("background-color", "red");
 });
 $( document ).ready(function() {
   $(".vis-item").css("background-color", "red");
 });

A: To add css class to some element:
 $('yourSelector').addClass('className');

To remove css class from some element:
 $('yourSelector').removeClass('className');

To change inline css that is style attribute of your html tag:
 $('yourSelector').css('display', 'block');
 $('yourSelector').css('background-color', 'blue');

And so on..This way you can add css properties in style attribute of your html tag. You can remove by passing empty string from style attribute like:
 $('yourSelector').css('width', '');    //This will removwe width property

A: Use addClass to over right existing class rather then inline css .
$( document ).ready(function() {
   $(".vis-item").addClass('red');
 });

CSS:
.red{
    background-color: red;
}


text:
Q: Extract tar.gz to STDOUT and zip STDOUT I need to extract an tar.gz archive I downloaded with curl into STDOUT and use the STDOUT as STDIN for zipping the files again.
curl -L someURL | tar xz --strip-components=1 -O| zip -r test.zip

gives me enter cocurl: (23) Failed writing bodyde here.
The problem is produced by the -O flag of tar.

A: Your're missing a minus sign before the -O and missed the minus argument for zip:
curl -L someURL | tar xzf - -O | zip test.zip - works on my system with

*

*curl 7.26.0

*tar (GNU tar) 1.26

*Zip 3.0


text:
Q: c++ simple operator overloading for both directions So I am trying to overload the operator* so both ways will work:
Myclass * a;
a * Myclass;

When I declare this function everything goes well:
Polynomial operator*(const double d);

But when I try doing it the other direction like this:
Polynomial operator*(Polynomial &, const double d)

I'm getting an error: "too many parameters for this operator function.
What am I doing wrong?
Thanks!

A: When you overload a binary operator as a member function, the class instance is always the left-hand operator and the argument to the function is the right hand, there's nothing you can do to change it. Not if you want to continue using member only functions.
But if you use a global non-member function you can easily have whichever order you want. For example
class Polynomial { ... };

// Function that allows poly * 12.34
Polynomial operator*(const Polynomial& lhs, const double rhs)
{
    ...
}

// Function which allows 12.34 * poly
Polynomial operator*(const double lhs, const Polynomial& rhs)
{
    ...
}

And if you don't want to reimplement the same code in both functions, and the operator is commutative (like multiplication and addition should be) then you can implement one of the function by calling the other:
Polynomial operator*(const Polynomial& lhs, const double rhs)
{
    ...
}

Polynomial operator*(const double lhs, const Polynomial& rhs)
{
    return rhs * lhs;  // Calls the operator function above
}

Of course, the operator taking the Polynomial object as left-hand side may of course be implemented as a member function.

On a related note, if you have implemented the operator as a member function, e.g.
class Polynomial
{
    ...

    Polynomial operator*(const double rhs)
    {
        ...
    }
};

The the following code
Polynomial poly1(...);
Polynomial poly2 = poly * 12.34;

is equal to
Polynomial poly1(...);
Polynomial poly2 = poly.operator*(12.34);


text:
Q: Problem using string resources in AndroidManifest.xml I'm a newbie using Android Studio, which I use for a Flutter mobile App project.
In the AndroidManifest.xml file I am trying to set up the required instruction for a Facebook login SDK package.
I do so by first adding a Value resource file and afterwards I add some string resources:
<string name="facebook_app_id">6548230980294823</string>

When the string resource is referenced in the manifest file it look like this:
<meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>

Unfortunately, it does not work. Android Studio keeps on claiming that it cannot resolve the string resource:

I have read countless posts already concerning this problems, but I was not able to find a solution.
Steps to reproduce:

*

*Start AndroidStudio (I am using version 3.5.2)

*Create a new Flutter project

*Add a new value resource file (name it strings.xml for instance)

*Add some string resources in the value resource file

*Use a string resource in the manifest file (AndroidManifest.xml).
For instance as listed above or elsewhere and otherwise in the
manifest file.
Results are always the same: "Cannot resolve the symbol ..."
Finally, I have noticed that if I download an example project from a flutter package, which contains references to string resources in the manifest file, this seems to work all-right (the example I am referring to is available here: https://github.com/roughike/flutter_facebook_login).
I have almost spent days on this problem.
Thanks in advance - from a newbie using Android Studio.


text:
Q: Jquery Masterpage Can not Change the text for a textbox from client side Ok this one is one of those that has had me bangin my head against the wall for acouple of hours. It seems very simple, I am using a Masterpage, Telerik controls and telerik RadScriptblock and Jquery. I am trying to change the text of an asp.net textbox in the grid edit form from client side code but it JUST WILL not WORK! I have tried the following with no luck.
 Text box:

 <asp:TextBox  ID="txtNewProduct" runat="server"/>

 // JQuery inside RadScriptBlock
 //Have tried all these but dont work

// $('#txtNewProduct').text('New Product');
//  $('#txtNewProduct').attr('text', 'New Product');
//  $('#txtNewProduct').val('New Product');

//This one gets me the object but it CANT seem to set the text have been trying
//for hours

//var txtnew = $('[id$=txtProduct]');
//txtnew.text = "New Product";  //This shows the value "New Product" in clienst side
//but does not change the textbox's text

If someone can point out how to do this simple task you might save me and some other poor soul some therapy :) thank you in advance.

A: The id is most likely changed if you are using a master page, check the source code that is generated.

A: As Paul Creasey said, check the generated source and then ensure your jQuery library file(s) successfully loaded...if loaded, then use something like Firebug (in Firefox) to test the jQuery. $('#txtNewProduct').val('New Product') should work.

A: Wow that was frustrating I hope it helps someone else out as well I was able to change the textbox's text using
$('[id$=txtNewProduct]').val('New Product');


text:
Q: Change radio button value in PrimeUi I'm trying to set a PuiRadioButton to checked but I've encountered a problem. The underlying pure HTML input elements gets selected, but PrimeUI does not show the change.
I've the two elements:
<input type="radio" name="peopleSelection" id="peopleRadioButton" value="people" checked="checked" />

and
<input type="radio" name="peopleSelection" id="groupRadioButton" value="group" />

and I've tried following statement
$('#groupRadioButton').attr('checked', 'checked');

It works perfetly fine in a JSFiddle. But when I inspect the HTML, the correct input element is checked successfully, but not shown by PrimeUI.
I also tried variations of these:
$('#groupRadioButton').prop('checked', true);
$('#groupRadioButton').attr('checked', 'checked');
$('#groupRadioButton')[0].checked = true;

Unfortunately I could not find a set or get method on the PrimeUi Documentation page.
How do select/unselect PrimeUI radio buttons?
Thanks in advance


text:
Q: Unpack error while using sklearn columntransfromer I was trying to one hot encode a dataframe for some testing.
I tried using the regular OneHotEncoder from sklearn but It seemed to have some issues with NaN values (NaN values that were not present on columns I wanted to encode)
From what I searched, a solution was to use a column transformer, which could apply the encoding only to certain columns, something like the following
ct = ColumnTransformer([(OneHotEncoder(categories = categories_list),['col1','col2','col3'])])

In which categories_list is a list of all present categories.
The problem is that when I try to apply this transformer to my dataframe, I always get not enough values to unpack error.
Im transforming like this
ct.fit_transform(df_train_xgboost)
Any idea on what should I do?
EDIT:
Some example Data
id | col1 | col2 | col3 | price | has_something
1    blue   car    new    23781       NaN
2    green  truck  used   24512       1
3    red    van    new    44521       0

Some more code
categories_list = ['blue','green','red','car','truck','van','new','used']
df_train_xgboost = df_train
df_train_xgboost = df_train_xgboost.drop(columns_I_dont_want, axis=1)
df_train_xgboost = df_train_xgboost.fillna(value = {'col1': 0, 'col2': 0, 'col3': 0})

ct = ColumnTransformer([(OneHotEncoder(categories = categories_list),['col1','col2','col3'])])

print(df_train_xgboost.shape)
ct.fit_transform(df_train_xgboost)

A: First of all, the use of ColumnTransformer is not necessary.

*

*To make your code work you need one more input argument i.e., the "name" of the transformer.
Full example:
df
    col1   col2  col3
0   blue    car   new
1  green  truck  used
2    red    van   new

ct = ColumnTransformer([("onehot",OneHotEncoder(),[0,1,2])])

ct.fit_transform(df.values)
array([[1., 0., 0., 1., 0., 0., 1., 0.],
       [0., 1., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 1., 1., 0.]])

*Now notice that you get the same output by only using OneHotEncoder:

o = OneHotEncoder()
o.fit_transform(df).toarray()

array([[1., 0., 0., 1., 0., 0., 1., 0.],
       [0., 1., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 1., 1., 0.]])


text:
Q: Can Jenkins build code to remote servers when triggered by GitHub webhook? I have a 'master' server (docker container actually) where I want to install Jenkins in order to link it (with webhook) with a github repo, so every time a developer pushes code, jenkins will auto-pull and build the code.
The thing is that there are an arbitrary number of extra 'slave' servers that need to have the exact same code as the master.
I am thinking of writing an Ansible playbook to be executed by Jenkins everytime the webhook runs and send the code to the slaves.
Can Jenkins do something like this?
Do I need to make the same setup to all the slaves with Jenkins and webhooks?
EDIT:
I want to run a locustio master server on the server that is going to have jenkins. My load tests are going to be pulled from Github there, but the same code needs to reside in the slaves in order to run in distributed mode.

A: The short answer to your question is that Jenkins certainly has the ability to run Ansible playbooks.  You can add a build-step to the project that is receiving the web hook that will run the playbook.

A: jenkins could trigger another job even on slaves. Then if i get correctly your issue , you just need something like that. https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Remote+Trigger+Plugin
You could build your job by name trigger. Also there is another useful plugin called artifactory. This manages your packages and serves. This mean , you can build your code for once and share to slave and slaves could access your build and runs job.


text:
Q: Check Ubuntu for Installation Issues/Errors I upgraded from Ubuntu 12.10 to 13.04. I have got an error massage before the upgrade was finished and now i have the feeling that Ubuntu 13.04 was not installed correctly. How can i check/scan the OS for errors ? I dual boot with Windows 7.

A: To be honest I'm not aware of any utility to scan for installation errors, but if you are experiencing some weird behaviour from the OS, you could try to reinstall the ubuntu-desktop metapackage, it should reinstall everything that may be lost/damaged during the upgrade.
I'm using Kubuntu, and sometimes when I get problems in updating the files of the KDE environment, reinstalling kubuntu-desktop (which, as you can guess, is the equivalent to ubuntu-desktop for Kubuntu) solves anything.
Anyway, from a more general point of view, I found that when making major version upgrades, it is better to use a LiveCD, rather than using the built-in upgrade options, it causes far less problems; if you have your /home folder on a separate partition, you won't lose any data, and you simply have to reinstall some software.
You can also check this and this.


text:
Q: Storing Blob as int16 instead of int8 JS I'm actually storing data obtained via MediaRecorder from an audio stream into a Blob which, after being read by FileReader.readAsArrayBuffer(), is represented as a Int8Array. Is there any way to read it as an Int16Array instead?
The recording method has been extrated from here
Thanks in advance.

A:
After being read by FileReader.readAsArrayBuffer(), is represented as a Int8Array

No, it's a buffer.

Is there any way to read it as an Int16Array instead?

No, but you can trivially construct any typed array "view" that you need on that buffer:
new Int16Array(fileReader.result)


text:
Q: Swapping IP addresses between two domain controllers On our VMWare ESXi environment is a single domain controller (Windows Server 2008R2) installed. Now I have to upgrade it to a new server (Windows Server 2012R2) which should has the same IP.
Many applications (no reliable list of applications exists) point to the current DC (Windows Server 2008R2) as their sole LDAP source. Not sure if they point to the name or IP address. Also the other server in our ESXi has as the a static DNS IP address of our domain controller.
That is why I have to migrate it without breakdowns.
Have you got any experiences how can I realize that wihtout any issues after the change.  Or are there some references from microsoft? Thank you in advance!

A: While knowing how to do this can be useful in certain situations, as EEAA pointed out, you should probably have two DCs instead of one. If for nothing more than a disaster recovery/ backup.
If you are not performing backups of your current DC... START PERFORMING AD BACKUPS BEFORE DOING ANYTHING ELSE.
You should be able to do this without too much headache.  After making the change you should definitely make it a priority to document where references to your DCs are in your environment.
This should be done at a time to minimize downtime.

*

*Bring up your new DC using a new static IP address. Have it DCPromo'ed in and make sure it's fully functional before proceeding. (Have the new DC point to the original for DNS)

*Give the 2008R2 DC the new static address, and the 2012R2 DC the original IP.

*Client side DNS Settings on the DCs here are important, if you are keeping two DCs DNS should point to the opposite DC then itself.  If you are only keeping the one, point DNS to itself on both.

*Restart AD DS services on both DCs, as well as the netlogon service.

*Check DNS to ensure that all the records have been updated appropriately (A, & SRV)

*Check AD logs to ensure there are no issues with replication (either FRS or DFSR)

If you were going to remove the original DC, you would then:

*

*Transfer any FSMO roles the DC holds

*DCpromo the DC out

*Verify it has been demoted properly and all SRV records have been removed from DNS.

If you still need a temporary fix for applications that point to a removed DC by name, you could add a CNAME record to DNS for that DC that points to the new DC.
Again, you should probably have two DCs.
Also, for further insight and information, see this other SF question: Windows 2003 DC to Windows 2008 R2 DC with same name and same IP that takes into account other factors that might be involved (same concepts apply in your situation still).

A: I successfully did this very recently.
Here is how you should proceed to have no down-time:
[Prerequisites]

*

*Make sure current DNS system works fine - dcdiag /test:DNS /v/e - all 6 roles (Auth, Basic, FW, Del, Dyn and RReg) should show PASS. If they do not, you have to have them PASS before you continue.

*Let's assume that your 2008R2 IP is 192.168.1.10 and your new 2012 IP is 192.168.1.11. You will also require a buffer temporary IP (let's say we use 192.168.1.99).
[Procedure]

*

*Give your new server the IP to be added to DC with: 192.168.1.11

*Add your new server to the DC.

*Make sure your new IP/server shows under Forward Lookup Zones --> YourDomainName --> Properties --> Name Servers. If it does not, add it there.

*Make sure your new IP/server shows under Forest DNS Zones and Domain DNS Zones. If it does not, add it there.

*Run again dcdiag /test:DNS /v/eto make sure both servers show PASS in all 6 roles.

*Now it's time to swap both IPs as fast as possible. Change the old 192.168.1.10 server IP to temporary one (192.168.1.99).

*Run the following on a command prompt on it:
ipconfig /flushdns
Net Stop DNS
Net Start DNS
Net Stop Netlogon
Net Start Netlogon
ipconfig /registerdns

*Change the IP of the new server 192.168.1.11 to your original IP (192.168.1.10)

*Run the following on a command prompt on it:
ipconfig /flushdns
Net Stop DNS
Net Start DNS
Net Stop Netlogon
Net Start Netlogon
ipconfig /registerdns
dcdiag /fix

*Make sure everything shows as PASS again.

*Transfer all FSMO roles to the new server.

*Use DCPromo to remove the old server.
Note on the roles: when I made the upgrade I did not have to have downtime at all because roles were on a 3rd server until the upgrade was made.


text:
Q: Finding family of $g$ functions with algebraic property Consider the family of functions $g$ that satisfy the following conditions over a certain field or algebra:
$$ g(uv, w) =g(u,w) g(v,w) $$
over any elements $u, v, w$ of the given field or algebra
How does one determine or characterise this family of functions?
In the particular case that the family of function is analytic and the field is Abelian,
$$g(u,v)= \sum_{m,n} a_{m,n}u^m v^n $$
 I get the following nilpotent condition on coefficients:
$$ \sum_{p+q=m} a_{p,n} a_{q,n} = a_{m,n}  $$
for all m and n
I'm not sure how to interpret this condition other than it seems to be its own square

A: The argument $w$ is merely an index. It's more instructive to write this as
$$g_w(uv) =g_w(u) g_w(v) $$
Then we see that $g$ is just an arbitrary indexed family of homomorphisms of the multiplicative semigroup.


text:
Q: Pass an object to null if some values are empty I have an object :
 contact:{
   email: ""
   firstName: ""
   id: 800
   lastName: ""
   phone: ""
   title: "MS"
   url: "/api/contacts/800"
  }

I would like to pass the whole object Contact to null, if the "lastName", "firstName", "Phone" and "email" fields are empty.
Do you have a solution ?

A: I don't know if it is what you are expecting but you can try this :
let contact = {
  email: "",
  firstName: "",
  id: 800,
  lastName: "",
  phone: "",
  title: "MS",
  url: "/api/contacts/800"
};

if (
  contact.email === "" ||
  contact.firstName === "" ||
  contact.lastName === "" ||
  contact.phone === ""
) {
  contact = null;
}

console.log(contact);


text:
Q: Make Mathematica wait before replacing? How can I force Mathematica to completely evaluate a subexpression before using a replacement rule?
For example, consider the following definition (for the series of n correction factors in Stirling's formula):
stirlingSeries[n_] :=
Series[Exp[
Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
   2 n + 2}]]], {h, 0, n}] /.
t^m_ -> If[Mod[m, 2] == 0, (m - 1)!!, 0]

What I want to tell Mathematica to do is replace powers of t at the end, as the very last step in calculating stirlingSeries[n].  Instead, it replaces them first.  This changes the result of the calculation.

A: Let me guess what could be the problem: you could have defined m before executing the definition of stirlingSeries that you wrote in the question. In that case, the replacement rule -> would have assigned the current value of m, instead of the delayed value. To illustrate what I think went wrong, here is the scenario:
m = 4

(* ==> 4 *)

stirlingSeries[n_] :=
 Series[Exp[
    Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
       2 n + 2}]]], {h, 0, n}] /.
  t^m_ -> If[Mod[m, 2] == 0, (m - 1)!!, 0]

stirlingSeries[4]

$$1+\sqrt{h}-\frac{7 h}{12}+\frac{199
   h^{3/2}}{540}-\frac{3193
   h^2}{12960}+\frac{46801
   h^{5/2}}{272160}-\frac{6084467
   h^3}{48988800}+\frac{13558333
   h^{7/2}}{146966400}-\frac{494880067
   h^4}{7054387200}+O\left(h^{9/2}\right)$$

stirlingSeries[n_] :=
 Series[Exp[
    Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
       2 n + 2}]]], {h, 0, n}] /.
  t^m_ :> If[Mod[m, 2] == 0, (m - 1)!!, 0]

stirlingSeries[4]

$$1+\frac{h}{12}+\frac{h^2}{288}-\frac{139 h^3}{51840}-\frac{571
   h^4}{2488320}+O\left(h^{9/2}\right)$$

On the last lines, I changed the definition to RuleDelayed (:>) which does what I believe you want: take the value of m to be that found in the pattern t^m_.


text:
Q: Parameterization and geodesics of a 3-torus So I'm thinking about a space exploration game where the primary mechanic is to fly a space ship around the surface of various 4-dimensional surfaces. The way I'd like to render this is by ray casting along the parameters of a surface; my possibly faulty assumption being that the ray would follow the geodesics of the surface (This appears to be true as far as I have seen). I've been able to look many parameterizations up such as ones for the unit 3-sphere, and a Klein bottle and a couple other things in lower dimensions that I might play with for surfaces of planets (terrestrial walking). I was hoping for parameterization of more spaces so that I could explore those as well. The tours seems most interesting because it seems to me like you would only see discreetly many copies of yourself and those copies would be different sizes. For instance you would see two quite large copies of yourself in the two cardinal directions and some smaller ones in between. This feels a lot more mentally manageable than seeing an exact copy of myself in every direction all of which are equally far away as in the 3-sphere case. If possible I'd also like to explore n-fold toruses as well.
So my question is a) what are the geodesics of a 3-torus and b) what is an example of a parameterization of a 3-torus. Do the rays cast though the parameterization match up with the geodesics of the torus?
bonus question: what are the geodesics and parameterizations of 2-fold and 3-fold toruses? What about 2-fold and 3-fold toruses in higher dimensions?


text:
Q: Create custom radio button I am trying to create the attached image using radio button groups. After trying multiple combinations I am not able to achieve what is intended.
The intention is to create a circular background around the solid circle whenever one radio button is selected.

Any help would be appreciated.

A: The radio button images are controlled by a StateListDrawable. When a radio button is check (state_checked="true"), the drawable assigned to the checked state is shown. When the state is "not checked" (state_checked="false"), the drawable assigned to the "not checked" state is shown. Here is an example StateListDrawable:
custom_radio_button.xml
<selector>
    <item android:state_checked="true" android:drawable="@drawable/ic_baseline_check_circle_24" />
    <item android:state_checked="false" android:drawable="@drawable/ic_baseline_check_circle_outline_24" />
</selector>

Here, I have just selected two vector graphic files from Android Studio. You will need to create the checked/unchecked images that you want.
Now, in the XML for the layout, specify the you want to use this StateListDrawable for the radio button.
...some XML...
<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_radio_button"
    android:checked="true"
    android:text="RadioButton 1" />
...more XML...

You would need to place this radio button and its sisters into a radio group.
Putting it all together gives the following:


text:
Q: change position of image when hover effect to css3 I have a css file that uses an image as button, when user hovers the button the image is realocated to other position like:
button.btn,
input[type="submit"].btn {
  *padding-top: 2px;
  *padding-bottom: 2px;
    background: url(http://www.eurekavi.com/ci_crud_1/assets/grocery_crud/themes/flexigrid/css/images/btn_cancelar.png) no-repeat;
    border: none;
    cursor: pointer;
    display: block;
    height: 30px;
    text-indent: -3000px;
    width: 80px;

}

button.btn,
input[type="submit"].btn:hover  {
background: url(http://www.eurekavi.com/ci_crud_1/assets/grocery_crud/themes/flexigrid/css/images/btn_cancelar.png) no-repeat 0 -30px;
    }

In html i add the code:
<div class="form-button-box">
    <input type="submit" value="" class="btn btn-large" />
</div>

After doing this a button will appear holding text that the image has. it works nice.
But then if text is a variable I can not do that, I would have to make a different image for different texts... That is not good.
I would like to generate a input button passing the text of button as attribute and have the same effect, I have two issues:

*

*How to generate correct color and get inmediatly to other color when hover.
(Do you know any good generator) my base color is #7d7d7d and final #272727

*how to avoid a strange effect in my button, when hover it is like animating or sliding and not doing it straight away, please take a look at my fiddle
could you please help me acomplish the last button (without that sliding effect, I mean change color inmediatly when hover) shown in this fiddle?

A: You need to make everything with CSS and not use images so you don't have to make a bunch of images for different texts. Check out this site to use to generate gradient code quickly. Otherwise, your buttons are fairly simple and can easily be made with CSS. Let me know if I am missing the point of your question.


text:
Q: command to generate a \cite{} only on first use In a book dealing with R, I use a command \pkg{} for every mention of an R package, that also generates index extries via another command \ixp{}.
\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1}}

All packages have .bib entries, and I'd like to modify this so that the package is also \cite{}d in the text on its first use, but thereafter generates a \nocite{}. That is, something like
\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1} \citep{#1}}

but where \citep{#1} becomes \nocite{#1} if the .bib key argument (#1) has occurred before in the text. (As I recall, glossary packages do something like this.)  How can I modify this definition to achieve this behavior?
The goal here is to also generate the references for all packages, but avoid cluttering the text with a citation for each mention.  Using \nocite{} after the first occurrence is desired for the purpose of generating entries in an Author index.
Here is a MWE:
\documentclass[12pt]{book}

\usepackage[comma]{natbib}
\renewcommand{\bibname}{References}
\bibliographystyle{abbrvnat}

\usepackage{imakeidx}
\makeindex[title=Subject Index,columns=2]

% Cited packages

\newcommand{\Rpackage}[1]{\pkg{#1} package}
%\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1}}
\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1} \citep{#1}}

% R packages:  indexed under both package name and packages!
\newcommand{\ixp}[1]{%
   \index{#1@\textsf{#1} package}%
   \index{package!#1@\textsf{#1}}%
    }

\usepackage{filecontents}
\begin{filecontents}{references.bib}
@Manual{vcd,
  title =        "vcd: Visualizing Categorical Data",
  author =       "David Meyer and Achim Zeileis and Kurt Hornik",
  year =         "2015",
  note =         "R package version 1.3-3",
}

@Manual{vcdExtra,
  title =        "vcdExtra: vcd Extensions and Additions",
  author =       "Michael Friendly",
  year =         "2015",
  note =         "R package version 0.6-7",
  URL =          "http://CRAN.R-project.org/package=vcdExtra",
}

\end{filecontents}

\begin{document}

\chapter{First chapter}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra}.
% Should generate a \citep{vcd} and \citep{vcdExtra}

\section{First section}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra} again.
These should generate nocite instead.
% Should generate a \nocite{vcd} and \nocite{vcdExtra}

\chapter{Second chapter}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra} again
These should generate nocite instead.
% Should generate a \nocite{vcd} and \nocite{vcdExtra}

\section{First section}
asfdAFASFAF

\bibliography{references}
\printindex

\end{document}
% ----------------------------------------------------------------

A: May be you need this:
\def\pkg#1{\textsf{#1}\ixp{#1}~\citex{#1}}
\def\citex#1{\expandafter\ifx\csname cit:#1\endcsname\relax
      \expandafter\gdef\csname cit:#1\endcsname{}%
      \citep{#1}%
   \else
      \nocite{#1}%
   \fi
}

The \citex macro tests if the parameter was used before, i.e. if the control sequence \cit:parameter is defined. If not, then it expands to \citep{parameter} and defines \cit:parameter. Else it expands to \nocite{parameter}.

A: I added a *-variant that prints the citation anyway, and it doesn't count as the first (maybe you want it in the introduction or later in the document).
\begin{filecontents*}{\jobname.bib}
@Manual{vcd,
  title =        "vcd: Visualizing Categorical Data",
  author =       "David Meyer and Achim Zeileis and Kurt Hornik",
  year =         "2015",
  note =         "R package version 1.3-3",
}

@Manual{vcdExtra,
  title =        "{vcdExtra}: vcd Extensions and Additions",
  author =       "Michael Friendly",
  year =         "2015",
  note =         "R package version 0.6-7",
  URL =          "http://CRAN.R-project.org/package=vcdExtra",
}

\end{filecontents*}

\documentclass[12pt]{book}

\usepackage[comma]{natbib}
\renewcommand{\bibname}{References}
\bibliographystyle{abbrvnat}

\usepackage{imakeidx}
\makeindex[title=Subject Index,columns=2]

% Cited packages

\newcommand{\Rpackage}[1]{\pkg{#1} package}
%\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1}}

\makeatletter
\DeclareRobustCommand{\pkg}{%
  \@ifstar{\@tempswatrue\pkg@do}{\@tempswafalse\pkg@do}%
}
\newcommand\pkg@do[1]{%
  % fixed part
  \textsf{#1}\ixp{#1}%
  \if@tempswa
    \space\citep{#1}%
  \else
    \ifcsname pkg@cited@#1\endcsname
      %\nocite{#1}% uncomment, if you want, but it does nothing
    \else
      \space\citep{#1}%
      \global\expandafter\let\csname pkg@cited@#1\endcsname\@empty
    \fi
  \fi
}
\makeatother

% R packages:  indexed under both package name and packages!
\newcommand{\ixp}[1]{%
   \index{#1@\textsf{#1} package}%
   \index{package!#1@\textsf{#1}}%
    }

\begin{document}

\chapter{First chapter}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra}.
% Should generate a \citep{vcd} and \citep{vcdExtra}

\section{First section}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra} again.
These should generate nocite instead.
% Should generate a \nocite{vcd} and \nocite{vcdExtra}

But we want to cite \pkg*{vcd} again.

\chapter{Second chapter}
Here we mention the \pkg{vcd} package and \pkg{vcdExtra} again
These should generate nocite instead.
% Should generate a \nocite{vcd} and \nocite{vcdExtra}

\section{First section}
asfdAFASFAF

\bibliography{\jobname}
\printindex

\end{document}

A: on the assumption that \nocite isn't really needed, this should work:
\newcommand{\expkg|[1]{\textsf{#1}\ixp{#1}}
\newcommand{\pkg}[1]{\textsf{#1}\ixp{#1} \citep{#1}\expkg{#1}}

after all, a single \cite will put an entry in the \.aux file that tells
bibtex to identify a matching entry in the .bib file and create an equivalent
entry in the .bbl file -- only one is needed.  the usual purpose of \nocite
is to ensure that an item is included in the .bbl file (thus in the bibliography)
if it is not actually cited in the text.

A: This is not a direct answer, but perhaps you would find it useful. Here is a package I wrote, but never published to serve a similar but not identical purpose. The purpose of this package is to make it easier to write articles on programming languages. To reference a language such as Java, you write \Java in your input. It would add the citation, but only if this is the first use of the command.

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{yogi-lang}[2005/09/12 v0.6]
\DeclareOption{terse}{\relax}
\DeclareOption{verbose}{\relax}
\ProcessOptions

\RequirePackage{xspace}
\newcommand{\@pl}[1]{\mbox{\textsc{\ensureLR{#1}}}\xspace}
\newcommand\lang[1]{\@pl{#1}}

\newcommand\NonCitingUseX[1]{\csname nocite#1\endcsname}
\newcommand\NonCitingUse[1]{\NonCitingUseX{#1}\xspace}
\newcommand\@IgnoreLanguageCitation[1]{%
    \expandafter\gdef\csname#1\endcsname{\csname nocite#1\endcsname}%
}
\newcommand\StopLanguageCitation[1]{%
\expandafter\gdef\csname#1\endcsname{\csname nocite#1\endcsname\xspace}%
}

\def\@LANG#1#2#3{%
    \expandafter\gdef\csname nocite#1\endcsname{#3}% Define the base version, as e.g., \nociteJava
    \expandafter\gdef\csname#1\endcsname{% First time invocation.
        \NonCitingUseX{#1}\relax      % Invoke the base version.
        \StopLanguageCitation{#1}\relax % Reset the definition for all future uses.
         ~#2\relax                    % Append the citation.
        \xspace
    }%
    \xspace
}

\newcommand\NewLanguageCitation[2]{\@LANG{#1}{\textup{#2}}{\textsc{#1}}}
\newcommand\NewLangaugeCitationSpecial[3]{\@LANG{#1}{#2}{#3}}

\DeclareOption{terse}{%
\gdef\@LANG#1#2#3{%
    \expandafter\gdef\csname nocite#1\endcsname{#3}% Define the base version, as e.g., \nociteJava
    \expandafter\gdef\csname#1\endcsname{% First time invocation.
        \NonCitingUseX{#1}\relax      % Invoke the base version.
        \StopLanguageCitation{#1}\relax % Reset the definition for all future uses.
        %~#2\relax                    % Append the citation.
        \xspace
    }%
   \xspace
}}

\ProcessOptions
\def\STOPLANGUAGECITATION{\def\langcite##1{}}
\def\STARTLANGUAGECITATION{\def\langcite##1{\cite{##1}}}
\STARTLANGUAGECITATION
%Use alphabetical ordering
\NewLanguageCitation{Go}{\langcite{XXX}}
\NewLangaugeCitationSpecial{AJEE}{\langcite{Cohen:Gil:04}}{\textsc{AspectJ2EE}}
\NewLanguageCitation{Ada}{\langcite{Tucker:97}}
\NewLanguageCitation{BCPL}{\langcite{Richards:Whitby-Strevens:80}}
\NewLanguageCitation{AspectJ}{\langcite{Kiczales:2001}}
\NewLanguageCitation{AWK}{\langcite{Aho:Kernighan:Weinberger:Book:88}}
\NewLanguageCitation{Basic}{}
\NewLanguageCitation{CPL}{\langcite{Kernighan:Ritchie:Book:88}}
\NewLangaugeCitationSpecial{CC}{\langcite{Stroustrup:Book:97}}{\mbox{C++}}
\NewLanguageCitation{Cecil}{\langcite{Chambers:Cecil:93}}
\NewLanguageCitation{CLOS}{\langcite{CLOS}}
\NewLanguageCitation{Cobol}{}
\NewLanguageCitation{CommonLoops}{\langcite{Bobrow:Kahn:Kiczales:Masinter:Stefik:Zdybel:86}}
\NewLangaugeCitationSpecial{CProlog}{\langcite{Shapiro:87}}{\textsc{Concurrent Prolog}}
\NewLangaugeCitationSpecial{CSharp}{\langcite{Hejlsberg:Wiltamuth:Golde:03}}{\textsc{C}${}^{\#}$}
\NewLanguageCitation{Datalog}{\langcite{Ceri:Gottlob:Tanca:90}}
\NewLanguageCitation{Dylan}{\langcite{Dylan:Shalit:97}}
\NewLanguageCitation{Eiffel}{\langcite{Eiffel:Reference:97}}
\NewLanguageCitation{Fickle}{\langcite{Drossopoulou:Damiani:Ciancaglini:Giannini:01}}
\NewLanguageCitation{Flavors}{\langcite{Moon:Flavors:86}}
\NewLanguageCitation{Fortran}{}
\NewLanguageCitation{Haskell}{\langcite{Jones:03}}
\NewLanguageCitation{Jam}{\langcite{Ancona:Lagorio:Zucca:03}}
\NewLanguageCitation{Java}{\langcite{Arnold:Gosling:96}}
\NewLanguageCitation{JavaScript}{\langcite{Flanagan:11}}
\NewLanguageCitation{Kea}{\langcite{Kea}}
\NewLanguageCitation{Lisp}{\langcite{Graham:95}}
\NewLanguageCitation{Mathematica}{\langcite{mangano:10}}
\NewLanguageCitation{Mesa}{}
\NewLanguageCitation{MixGen}{\langcite{Allen:Bannet:Cartwright:03}}
\NewLanguageCitation{ML}{\langcite{ml-spec:Milner:Tofte:Harper:MacQueen:97}}
\NewLanguageCitation{Modula}{\langcite{Nelson:91}}
\NewLanguageCitation{NextGen}{\langcite{Allen:Bannet:Cartwright:03}}
\NewLanguageCitation{Oberon}{\langcite{Wirth:Reiser:Book:92}}
\NewLanguageCitation{ObjectiveC}{\langcite{Cox:Book:Evolutionary:86}}
\NewLanguageCitation{Pascal}{\langcite{Wirth:71}}
\NewLanguageCitation{Perl}{\langcite{Perl:94}}
\NewLanguageCitation{PHP}{\langcite{Lerdorf:Tatroe:02}}
\NewLangaugeCitationSpecial{PLI}{\langcite{Hughes:86}}{\textsc{PL/1}}
\NewLanguageCitation{PolyGlot}{\langcite{PolyGlot}}
\NewLanguageCitation{Prolog}{\langcite{Deransart:Cervoni:Ed-Dbali:96}}
\NewLanguageCitation{Python}{\langcite{Lutz:96}}
\NewLanguageCitation{Ruby}{\langcite{Thomas:Hunt:00}}
\NewLanguageCitation{Scala}{\langcite{Odersky:Altherr:Cremet:Emir:Maneth:Micheloud:Mihaylov:Schinz:Stenman:Zenger:04}}
\NewLanguageCitation{Scheme}{\langcite{Dickey:92}}
\NewLanguageCitation{SED}{\langcite{ref:sed}}
\NewLanguageCitation{Self}{\langcite{Ungar:Smith:87}}
\NewLanguageCitation{Smalltalk}{\langcite{Goldberg:Book:84}}
\NewLanguageCitation{SQL}{}
\NewLanguageCitation{Tcl}{\langcite{Ousterhout:90}}
\NewLangaugeCitationSpecial{THETA}{\langcite{Liskov:al:95}}{\lang{Theta}}
\NewLanguageCitation{XQuery}{\langcite{XQuery}}
\NewLanguageCitation{APL}{\langcite{Iverson:62}}


text:
Q: How to setup Gruntfile to use compass/sass on heroku? I've successfully set up my heroku app with the grunt buildpack. When I push my Node.js app to heroku it will run the appropriate grunt task.
What I'd like is to use the 'grunt-contrib-compass' package to compile my .scss files. But that requires the compass executable and I don't know how to get that.
I've checked the heroku documentation and have seen an outdated doc that describes setting up compass with ruby... but I haven't seen any recent documentation for setting it up with Node.js.
Any ideas?

A: This took a lot of figuring out, but I've finally managed to get it to work. What's needed is to get Ruby to install alongside your Node.js app, so you can install the appropriate gems. This gist was very helpful and more-or-less describes what I needed to do.
In summary, the process was:

*

*Create the files .buildpacks, Gemfile, and Gemfile.lock in the project directory, with the following contents:

.buildpacks
https://github.com/heroku/heroku-buildpack-ruby.git
https://github.com/heroku/heroku-buildpack-nodejs.git

Gemfile
source "http://rubygems.org"
gem "sass"

Gemfile.lock
GEM
  remote: http://rubygems.org/
  specs:
    sass (3.4.5)

PLATFORMS
  ruby

DEPENDENCIES
  sass

nb. I'm only using Sass, not Compass, but I'm guessing all you'll need to do to get compass is just add gem "compass" to the Gemfile and, eg. compass (1.0.3) below sass in the Gemfile.lock.

*

*Add a multi buildpack to your app:
heroku config:add BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git

*Finally, push these out to Heroku, and Ruby and Sass should install alongside your Node.js app, allowing you to use sass-related grunt tasks.

A: There is a forked-fork that includes compass installation. That might help:
https://github.com/stephanmelzer/heroku-buildpack-nodejs-grunt-compass

A: I got my app working on heroku using grunt-sass  instead of grunt-contrib-sass. To swap them out just do npm install --save grunt-sass and then swap out the grunt-task wherever it's used (e.g.
  grunt.loadNpmTasks('grunt-sass') instead of grunt.loadNpmTasks('grunt-contrib-sass')


text:
Q: .Net Architecture challenge: The Change-prone Frankestein Model Good Morning SO!
We've been scratching our heads with with this interesting scenario at the office, and we're anxious to hear your ideas and approaches:

*

*We have a database, whose schema is
prone to changes -lets call it
Prony-. (is used to store configuration parameters for
embedded devices. so if the embedded
devices guy need a new table,
property or relationship for the
model, he should be able to adapt
the schema in a easy way -happens so
often- ).

*Prony needs a web interface to
    create/edit its data (a set of simple CRUDs would be enough).

*We have another database containing
    data that also need to be loaded to
    the devices, after making some
    transformations - lets call this one
    Oddy- (this data it's generated by an already existent
    administrative web application).

*Finally we have Tracy, a server that communicates our DBs and our embedded devices.
She should to auto-adapt herself, to our dbs schema changes and serialize the data to the devices.
Nice puzzle, don't think so? : )

Our current candidate:

*

*Rady: The fast
Lets create some views in
Prony that make the data transformation from Oddy. then
use DynamicData (or some RAD
tool) to create/update a simple web
interface for Prony (so he can
even consult the transformated data
from coming from Prony : ). About
Tracy, she will need to be recompiled
to update her DB schema (Entity framework should work) and use Reflection to explore recursively the schema and serialize data.
Cons:

*

*We would have to recompile Tracy and the Prony's web interface.

What do you think of the candidate?
Any ideas?

A: One way to deal with a data model that is constantly changing after product release is to use the EAV Database Model, in whole or in part, of your database design. The EAV structure adds rows rather than columns or tables and allows for much less frequent schema changes (or none at all.)
It does come with its own set of caveats of course, such as the need to often pivot the data, but they can be managed. There are plenty of EAV dbs out there in production.
Performance note: People often worry about the performance of EAVs. i've have a number of EAVs with the EAV tables running well over 10 million records. Reads, inserts, updates and deletes are fine. The trouble comes in when you start doing heavy reporting on such a data structure. In your case you're storing config info for devices. That's not innocuous or trivial but I would say that that part of the db sounds like a great candidate for EAV since your reads and writes are going to be limited and i'm guessing that your reporting needs simple.


text:
Q: How do I create an SDK style project for a .net framework 4.7.2 project in using visual studio? I am running the latest version of VS2019 16.6.1
Yet the new project wizard for a windows class library still creates the old style project.
I want to use this method to research this problem
I found some help on converting framework projects here but not on creating new ones from scratch.

A: The simplest approach in my experience is to create a .NET Core/Standard project for whatever type of application you want (e.g. console or class library) and then edit the csproj file by hand. (You can edit the csproj file by just double clicking on the project in Visual Studio, if it's an SDK-style project.)
So as a concrete example, to create a .NET 4.7.2 class library, I'd choose "Class Library (.NET Standard)" from the list of project templates. That creates a project file like this:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

</Project>

Just edit the project to specify the target framework you actually want - so for .NET 4.7.2 you'd use:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net472</TargetFramework>
  </PropertyGroup>
</Project>

(I tend to tidy up the XML at the same time removing the blank lines like that, but you don't have to of course :)


text:
Q: Moving mysql columns to another table I have a mysql issue. Hope one of you can help me!
I have two tables with same length and I would like to move the table_2's columns next to table_1's columns by matching the unique id (u_id).
Table structures that I have;
table_1
id - u_id - field_1 - field_2
1  - 123  - abc     - (empty)
2  - 456  - fgd     - (empty)

table_2
id - u_id - field_2
1  - 123  - kjh
2  - 456  - mnb

Table structures that I want;
table_new
id - u_id - field_1 - field_2
1  - 123  - abc     - kjh
2  - 456  - fgd     - mnb

How can I do this?
Thanks...

A: At mysql prompt:
INSERT INTO table_new (id, u_id, field_1, field_2) SELECT t1.id, t1.u_id,
    t1.field_1, t2.field_2 FROM table_1 t1 JOIN table_2 t2 ON (t1.u_id = t2.u_id);

or just
UPDATE table_1 SET field_2 = (SELECT t2.field_2 FROM table_2 t2 WHERE t2.u_id = table_1.u_id)

A: I would use the multi-table UPDATE syntax.
UPDATE table1 JOIN table2 USING (u_id)
SET table1.field_2 = table2.field_2;

A: Straightforward enough to do it in php.
Here is some pseudo code to get you started.
   SELECT u_id, field_1 FROM table_1;
   (while results)
   {
            SELECT field_2 FROM table_2 WHERE u_id = ?;

              INSERT INTO table_new VALUES (u_id, field_1, field_2);

  }

A: Assuming you have a php function called query which you normally use for select statements:
$tables = array();
$tables[] = query("DESCRIBE table_1");
$tables[] = query("DESCRIBE table_2");

$sql = "CREATE TABLE `table_new` {";

foreach ($tables as $table) {
  foreach ($table as $col) {
    $sql .= "`".$col['Field']."` ".$col['Type'];
    if ($col['Null'] == "NO") $sql .= " NOT ";
    $sql .= " NULL";
    if ($col['Default'] != "NULL") $sql .= " DEFAULT '".$col['Default']."'";
    $sql .= ", ";
  }
}

$sql .= ")";

That's the basic idea.. if you need to maintain foreign keys or triggers you'll need to start looking in the information_schema.statistics table

A: create table table_new as select t1.id, t1.u_id, t1.field_1, t2.field2 from table_1 t1 left join table_2 t2 on t1.u_id = t2.u_id;

A: First, create table_new. Then, use the MySQL SELECT INTO. Maybe something like this:
INSERT INTO table_new SELECT table_1.u_id, table_1.field_1, table_2.field_2
FROM table_1 LEFT JOIN table_2 USING (u_id);


text:
Q: Color perception of UV light? I just finished watching a video that explained some of how UV light looks with a UV camera. In the video, at one point the UV camera made everything distinctly green. At another point, everything was purple instead of green. The video had demonstrations about absorbing UV light and how that made things darker vs. reflecting UV light made them brighter, but I still don't know how the green to purple shift happened.
Was that an issue of the camera lens? Is my own color perception somehow incorrect and there was never any green at all?

A: Here is another video about a UV camera from Veritaseum. The World in UV. It does not explain what you asked, but it does make something clear. The UV camera detects UV light. It then shows it to you with light you can see. That light is visible. So you can conclude that a UV camera is a UV to visible converter.
To a degree, that is all you need to know. You can't see UV, so the camera has to pick some color you can see. It doesn't really matter which one it picks. I depends on the manufacturer.


text:
Q: OpenMp parallelization region calls a subroutine which also calls a subroutine My code works well without parallelization. But it doesn't with parallelization.
My code consists of a module that contains an array of size 100x100x100.
real(8), dimension(1:100,1:100,1:100) :: array

This module is placed at the lower hierarchical level so it can be called by any other module. And then the other module that consists of a do loop which calls a subroutine.
do i=1,100
  do j=1,100
    do k=1,100
      call some_calculation(i,j,k)
    enddo
  enddo
enddo

The subroutine some_calculation performs some arithmetic process using the array(i,j,k) and then update array(i,j,k). The input values i,j,k correspond to accessing array(i,j,k). But when I parallelize the most outer do loop
!$OMP PARALLEL DO
do i=1,100
  do j=1,100
    do k=1,100
      call some_calculation(i,j,k)
    enddo
  enddo
enddo
!$OMP END PARALLE DO

I receive different results of array. Does anyone has any clue for this? Thanks you!

A: Your loop indices should be private:
!$OMP PARALLEL DO private (i,j,k)
do i=1,100
   do j=1,100
      do k=1,100
         call some_calculation(i,j,k)
      enddo
   enddo
enddo
!$OMP END PARALLEL DO


text:
Q: What methods or actions we should avoid when build a wordpress site? There are many tutorials talk about how to build wordpress site from a theme or scrath.
But I want to know what's the worst way to build a wordpress site?
I heard people saying: Using hooks instead of override. I am not sure if this is true. If this is true, then we should aoid override files?
WTF wrong with people give me negative 1? This is a reasonable question. If you don't want to help, just leave.

A: The best way to build custom themes is to get a book and learn the right way to use template hierarchies and custom post types. Make use of the loop using wp_query. Use WordPress template tags , methods and functions if they exist rather than writing your own.
The worst way to build a theme is to reinvent the wheel, writing your own code for things that already exists. Not only will it take a lot longer, but it will more more likely to break during updates and harder for other people to understand.


text:
Q: Printing Stars in java public static void processQuestionData()
{
   double[] cake = {3.6, 7.8, 15.8}
   double carrot = 15.8

   for (int i = 0; i < cake.length; i++)
    {

        drawBar(cake[i], carrot);

    }

public static void drawBar(double value, double max )
{
    final int MAX_STARS = 20
    String BAR_REP = "*";

    double correctRatio = (value / max) * MAX_STARS;

    if (correctRatio == MAX_STARS)
    {
        for (int index = 0; index < MAX_STARS; index++)
        {
            System.out.print(BAR_REP);
        }
    }

    else if (correctRatio < MAX_STARS)
    {
        for (int index = 0; index < MAX_STARS; index++)
        {
            System.out.print(BAR_REP);
        }
    }
}

I want given a value and a max as double type arguments, draws a bar using * representing the value, scaled so that max value would equal the constant MAX_STARS. I am not able to do that what is wrong with my code?
 Output should be
 ****
 *********
 ********************

1st star gotten by (3.6 / 15.8) * 20 = 4
3rd star gotten by (15.8 / 15.8) * 20 = 20
How can I do that?

A: A FEW CHANGES IN YOUR CODE WILL MAKE IT RUN PROPERLY:
I feel that your code may not be displaying the output correctly because of the missing System.out.println(); statement (that I have added in the last line of the code). Also the conditional checking you were performing was redundant. Instead of checking for = and < seperately you can check for <= in one block itself.
public static void processQuestionData()
{
   double[] cake = {3.6, 7.8, 15.8};
   double carrot = 15.8;

   for (int i = 0; i < cake.length; i++){
            drawBar(cake[i], carrot);
   }

}

public static void drawBar(double value, double max ){
    final int MAX_STARS = 20;
    String BAR_REP = "*";

    double correctRatio = (value / max) * MAX_STARS;

    if (correctRatio <= MAX_STARS){
        for (int index = 0; index < correctRatio; index++){
            System.out.print(BAR_REP);
        }
    }
    System.out.println();
}

A: Here is a code that works:
public static void drawBar(double value, double max )
{
    final int MAX_STARS = 20;

    final double ratio = value / max;
    if (Double.compare(ratio, 1.0) > 0)
        return;
    final int nrElements = (int) (ratio * MAX_STARS);
    final char[] array = new char[nrElements];
    Arrays.fill(array, '*');

    System.out.println(new String(array));
}

Note:

*

*MAX_STARS could be a private static final int at the class level;

*it is not checked whether value / max is greater than 1;

*if you want to make comparisons between double values, you should use Double.compare() as shown above; some legal double values are not == to one another, for instance Double.NaN;

*you could even optimize that further by creating a private static final array of 20 stars, using a writer and print a subarray each time.