text:
Q: Postgres - only return results of query if two sub-queries produce results Here is a table called fruits:
id  fruit_name  quantity   date
1 | 'apple'    | 10       | '2019-01-01'
2 | 'peach'    | 15       | '2019-01-02'
3 | 'plum'     | 5        | '2019-01-05'
4 | 'banana'   | 10       | '2019-01-06'
5 | 'orange'   | 20       | '2019-01-06'
6 | 'grape'    | 25       | '2019-01-09'

I'm trying to create a query from two sub-queries. The main query should only return results if both the two sub-queries each returned any results. So if either of the two sub-queries does not have any results, then the query as a whole should return nothing.
The following is a query I've worked on. It sorta gets at what I am trying to create:
WITH r AS (
    SELECT *
    FROM fruits
    WHERE fruit_name = ('pear')
)
SELECT *
FROM r
UNION ALL
SELECT *
FROM fruits
WHERE fruit_name = ('banana')
  AND EXISTS (
    SELECT *
    FROM r
  );

So this query will not return any results, because the first sub-query asks for a 'pear', and there is no 'pear' in the fruits table. This is working as intended.
However, if I swap 'pear' and 'banana' in the query, then it will return one row: the 'banana' row. This is not what I want happen -- in this scenario, I would also want it to return nothing.
So basically, how can I modify this query (or use a better query) so that it only returns results if each of the two sub-queries each have results?
SQL Fiddle: http://www.sqlfiddle.com/#!15/7ecb1/5

A: Use two checks in the where clause:
select *
from fruits
where fruit_name in ('banana', 'pear')
and exists (
    select from fruits
    where fruit_name = 'banana')
and exists (
    select from fruits
    where fruit_name = 'pear');

Note that in Postgres the select list may be empty. You can select a column or a constant
...
and exists (
    select id from fruits
    where fruit_name = 'banana')
...

but this does not affect the result.
Alternatively, you can check whether the results contain rows with both banana and pear:
with results as (
    select *
    from fruits
    where fruit_name in ('banana', 'pear')
)
select *
from results
where (
    select count(distinct fruit_name)
    from results
    ) = 2

A: You can express using a single subquery:
select f.*
from fruits f
where f.fruit_name in ('banana', 'pear') and
      exists (select 1
              from fruits f2
              where f2.fruit_name in ('banana', 'pear') and
                    f2.fruit_name <> f.fruit_name
             );

However, assuming that the name is unique, I would be inclined to do:
select f.*
from (select f.*, count(*) over () as cnt
      from fruits f
      where f.fruit_name in ('banana', 'pear')
     ) f
where cnt = 2;

This logic can easily be adjusted if you do have duplicates, but you sample data does not have any.

A: You could use two sub-queries instead of one
WITH sub1 AS (
    SELECT *
    FROM fruits
    WHERE fruit_name = ('pear')
),
sub2 AS (
    SELECT *
    FROM fruits
    WHERE fruit_name = ('banana')
)
SELECT *
FROM sub1
UNION ALL
SELECT *
FROM sub2
WHERE
EXISTS (
    SELECT *
    FROM sub1
  )
AND EXISTS (
    SELECT *
    FROM sub2
  );


text:
Q: Trying to create a multithreaded program to find the total primes from 0-100000000 Hello I am trying to write a C++ multithreaded program using POSIX thread library to find the number of prime numbers between 1 and 10,000,000 (10 million) and find out how many microseconds it takes...
Creating my threads and running them works completely fine, however I feel as if there is an error found in my Prime function when determining if a number is prime or not...
I keep receiving 78496 as my output, however I desire 664579. Below is my code. Any hints or pointers would be greatly appreciated.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time;

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```

A: This is because, you used 10^6 instead of 10^7.
Also, added some corner cases for numbers 1, 2 and 3:
//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){

      // Corner cases

      if(i<=1)continue;
      if (i <= 3){
            sum_t++;
            continue;
      }

      for (int j=2; j*j <= i; j++)
      {
          if ((i % j == 0) ||  (i %( j+2))==0 )
          {
              break;
          }
          else if (j+1 > sqrt(i)) {
              sum_t++;
          }
       }

  }

    cout << "Thread " << temp_index << " terminates" << endl;
    pthread_exit( (void*) sum_t);
}

I tested your code with correct number and got the correct number of primes as output:
Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 4.69242e+07 microseconds

Thanks to @chux - Reinstate Monica for pointing this out

A: Along with taking 10^7 as the numbers divided in thread instead of setting the limit as 10^6 ,a number of other small scale errors are there and a number of optimizations could be made -

*

*First of all start numbers could be from 2 itself
long start_numbers[4] = {2, 2500001, 5000001, 7500001};

*sum_t++ in your code may not work on edge cases. It is better to follow the following algorithm for calculating Prime function
  bool flag = false;
  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
  flag = false;

  for (long j=2; j*j <= i; j++){
      if (i % j == 0 )
      {
          flag = true;
          break;
      }
   }
   if(!flag)
        sum_t++;
  }

After these 2 operations i am getting the result as
Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 6.62618e+06 microseconds

edit:
( Note : in this case j is taken as long datatype but it could work as well with int in this 'example' since the tested compiler takes int as 32 bits long)

redpajama_set_name: RedPajamaStackExchange


text:
Q: rustc: argument must be a string literal I have test.rs:
const TEST: &'static str = "Test.bin";

fn main() {
    let x = include_bytes!(TEST);
}

rustc test.rs

How to fix this error?
error: argument must be a string literal

 --> test.rs:4:22
  |
4 |     let x = include_bytes!(TEST);
  |                      ^^^^

A: The macro expects a string literal, so it cannot be a variable:
include_bytes!("Test.bin");

Alternatively you could create a macro that will expand into the desired value too:
macro_rules! test_bin {
    // `()` indicates that the macro takes no argument.
    () => {
        "Test.bin"
    };
}

fn main() {
    let x = include_bytes!(test_bin!());
}

Playground


text:
Q: How to import JFrame? package main;

import javax.swing.JFrame;

public class Main extends JPanel{

    public Main() {
        add(new Panel());
        setName("NGame");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

The import javax.swing.JFrame; line isn't recognized as a class by eclipse and will not import. The two set methods are not recognised as the JFrame will not import. I have the latest JDK and have checked that the JFrame class is existant with the shift + ctrl + T command. What is happening?

A: You need to make Main extend JFrame, not JPanel. Try something like this:
package main;

import javax.swing.*;

public class Main extends JFrame {

    public Main() {
       add(new JPanel());
       //...other code
    }

}

A: Several things...

*

*You are extending from JPanel, but not importing it.

*You are importing JFrame, but not actually using it.

*setDefaultCloseOperation is not a valid method for JPanel

*EXIT_ON_CLOSE is an unknown variable as it's not declared  within JPanel or any of it's parent classes...

*You are mixing heavy and light weight components (Panel is a heavy weight component and JPanel is a light weight component, these components tend not to mix well)

Instead, try extending from JFrame instead...
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

    public Main() {
        add(new JPanel());
        setName("NGame");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

Now, having said that.  It's generally not necessary to extend from JFrame as you rarely add any new functionality to it.
Instead, you should create an instance of JFrame and add your components to it, for example...
package main;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Panel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new MainPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MainPane extends JPanel {
        public MainPane() {
            add(new Panel());
            setName("NGame");
        }
    }

}

A: Right click on src, then build path, libraries, and remove the JRE System Library, add libraries and add it again. This helped it for me at least =)

A: That's because JPanel doesn't have those methods. setName doesn't even exists. exists, but I don't think it's what you meant to do.
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

    public Main() {
        //instead of setName()
        setTitle("NGame");
        add(new Panel());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //setVisible(true);
        //pack();
        //etc etc
    }
}


text:
Q: Using SQLAlchemy connection pool with different deployment environment I have been reading the SQLAlchemy documentation on connection pooling, while the topic is by itself simple; I think it has lots to do with how you deploy your application (I'm talking about a WSGI application here).
Lately I'm starting to use Gunicorn. It has several workers types.  Currently I'm using only synchronous workers: those that "that handles a single request at a time".
So in this scenario, would be best to use a StaticPool, i.e a single reutilizable connection per worker? Or does SQLAlchemy could attempt to make several connections even in the case of an synchronous worker? - assuming that the application itself does not use threads.

A: There's every reason just to stick with the default of QueuePool:

*

*QueuePool only opens as many connections as it's asked to at at time.  If your app uses only one connection at a time, that's the only connection your app will open.

*SQLAlchemy itself never opens additional connections beyond what you tell it to (anything that requires database access is basically going to use a single connection to access the DB.  like create_all(), or Session.query().whatever.  It only uses one connection at a time.).

*if your app does happen to have some kind of thing that incurs more than one connection at a time, such as, using two Session objects at once, or perhaps calling engine.execute() when you are still fetching the results from another engine.execute(), QueuePool will set up that second connection without any issue.  Whereas StaticPool will use the same connection and then you'll get issues.

*If you really want to make sure your app is using one and only one connection per process, you can look into AssertionPool - this is more of a debugging/test pool though, not necessarily one that we've used at scale.  Or set up QueuePool with pool_size=1 and max_overflow=0, which would basically lead to a deadlock if you try to open two connections at the same time in one thread....


text:
Q: How to fix BackgroundWorker1 not doing his work? So I have a problem with VB.NET, and specifically the BackgroundWorker1.
I have a function named SystemLoad().
When you click a button, it does BackgroundWorker1.RunWorkerAsync(). No problem here, but the problem is on the DoWork function.
Inside the DoWork function, I write SystemLoad() to call the  following function. But, it doesn't work. It does absolutely nothing.
Is there a solution to this? I already tried doing Dim T As New Thread(AddressOf SystemLoad): T.Start() but it does the same thing, nothing.
Private Sub SystemLoad()
    Try
        'Log(Prefix & " Resolving target...")
        Main.TextBox2.Invoke(Sub() Main.TextBox2.AppendText(Prefix & " Resolving target..."))

        Using req As New HttpRequest
            req.IgnoreProtocolErrors = True
            req.Cookies = New CookieStorage(False)
            req.UserAgent = Http.RandomUserAgent

            If Main.ComboBox1.SelectedIndex = 0 Then
                Dim P As String = Main.Proxies(New Random().Next(Main.ProxiesCount)).ToString
                req.Proxy = New HttpProxyClient(P.Split(":")(0), P.Split(":")(1))

                'Log(Prefix & " Using proxy " & P)
                Main.TextBox2.Invoke(Sub() Main.TextBox2.AppendText(Prefix & " Using proxy " & P))
            ElseIf Main.ComboBox1.SelectedIndex = 1 Then
                Dim P As String = Main.Proxies(New Random().Next(Main.ProxiesCount)).ToString
                req.Proxy = New Socks4ProxyClient(P.Split(":")(0), P.Split(":")(1))

                'Log(Prefix & " Using proxy " & P)
                Main.TextBox2.Invoke(Sub() Main.TextBox2.AppendText(Prefix & " Using proxy " & P))
            ElseIf Main.ComboBox1.SelectedIndex = 2 Then
                Dim P As String = Main.Proxies(New Random().Next(Main.ProxiesCount)).ToString
                req.Proxy = New Socks5ProxyClient(P.Split(":")(0), P.Split(":")(1))

                'Log(Prefix & " Using proxy " & P)
                Main.TextBox2.Invoke(Sub() Main.TextBox2.AppendText(Prefix & " Using proxy " & P))
            End If

            req.ConnectTimeout = Convert.ToInt32(Link.Split("|")(2))
            req.KeepAliveTimeout = Convert.ToInt32(Link.Split("|")(2))
            req.ReadWriteTimeout = Convert.ToInt32(Link.Split("|")(2))

            Dim Respo As String = req.Post(Link.Split("|")(1)).ToString
            ResolveTarget(Respo)
        End Using

        RefreshTimer.Start()
    Catch ex As Exception
        Main.TextBox2.Invoke(Sub() Main.TextBox2.AppendText(Prefix & " ERROR " & ex.Message))
    End Try
End Sub

Here is how I declare the BackgroundWorker1 :
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    BackgroundWorker1.RunWorkerAsync()
End Sub

'SystemLoad() function

Private Sub BackgroundWorker1_DoWork(sender As Object, e As
System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    BeginInvoke(New Action(AddressOf SystemLoad), Nothing)
End Sub

EDIT : I found this code, but the program GUI is crashing ...
I put this code in the BackgroundWorker1_DoWork function, not directly in the Form_Load function but it still crashes.
BeginInvoke(New Action(AddressOf SystemLoad), Nothing)

A: The following subset of your code works.
Imports System.ComponentModel

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub SystemLoad()
        Try
            Debug.WriteLine(" Resolving target...")
            ' Here is how to append to TextBox2 from backgrouond thread.
            TextBox2.Invoke(Sub() TextBox2.AppendText("...message..."))
            '...
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try
    End Sub

    Dim WithEvents BackgroundWorker1 As New BackgroundWorker

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        SystemLoad()
    End Sub

End Class

If you do not get any logging, then the Log() function must be failing. Where is the Log() function writing to? Is it writing to a control of the Form? A Form or any of its controls cannot be updated from a background thread. See How do I update the GUI from another thread?.


text:
Q: ¿Es posible enviar un icono de Fontawesome a un componente? Básicamente lo que estoy intentando hacer es tener un solo componente que me arme varios items. Los items consisten solamente en un titulo, una descripcion, y el ícono. los primeros dos los envio sin problemas, pero ya el segundo no se me ocurre como mandarlo, ya que si lo envio como como los otros dos, no se muestra por pantalla.
ejemplo:
éste son los items que quiero mostrar:
<IndexComponent titulo='Asistencia Profesional' texto = 'Contamos con un equipo de pre-venta especializado y un departamento de ingeniería para los proyectos más complejos' icono = 'faPeopleGroup'/>
<IndexComponent titulo='Training y seguimiento' texto = 'Capacitaciones para canales e integradores, acerca de instalación y puesta en marcha de nuestros productos, acompañándolos en el proceso de postventa.' icono = 'faPeopleGroup'/>
<IndexComponent titulo='Crédito y Financiación' texto = 'Ofrecemos financiación estándar y especial tanto para el área de distribución, como también para cualquier tipo de proyecto.' icono = 'faPeopleGroup'/>
<IndexComponent titulo='Centro de distribución' texto = 'Contamos con un depósito en el cual nuestro equipo se encarga de realizar la logística en tiempo y forma acompañando el dinamismo del negocio' icono = 'faPeopleGroup'/>

Y asi lo recibo en el componente:
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPeopleGroup } from '@fortawesome/free-solid-svg-icons';

const IndexComponent = (props) => {
    const titulo = props.titulo;
    const texto = props.texto;
    const icono = props.icono;

    return (
        <>

{titulo}

{texto}

                <FontAwesomeIcon icon={icono} color="#003a82"/>

        </>
    );
}

El problema es que aunque importe el icono o FontAwesome, no logro mostrarlo

Es posible ésto que planteo? Enviar un icono desde un componente a otro?

A: Puedes hacerlo siguiendo las indicaciones de la documentación de la siguiente manera:
import { solid, regular, brands, icon } from '@fortawesome/fontawesome-svg-core/import.macro'

Importas los macros y a continuación:
<IndexComponent titulo='...' texto = '...' icono={solid('faPeopleGroup')} />

Y ahora si podrías usar el icono:
<FontAwesomeIcon icon={icono} color="#003a82"/>


text:
Q: Is there an English variant of "Zeitgeist" other than "spirit of the times"? Is there a cut-and-dry English word that means the same, or roughly the same, as the German word "Zeitgeist," other than its literal meaning of "spirit of the times"?
I've grown sour on its presence in conversational English due to heavy use as a clever buzzword and would like to know if there is a simpler alternative.

A: The thesaurus answer gives some terms, but what's more interesting to me is the antonym old-fashioned. Based on that, I'd go with antonyms of old-fashioned which bring up such terms as contemporary, fresh, and in vogue. All of those terms, and especially the synonyms to in vogue work well.
In somewhat of a self-referential point of view, the use of the zeitgeist is pretty much in vogue today as the latest thing to discuss and, to turn a phrase, "word drop". At least, that's what my new friends who are all into Zeitgeist like to say.

A: Among the suggested  synonyms I think two of them may come close to the notion of 'spirit of time':
atmosphere:

*

*A dominant intellectual or emotional environment or attitude: the atmosphere  of the 50s.

feeling:

*

*an impression or mood; atmosphere: the feeling of a foreign city.


text:
Q: how to trim request param values before validating them with spring mvc? I have code like this:
data class LoginParams(
        @field:NotNull
        @field:Email
        @field:Size(min = 1, max = 100)
        val email: String?,
        @field:NotNull
        @field:Size(min = 4, max = 100)
        val pass: String?
)

@PostMapping("/login")
fun login(@Valid params: LoginParams){
   //...
}

I want the email field to be trim()'ed before doing the @Size validation on it. how do I achieve so?

A: There is no option to perform trim with bean validation though instead of @field:Size you can use Pattern to allow spaces around the data as:
@field:Pattern(regexp="^\s*[\S]{1,100}\s*$")

*

*^\s*: start matching 0 or more spaces

*[\S]{1,100}: match 1-100 non-space characters

*\s*$: match 0 or more spaces at the end of the match

or Optionally, custom validator can be created to implement custom validation login with
// in your custom annotation interface file
@Constraint(validatedBy = CustomTrimSizeValidator.class)


text:
Q: How should we prevent XSS attacks that *only* break page rendering? Suppose we have a form that allows entering a piece of markdown as a message body. That text is then render in HTML as JSON on another page:
<html>
   <body>
       <script type="text/javascript">
       loadMessage({
           name: 'John Doe',
           message: '**Hello** World'
       });
       </script>
   </body>
</html>

Pretend that loadMessage uses a markdown parser (e.g. marked) and outputs the HTML at runtime.
I've identified a case where a malicious user could cause an error on the page:
<html>
   <body>
       <script type="text/javascript">
       loadMessage({
           name: 'John Doe',
           message: '</script>'
       });
       </script>
   </body>
</html>

Because </script> causes the browser to close the script block, an Unexpected token ILLEGAL exception is thrown. Marked is able to sanitize such an attack, but this attack is even before JavaScript execution.

*

*Strip all <script> and </script> when the initial form is submitted. This would mean updating a lot of our framework code (using ASP.NET MVC - so we'd have to extend the default ModelBinder).

*Leverage the JSON formatter for this - convert to '</' + 'script>' when writing the JSON. We'd be keeping the source intact - but maybe that's a bad thing.

How should we mitigate such an attack?

A: I might personally go along with stripping anything resembling the script tag, as such an approach would provide an extra layer of security against validation bugs in your Markdown parser. But your mileage may vary depending on your application.
If you do need to encode, see https://stackoverflow.com/a/236106/131903 for a reasonable encoding approach (that is, use \x3c to replace the less-than sign). This will work:
<html>
  <script>
    alert("1 \x3c/script> 2");
  </script>
</html>


text:
Q: spring data jpa specification join fetch is not working I am trying to use Spring Data JPA Specificaiton to query data, but I got some problem here.
The Java code is as below:
    List<NoticeEntity> studentNoticeEntityList = noticeRepository
            .findAll((root, criteriaQuery, criteriaBuilder) -> {
                criteriaQuery.distinct(true);

                root.fetch(NoticeEntity_.contentEntitySet, JoinType.LEFT);

                Predicate restrictions = criteriaBuilder.conjunction();

                SetJoin<NoticeEntity, UserNoticeEntity> recipientNoticeJoin = root
                        .join(NoticeEntity_.recipientNoticeEntitySet, JoinType.INNER);
                recipientNoticeJoin.on(criteriaBuilder.equal(
                        recipientNoticeJoin.get(UserNoticeEntity_.recipientStatus), NoticeRecipientStatus.Unread));
                Join<UserNoticeEntity, WeChatUserEntity> recipientUserJoin = recipientNoticeJoin
                        .join(UserNoticeEntity_.user);

                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(recipientUserJoin.get(WeChatUserEntity_.id), id));
                // recipientNoticeJoin.fetch(UserNoticeEntity_.user, JoinType.INNER);

                return restrictions;
            });

When I comment the code "recipientNoticeJoin.fetch(UserNoticeEntity_.user, JoinType.INNER);", it is working fine, but when I un-comment this, I will get error:
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

So, I am wondering if join fetch is supported by using Specification way, or there is something wrong with my code.
I know there is another way by using @Query("some hql"), but somehow I just prefer to use the Specification way.
Thanks a lot.

A: The error specifies that you're missing an entity from your select list. Try this:
criteriaQuery.multiselect(root, root.get(NoticeEntity_.recipientNoticeEntitySet);

Also, hibernate may run a count query first to determine the number of results, and this can cause the above error. You can avoid this breaking by checking the return type of the query before adding the fetch.
Eager fetching in a Spring Specification


text:
Q: Issues Reading a CSV file into a C Struct I've just started learning C, and I'm currently trying to create a program to automate a fishing minigame I made for my D&D campaign. In order to do so, I created a CSV containing all the tables I had originally written up. I've been trying a variety of things for about a week now to just simply read the CSV into C so that I can call specific elements at will. I've finally gotten something to very nearly work, but I'm getting a strange problem. Firstly, the CSV is formatted as such:
bluefish,str,2,5
bluefish,str,2,5
bluefish,str,2,5
bluefish,str,2,5
kahawai,dex,2,1000
narrow barred mackerel,str,3,5

It goes on for another 400 lines, but you get the point. My current code looks like the following:
typedef struct{
    char name[50];
    char contest[5];
    int modifier;
    int value;
} fts_t;

    /*Checking for the file and opening it*/
    FILE *tpointer;

    tpointer = fopen("fishing_tables.csv", "r");
    printf("Accessing Fishing Tables...\n");

    if(tpointer == NULL){

        printf("Error: Missing fishing_tables.csv");
        return 0;

    } else{

        printf("Success! Importing Data...\n");

    }

    /*Creating a struct array and initializing variables*/
    fts_t ft[400];
    char buffer[1024];
    int count = 0;
    char name[100];
    char contest[3];
    int modifier;
    int value;

    while(fgets(buffer, 1024, tpointer)){
        sscanf(buffer, " %[^,],%[^,],%d,%d", name, contest, &modifier, &value);
        strcpy(ft[count].name, name);
        strcpy(ft[count].contest, contest);
        ft[count].modifier = modifier;
        ft[count].value = value;
        printf("%s\t%s\t%d\t%d\n", ft[count].name, ft[count].contest, ft[count].modifier, ft[count].value);
        count++;
    }

So, following above, I'm having it print out the elements of the struct at each count as it loops, just to check that it's creating the struct correctly. The problem comes in that the output looks like this:
        dex     2       15

        dex     2       15

        dex     2       15

        dex     2       15

        dex     2       15

next    0       0       0

next    0       0       0

next    0       0       0

next    0       0       0

next    0       0       0

Now, hilariously, the rows beginning with "next" are the only rows printing correctly. I have these added in for some extra shenanigans in the context of the minigame, but what's important is that those are correct. However, in every other row, the name variable is not being read, and I'm really lost as to why, when the "next" rows are functioning fine. I've checked the actual variable itself, and it appears there's some sort of problem in my sscanf statement.
Any help is appreciated.


text:
Q: Incorrect Timestamp conversion in Spark I am trying to convert a string (UTC time) to timestamp.
List<String> list = new ArrayList<String>();
    list.add("2018-03-11 02:00:00");
    list.add("2018-03-11 03:00:00");
sparkSession.createDataset(list, Encoders.STRING()).select(to_timestamp(col("value").cast(DataTypes.TimestampType), "yyyy-MM-dd HH:mm:ss")).show();

The output for this is
+-------------------+
|              value|
+-------------------+
|2018-03-11 03:00:00|
|2018-03-11 03:00:00|
+-------------------+

I can see that its applying the DST (CST), which should not be applied in my case as I am dealing with UTC string.
Any ideas?

A: You are using date time string without timezone component. When you convert string to timestamp and displaying. I guess it is showing in local timezone.


text:
Q: MongoDB: Count by unique value after aggregate by group I have to get count unique values by group.
Here is the example data:
[
   {
     iphone: iphone6,
     name: Tom
   },
   {
     iphone:iphone7,
     name: Tom
   },
   {
     iphone:iphone6,
     name: Joe
   },
   {
     iphone:iphoneX,
     name: Joe
   }
]

I want to group by showing like:
[
   {
     _id:iphone6,
     people:[Tom,Joe]
   },
   {
     _id:iphone7,
     people:[Tom]
   },
   {
     _id:iphoneX,
     people:[Joe]
   }
]

I have a problem with using $group. How can I do this?

A: *

*$group: Group by iphone and $push name to people array field.

*$sort (Optional): Sort by _id ascending.

db.collection.aggregate([
  {
    $group: {
      _id: "$iphone",
      people: {
        $push: "$name"
      }
    }
  },
  {
    $sort: {
      _id: 1
    }
  }
])

Sample Mongo Playground


text:
Q: create interpolated polygons from GPS data with value column I have some GPS data with a value assigned to each point (think like air quality). I can plot those points, with folium for instance, and map the value to the size of a circle, like this:
import pandas, numpy, folium
lat = numpy.random.uniform(45, 45.01, 250)
lon = numpy.random.uniform(3, 3.02, 250)
value = numpy.random.uniform(0,50,250)
df = pandas.DataFrame({'lat': lat, 'lon': lon, 'value': value})
mymap = folium.Map(location = [lat.mean(), lon.mean()], tiles="OpenStreetMap", zoom_start=14)
for elt in list(zip(df.lat, df.lon, df.value)):
    folium.Circle(elt[:2], color="blue", radius=elt[2]).add_to(mymap)
mymap.save('mymap.html')

And I would like to treat this data, interpolate it and create a shapefile as the output, with interpolated polygons containing the average value and showing areas of high and low value (fake picture on the right). The limit of the polygons would auto-generated, of course, from the interpolation.
How can I achieve this? Because i have tried using HeatMap tool in folium, but it is designed to interpolate the density of points, not the value associated with each point!
I hope it's not too complex..Thanks,
note: I use folium but i'm ok with other python libraries.

A: We can feed the values to HeatMap in folium as weights (see the data parameter in documentation).
Here's an example. I've divided values in the bottom half of the box by 5 to demonstrate that despite the relatively uniform density of data points, the heat map clearly shows higher magnitudes in the upper half of the picture:
import pandas as pd
import numpy as np
import folium
from folium.plugins import HeatMap
import matplotlib as mpl

# parameters
n = 250                     # number of points
lat0 = 40.7                 # coordinates will be generated uniformly with
lon0 = -73.9                # lat0 - eps <= lat < lat0 + eps
eps = 0.1                   # lon0 - eps <= lon < lon0 + eps
v_min, v_max = 0, 100       # min, max values

# generating values
lat = np.random.uniform(lat0 - eps, lat0 + eps, n)
lon = np.random.uniform(lon0 - eps, lon0 + eps, n)
value = numpy.random.uniform(v_min, v_max, n)
df = pandas.DataFrame({'lat': lat, 'lon': lon, 'value': value})

# to demonstrate the effect of weights on the heatmap,
# we'll divide values below the center of the box by K = 5
K = 5
df.loc[df['lat'] < lat0, 'value'] /= K

# plotting the map, both the points themselves and the heatmap
m = folium.Map(location = [lat0, lon0], tiles="OpenStreetMap",
               zoom_start=11, width=400, height=400)
for elt in list(zip(df.lat, df.lon, df.value)):
    folium.Circle(elt[:2], color="white", radius=elt[2]).add_to(m)

# df.values used here is a (250, 3) numpy.ndarray
# with (lat, lon, weight) for each data point
HeatMap(data=df.values, min_opacity=0.1).add_to(m)

m

Output:

Update:
Here's a slightly different approach, not using the built-in HeatMaps (which is probably currently a better option in light of https://github.com/python-visualization/folium/issues/1271, as mentioned by @agenis).
We first transform our data, making the grid of squares, where value for each square is the average of original data point values lying within that cell (so it does not depend on the number of points within that cell, only their values).
Then we can visualise those squares by plotting GeoJson polygons on the map. Here's an example:
# define the size of the square
step = 0.02

# calculate values for the grid
x = df.copy()
x['lat'] = np.floor(x['lat'] / step) * step
x['lon'] = np.floor(x['lon'] / step) * step
x = x.groupby(['lat', 'lon'])['value'].mean()
x /= x.max()
x = x.reset_index()

# geo_json returns a single square
def geo_json(lat, lon, value, step):
    cmap = mpl.cm.RdBu
    return {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
            'color': 'white',
            'weight': 1,
            'fillColor': mpl.colors.to_hex(cmap(value)),
            'fillOpacity': 0.5,
          },
          "geometry": {
            "type": "Polygon",
            "coordinates": [[
                [lon, lat],
                [lon, lat + step],
                [lon + step, lat + step],
                [lon + step, lat],
                [lon, lat],
              ]]}}]}

# generating a map...
m = folium.Map(location=[lat0, lon0], zoom_start=11, width=400, height=400)

# ...with squares...
for _, xi in x.iterrows():
    folium.GeoJson(geo_json(xi['lat'], xi['lon'], xi['value'], step),
                   lambda x: x['properties']).add_to(m)

# ...and the original points
for elt in list(zip(df.lat, df.lon, df.value)):
    folium.Circle(elt[:2], color="white", radius=elt[2]).add_to(m)

m

Output:

Update (2):
Here's a version with interpolation on the grid using griddata:
import pandas as pd
import numpy as np
import folium
from scipy.interpolate import griddata

# parameters
n = 250                     # number of points
lat0 = 40.7
lon0 = -73.9
eps = 0.1
v_min, v_max = 0, 100       # min, max values

# generating values
lat = np.random.normal(lat0, eps, n)
lon = np.random.normal(lon0, eps, n)
value = numpy.random.uniform(v_min, v_max, n)

# set up the grid
step = 0.02
xi, yi = np.meshgrid(
    np.arange(lat.min() - step/2, lat.max() + step/2, step),
    np.arange(lon.min() - step/2, lon.max() + step/2, step),
)

# interpolate and normalize values
zi = griddata((lat, lon), value, (xi, yi), method='linear')
zi /= np.nanmax(zi)
g = np.stack([
    xi.flatten(),
    yi.flatten(),
    zi.flatten(),
], axis=1)

# geo_json returns a single square
def geo_json(lat, lon, value, step):
    cmap = mpl.cm.RdBu
    return {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
            'color': 'white',
            'weight': 1,
            'fillColor': mpl.colors.to_hex(cmap(value)),
            'fillOpacity': 0.5,
          },
          "geometry": {
            "type": "Polygon",
            "coordinates": [[
                [lon - step/2, lat - step/2],
                [lon - step/2, lat + step/2],
                [lon + step/2, lat + step/2],
                [lon + step/2, lat - step/2],
                [lon - step/2, lat - step/2],
              ]]}}]}

# generating a map...
m = folium.Map(location=[lat0, lon0], zoom_start=9, width=400, height=400)

# ...with squares...
for gi in g:
    if ~np.isnan(gi[2]):
        folium.GeoJson(geo_json(gi[0], gi[1], gi[2], step),
                       lambda x: x['properties']).add_to(m)

# ...and the original points
for elt in list(zip(lat, lon, value)):
    folium.Circle(elt[:2], color='white', radius=elt[2]).add_to(m)

m

Output:

A: I appears to me that you need to filter your data so you split it into groups according to given categories.  With those sets of points, you should then be able to generate convex hulls.  It appears there are methods to do this in scipy - see here for some examples:
Convex hull area in Python?


text:
Q: Select manual em repositório usando Spring? Olá, gostaria de saber se existe uma forma de fazer um select dentro do Repository, estou usando Spring e REST, preciso retornar todas as entidades que possuem outra entidade, pegaria elas pelo id, e preciso alimentar uma chamada ajax com ela, então precisaria de um array json. Se alguém puder ajudar, ficaria muito grato.

A: Encontrei a solução, crio métodos com nomes específicos, como esse:
List<Answer> findByQuestionIdAndDeadIsFalse(String questionId);

Criei dentro do Repository e chamo ele, fazendo uma injeção de dependência no lugar em que preciso, no meu caso no Controller.


text:
Q: How to Convert DataReader Result to Entity? ->use Emit Now I want   to  Convert a DataReader to an Entity . I have a method like this:
 private static void ReadInt32(ILGenerator il, LocalBuilder item,
                List<DbColumnInfo> columnInfoes, LocalBuilder[] colIndices, int i)
            {
               il.Emit(OpCodes.Ldloc_S, item);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldloc_S, colIndices[i]);

                il.Emit(OpCodes.Callvirt, DataRecord_GetInt32);
                il.Emit(OpCodes.Callvirt, columnInfoes[i].SetMethod);

}

and call the method like here,
 if (IsCompatibleType(columnInfoes[i].Type, typeof(int)))
                    {
                        // item.%Property% = arg.GetInt32(%index%);
                        ReadInt32(il, item, columnInfoes, colIndices, i);
                    }

unfortunately, there will come up an Exception if the Data Filed in DB is NULL. As int type can't be NULL value but I made it transfer to int?. then turns out that my calling method works well.
but here I want an extension that is while Data Filed in DB is NULL, we can use Custom attribute to indicate a default value. So I re-defined ReadInt32 as following, But to my surprise, there always comming up JIT inner Exception. I'm not familiar with IL, I really looking forward some help for you all, really appreciate.
change the code's as following,but still exist error,the exception type is :
System.EntryPointNotFoundException:
 var local = il.DeclareLocal(columnInfoes[i].Type);//int i
            Label intNull = il.DefineLabel();//int intNull;
            Label intCommon = il.DefineLabel();

            il.Emit(OpCodes.Ldloca, local);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldloc_S, colIndices[i]);
            il.Emit(OpCodes.Callvirt, DataRecord_IsDBNull);// int i=isdbnull?
            il.Emit(OpCodes.Brtrue_S, intNull);// int i=isdbnull?intNull

            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ldloc_S, colIndices[i]);//int i=isdbnull?1000:getInt(32)

            il.Emit(OpCodes.Callvirt, DataRecord_GetInt32);//int i=isdbnull?1000:getInt32(i);
            il.Emit(OpCodes.Br_S, intCommon);

            il.MarkLabel(intNull);;
            il.Emit(OpCodes.Ldc_I4, 123);//intNull=DefaultValue  columnInfoes[i].DefaultValue
            il.MarkLabel(intCommon);
            il.Emit(OpCodes.Stloc_S, item);
            //il.Emit(OpCodes.Ldloc_S, item);
            il.Emit(OpCodes.Ldloc, local);
            il.Emit(OpCodes.Callvirt, columnInfoes[i].SetMethod);

A: Just use Dapper. If it's good for SO, it will be good for you, too ;-)


text:
Q: How to merge google chrome user of home and work I have the following configuration:

*

*Google chrome at home

*Google chrome at work

I need to have the two chromes merged in one account, using differents users.
I want to be able to Sync my google account in others computers, and have the two users, work and home.
Anyone have some idea of what's the best way to achieve this?
Thanks!

A: According to Google, it's currently not possible to merge two different accounts. It's possible, however, to move data out of certain products, namely:

*

*AdWords

*Blogger

*Bookmarks (Export and import)

*Contacts (Export and import)

*FeedBurner

*Finance: Export and Import

*iGoogle (To transfer data, create your own backup and restore it to
the new account through XML)

*Picasa Web Albums

*Places (bulk upload)

*Reader

*YouTube

Unfortunately, Chrome isn't currently on the list of the supported products. More information about merging accounts here.
However, there's another way to achieve this, albeit using a third-party extension. Xmarks allows you to sync your bookmarks to all of your devices that have Xmarks installed. It also allows you to set up Profiles, which gives you the ability to separate bookmarks according to your needs.
Assign bookmarks to sync profiles

Assign sync profiles to computers

This page walks you through the process of setting this up.


text:
Q: Webkit download pre-built database I have a rather large db (as in many records). I'd rather let the client download a pre-built db instead of forcing them to load a bunch of text, then insert all the records before being able to use the db.
The closest thing to a spec I can find is this:
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/UsingtheJavascriptDatabase/UsingtheJavascriptDatabase.html
It doesn't mention anything about being able to download a database, but I thought someone on SO might have a solution.

A: Just make up the DB on the simulator or via some GUI... Then make the DB available on the web via a link to the DB file on your webserver. Then in the app check a flag that you make up to see if it has downloaded the DB yet, if it hasn't then just download the DB just like any other file over HTTP and store it in your documents directory. Then set your flag so you know you have downloaded the DB and that the app doesn't need to do this again. Then when you need to access the DB just point sqlite to the DB file you placed in the Documents directory.


text:
Q: Maximum load resistor for a given single transistor circuit
Following parameters are given for the above circuit:
R1=8.2 kΩ, R2=5.6kΩ, RE=2.7kΩ, VEB=Uj=0.7V, Vcc=10V, β=200
The question asks the maximum load resistance RL for the transistor in active mode.
I solve the question in the following way:

The maximum load resistance RL for the transistor in active mode means to me the transistor is approaching to saturation at that point.
So for that point, I take Vce=0 and set Vy=Vx+0.7V.
Since Vx=Vcc*R2/(R1+R2)
Vy=Vcc*R2/(R1+R2) + 0.7V
Vy=10*(5.6/13.8) + 0.7V = 4.76V
Now since Vce=0V, and Ie=(Vcc-Vy)/Re = 1.94mA
Ic = Ie approximately so
RL = Vy/Ic = 4.76V/1.94mA = 2.45kΩ
So I calculate the maximum RL in active region as 2.45kΩ, whereas the answer is 2.1kΩ.
Is my calculation wrong?

A: The following two schematics are equivalent:

simulate this circuit – Schematic created using CircuitLab
Where \$V_{TH}=V_{CC}\frac{R_2}{R_1+R_2}\$ and \$R_{TH}=\frac{R_1\cdot R_2}{R_1+R_2}\$.
From the above, and assuming \$I_B^{'}=\mid I_B\mid\$ and \$V_{BE}^{'}=\mid V_{BE}\mid\$, you can compute:
$$\begin{align*}
V_{TH}+ I_B^{'}\cdot R_{TH}+ V_{BE}^{'} + I_B^{'}\cdot\left(\beta+1\right)\cdot R_E&=V_{CC}\\\\
\therefore\quad
I_B^{'}=\frac{V_{CC}-V_{TH}-V_{BE}^{'}}{R_{TH}+\left(\beta+1\right)\cdot R_E}
\end{align*}$$
Given your values, I get \$I_B^{'}\approx 9.6\:\mu\textrm{A}\$.
The start of shallow entry into saturation occurs right when \$V_{BC}=0\:\textrm{V}\$ or when \$V_B=V_C\$:
$$\begin{align*}
V_C&=V_B\\\\
I_C\cdot R_L &= V_{TH}+I_B^{'}\cdot R_{TH}\\\\
\beta\: I_B^{'}\cdot R_L &=V_{TH}+I_B^{'}\cdot R_{TH}\\\\
\therefore \quad R_L &=\frac{V_{TH}+I_B^{'}\cdot R_{TH}}{\beta\: I_B^{'}}=\frac{1}{\beta}\left(R_{TH}+\frac{V_{TH}}{I_B^{'}}\right)
\end{align*}$$
From which I get \$R_L\approx 2130\:\Omega\$.

A: Maximum gain for CE stage is VDD/0.026; the current is irrelevant (within reason).
Consider a 26 volt battery. You can operate at 1mA (thus 24Kohm allows 2 volts across the Vce, so bipolar is just barely out of saturation), or 10mA  or 100mA,
or 1uA (with 24,000,000 Ohm Rcollector)


text:
Q: SOAP Web Service Response different on SOAPUI and C#.NET I am using IBM Integration Bus for my middle ware, as I have developed an integration service (SOAP Web Service) on it which is successfulllu integrated with database and using ESQL Compute Node in message flow I have called database function which return data;
SET OutputRoot.XMLNSC.ns:SD_GetAccountAvailableLimitResponse.SD_GetAccountAvailableLimitResponse =
        PASSTHRU('SELECT * FROM SampleDB.DBO.FUNC_GET_Data(''haxan'',''11335544'')');

This returned correct and full data contain multiple records.
Now the second part which has the issue/problem. I am calling this SOAP Web Service in C#.NET application and add this as a Web Reference. As my C# Code is
IS_ServiceHttpService httpRequest = new IS_ServiceHttpService();
        SD_GetAccountAvailableLimit obj = new SD_GetAccountAvailableLimit();
        obj.sAccountNumber = "11335544";
        obj.sChannelID = "20";
        obj.sSambaDigital_Username = "haxan";
        obj.sUserID = "tcib";
        obj.sPassword = "TcibSamba";
        obj.sChannelID = "20";
SD_GetAccountAvailableLimitResponse response = httpRequest.SD_GetAccountAvailableLimit(obj);

Here is the problem in Response !, when I test this Serive on SOAPUI it will return more than one records according to database query inside function but when I call this in C# as above; the response contain only first record (Very first row). I am badly confused why this is happening, please help me out in this. Thanks


text:
Q: Hive: no result display After I run:
hive> select * from bxdataset where  yearofpublication = "2002";

The result is :
MapReduce Jobs Launched:
Job 0: Map: 1
HDFS Read: 9491 HDFS Write: 0 SUCCESS

Total MapReduce CPU Time Spent: 0 msec

OK

Time taken: 9.651 seconds

So there is no any result display. But I'm pretty sure that there exits at least one row which yearofpublication is 2002. And the data type is STRING.

A: You can validate your yearofpublication data by running simple query.
select yearofpublication from bxdataset limit 10

If you see your data in output ,then you can try something like below
select * from bxdataset where  yearofpublication like "%2002%";


text:
Q: Error passing vector argument to function argument I am getting an error "not enough input arguments" when calling a function that was passed as an argument using two other arguments.
>>q = [.33 .423 .523 1.023 .6 1.047]';
>>NewtRaphDynamics(q,0,PA1_PHI,PA1_Jacobian)
Error using PA1_PHI (line 8)
Not enough input arguments.

where PA1_PHI and PA1_Jacobian are function files in the matlab directory. The function NewtRaphDynamics is thus:
function [qout D] = NewtRaphDynamics(iq,t,PHI,Jac,err,it)
%... code setting defaults for 'err' and 'it' if they are not specified ...
norm = @(what) sqrt(what'*what);

iter = 0;
iq
pause

% Solving for position problem q
while iter < it
    iPHI = PHI(iq,t);
    D = Jac(iq);
    if(norm(iPHI) < err), break, end
    deliq = - D\iPHI;
    iq = iq + deliq;
    iter = iter + 1;
end

qout = [t iq'];

the function call throwing the error is:
function PHI = PA1_PHI(q,t)

PHI = zeros(6,1);

PHI(1) = q(1) - .5*cos(q(3)) + .2*sin(q(3));
PHI(2) = q(2) - .5*sin(q(3)) - .2*cos(q(3));
PHI(3) = q(4) - .4*cos(q(6)) - (q(1) + .7*cos(q(3)) + .1*sin(q(3)));
PHI(4) = q(5) - .4*sin(q(6)) - (q(2) + .7*sin(q(3)) - .1*cos(q(3)));
PHI(5) = q(4) + .4*cos(q(6)) - 1.6;
PHI(6) = q(5) + .4*sin(q(6)) - (1 - .2*cos(2*pi*t)); % appended constraint


text:
Q: formatted paste two text files adding a given number of empty lines in one of them via bash/sed/awk I have two text files A.txt (length N) and B.txt (lenght N*n, where n is the block lenght) with the following structure
A.txt:
Line 1
Line 2
Line 3
...
Line N

B.txt:
Block1 (line 1)
Block1 (line 2)
Block1 (line 3)
...
Block1 (line n)
Block2
...
...
BlockN

I would like to merge the two files respecting some format and in a way that each i-th line from A.txt would go before the corresponding i-th block in B.txt:
Line1 #from A.txt
Block1 (line 1) #from B.txt
Block1 (line 2)
Block1 (line 3)
...
Block1 (line n)
Line2 #from A.txt
Block2 #from B.txt
...
...
LineN #from A.txt
BlockN #from B.txt

In bash, the best would be to add (n-1) empty lines to A.txt and then use paste command, followed by awk to manage the formatted printing of all lines.
However, I face two difficulties:

*

*define (with a bash loop) a string made of (n-1) empty lines

*pass the string variable to awk to printf it

This is a possible example (N=2, n=3):
A.txt:
10  2.3
20  0.653

B.txt:
A x 2.5 3 6.1
B x 1.0 2.5 4
C x 1 1 0.52
A x 1.5 2 2.5
B x 2 3 1
C x 2.01 3.0 1.0

it should results (format requirement may also need to clean up some column from B.txt):
10    2.300
A   2.5 3.0 6.1
B   1.0 2.5 4.0
C   1.0 1.0 0.5
20    0.653
A   1.5 2.0 2.5
B   2.0 3.0 1.0
C   2.0 3.0 1.0

A: Here's a solution where n = 3 and N = 4. The n value is passed to awk via -v:
$ cat a.txt
A1
A2
A3
A4

$ cat b.txt
b11
b12
b13
b21
b22
b23
b31
b32
b33
b41
b42
b43

$ awk -v n=3 'NR==FNR {a[NR]=$0; next} FNR % n == 1 {print a[++i]}1' a.txt b.txt
A1
b11
b12
b13
A2
b21
b22
b23
A3
b31
b32
b33
A4
b41
b42
b43

Explanation:
awk -v n=3

Invoke awk passing in the n variable set to value 3
NR==FNR {a[NR]=$0; next}

When NR equals FNR it means we are reading from the first file, a.txt  (because the overall record number, NR, is the same as the record number within the file, FNR).
The associated action saves all the lines from a.txt into the array a, each line being indexed by its line number.
The next statement skips all further processing and goes immediately to try and read the next line from a.txt
FNR % n == 1 {print a[++i]}

When we arrive here we know we are reading the second file, b.txt (this should be clear from reading about NR==FNR and the next statement, above).
We use the mod function with the passed-in block size to test whether the current line of b.txt is the first line of a block. (If the block size is 3, e.g., we know that lines 1, 4, 7, ... start the blocks.)
If we are at the start of a block, we print the next line from the a array containing the lines from a.txt. The incremented index i assures that line t from a.txt will always be printed before block t from b.txt.
1

The 1 is an awk idiom that says to print the current line. Awk consists of a set of patterns and actions. The 1 here is a pattern that evaluates to true. Since there's no explicit action given, the default action is invoked which is to print the current line. Instead of the 1, we could have put {print}, e.g.


text:
Q: Download Zip file in Xamarin iOS Native I have to download a Zip File in Xamarin iOS.
URL - https://osdn.net/projects/sfnet_fotohound/downloads/sample-pictures/Sample/Sample-Pictures.zip/
As soon as i hit this URL, the download should start and the same should get saved in a particular folder in the documents directory.
How should I implement the same in Xamarin Native iOS.

A: You can use NSURLSession to download the zip file.
Firstly, you should find the real download link of this download site.
You can refer to this.

In Chrome - run download as normal - then go to Menu - Downloads - and you should see the direct link which was used.

Actually, your file link is https://mirrors.netix.net/sourceforge/f/fo/fotohound/sample-pictures/Sample/Sample-Pictures.zip.
Now start to code. Create download task via NSURLSession:
        public void downloadTask()
        {
            // Your file link.
            NSUrl url = NSUrl.FromString("https://mirrors.netix.net/sourceforge/f/fo/fotohound/sample-pictures/Sample/Sample-Pictures.zip");

            // Configure your download session.
            var config = NSUrlSessionConfiguration.DefaultSessionConfiguration;
            NSUrlSession session = NSUrlSession.FromConfiguration(config, new SimpleSessionDelegate(), new NSOperationQueue());
            var downloadTask = session.CreateDownloadTask(NSUrlRequest.FromUrl(url));

            // Start the session.
            downloadTask.Resume();
            Console.WriteLine("Start DownloadTask!!!");
        }

Configure the callback DidFinishDownloading:
    class SimpleSessionDelegate : NSUrlSessionDownloadDelegate
    {
        public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location)
        {
            // Configure your destination path. Here's saved to /Documents/ folder.
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var destinationPath = Path.Combine(documents, "Sample.zip");

            if (File.Exists(location.Path))
            {
                NSFileManager fileManager = NSFileManager.DefaultManager;
                NSError error;

                // Remove the same name file in destination path.
                fileManager.Remove(destinationPath, out error);

                // Copy the file from the tmp directory to your destination path. The tmp file will be removed when this delegate finishes.
                bool success = fileManager.Copy(location.Path, destinationPath, out error);

                if (!success)
                {
                    Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription);
                }
            }

        }
     }

Now the file has been saved at the documents directory and named Sample.zip.


text:
Q: Implementing Jquery Isotope on images added dynamically I am trying to write a module for Drupal which would have the functionality to handle images using isotope. What I am trying to do is taking an input link from user, then loading that image in #content-images div. I am facing problems in implementing isotope plugin on those images.
Here is the jsfiddle: http://jsfiddle.net/xu4k7/1/ for my code.
When I change the above code to the following code, images do not show up.
(function ($) {
$(document).ready(function () {
    $("#input-box-to-obtain-image-links").change(function() {
            var value = $(this).val();
            $('#content-images').append('

');
    });

     $('#content-images').isotope({
        itemSelector: '.image'
    });
});
})(jQuery);

I just want to know how can I implement isotope on those images so that when I resize my browser, images align themselves.
Thanks

A: Your isotope wrapper has a 0px height, that's why images are not visible. Maybe isotope init is done too early, so it can't compute its wrapper height ? See
Isotope jquery plugin doesn't show properly on chrome
or
Isotope intermittently returns 0px height on div
(first link really seems to be your solution : put isotope init in a callback fired after the actual DOM update)


text:
Q: Sqoop import null values from mysql doesn't replace Null In mysql there is a table with some columns have null values. I want to sqoop import the table to hive. When I do sqoop import I am getting all null values in the columns that have null in the mysql table.
I am doing the following
sqoop import --connect jdbc:xxxxxx --username xxxx --password xxxx \
--query "select * from  hive_db.xxxx where \$CONDITIONS" --null-string '' \
--null-non-string '' -m 1 --hive-import --hive-database hivedatabase \
--hive-table table --as-parquetfile --create-hive-table --target-dir /user/hive/warehouse/hivedatabase.db/table

But I am still getting the hive columns as Null intsead of empty
Why is this happening? How do I get the desired result.

A: it is used when you import data as textfile to specify null values.
a workaround could be change the null values in your query. depending on your databse engine, it could be something like this (sql server sintax)
--query "select isnull(columnA,''), isnull(columnB,''), etc from yourTable where $conditions"

A: sqoop import --connect jdbc:xxxxxx --username xxxx --password xxxx \
--query "select * from  hive_db.xxxx where \$CONDITIONS" --null-string " " \
--null-non-string " " -m 1 --hive-import --hive-database hivedatabase \
--hive-table table --as-parquetfile --create-hive-table --target-dir /user/hive/warehouse/hivedatabase.db/table


text:
Q: JQuery Version and Editing Tool Tips I am using a tooltip edit script that includes the following:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="http://static.tumblr.com/iuw14ew/VSQma1786/jquery.style-my-tooltips.js"></script>

<script>
    (function($){
        $(document).ready(function(){
            $("a[title]").style_my_tooltips({
                tip_follows_cursor: true,
                tip_delay_time: 90,
                tip_fade_speed: 600,
                attribute: "title"
            });
        });
    })(jQuery);
</script>

But, due to another script I am using, I need to use this version of jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

Trying to use the 2.1.4 breaks the tooltips style. Help? I am super super new to jQuery and Javascript.

A: As @Ali said in his comment, you can use jQuery's noConflict function.
By default, jQuery uses $ as a shorthand function name. Using jQuery.noConflict() you can bind this to something else.
This means, as shown in the linked answer, you can do the following:
For version 1.7, you can do the following:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
   var jQ = $.noConflict(true);
</script>
Now, instead of $(document).ready() you can use jQ(document).ready() to access jQuery 1.7 functions.
jQuery 2.1.4 will still be accessible through $.
Do note that jQuery 1.7 is 6 years old, and might be obsolete. Consider looking for a more up-to-date version of the Tooltip library you're using.
Bootstrap has the functionality you're looking for!


text:
Q: Parameter is not valid Exception in windowsForm i am using multi panels for making multi section project and using access database and inserting some thing in it like below:
    private void addmoneyPanel_firstLoad()
    {
        try
        {
            employee_list.Items.Clear();
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;

            command.CommandText = "select Ename,Elastname from employee";
            OleDbDataReader reader = command.ExecuteReader();
            while(reader.Read())
            {
                employee_list.Items.Add(reader[0].ToString() + " \n" +reader[1].ToString());
            }
            connection.Close();
            /*addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
            addMoneyPanelMes.ForeColor = Color.Green;*/

        }
        catch (Exception err)
        {
            addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
            addMoneyPanelMes.ForeColor = Color.Red;
            addMoneyPanelMes.Visible = true;
        }
    }
    private void pictureBox1_Click_1(object sender, EventArgs e)
    {
        try
        {
            string TempPrice, TempCheckNum, TempCriditNum;
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            if(radioButton1.Checked == true)
            {
                TempPrice = money_price.Text;
                TempCheckNum = "0";
                TempCriditNum = "0";
            }else if(radioButton2.Checked == true)
            {
                TempPrice = money_price.Text;
                TempCheckNum = "0";
                TempCriditNum = criditNumber.Text;
            }
            else
            {
                TempPrice = money_price.Text;
                TempCheckNum = checkNumber.Text;
                TempCriditNum = "0";
            }
            ///////////////////////////////split the combo box names
            string mainToSplit,id = "";
            string[] splited;
            mainToSplit = employee_list.SelectedItem.ToString();
            splited = mainToSplit.Split('\n');
            splited[0] = "" + splited[0].Remove((splited[0].Length-1),1);

            command.CommandText = "select id from employee where Ename='" +splited[0]+ "' AND Elastname='" +splited[1]+"'";
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.Read())
                id = reader[0].ToString();

            connection.Close();

            connection.Open();
            OleDbCommand command2 = new OleDbCommand();

            command2.Connection = connection;
            command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
            command2.ExecuteNonQuery();
            connection.Close();
            addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
            addMoneyPanelMes.ForeColor = Color.Green;
            addMoneyPanelMes.Visible = true;

        }

        catch(OleDbException h)
        {
            addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
            addMoneyPanelMes.ForeColor = Color.Red;
            addMoneyPanelMes.Visible = true;
        }
    }

this 2 function will be run successfully but after that i will get the "Parameter is not valid" Exception in this part:
   private void timer1_Tick(object sender, EventArgs e)
    {
        if(pass == 0 || pass == 1)
        {
            prossespass();
        }
        DateTime datetime = DateTime.Now;
        try
        {
            time.Text = string.Format("{0:hh:mm:ss}", DateTime.Now); // error here
            timesun.Text = datetime.ToString("tt");
        }
        catch(Exception d)
        { }

    }

this is a timer for a clock in my project. so after returning to the main panel that clock is existing in it (make the main panel visible and hide current panel) clock text box cant set and my project crashed.
i dont know what the problem is.
but if i erase this part from the second function that i mentioned:
  addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
            addMoneyPanelMes.ForeColor = Color.Green;
            addMoneyPanelMes.Visible = true;

or removing insert section in second function above:
connection.Open();
            OleDbCommand command2 = new OleDbCommand();

            command2.Connection = connection;
            command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
            command2.ExecuteNonQuery();
            connection.Close();

i have other function in other panels that work with database but work great together this is it. thanks for your help.

A: just turn the timer off:
timer1.Enabled = false;

when  enter to each panel and turn it on when come back to main panel:
timer1.Enabled = true;


text:
Q: Temporary table resource limit i have two applications (server and client), that uses TQuery connected with TClientDataSet through TDCOMConnection,
and in some cases clientdataset opens about 300000 records and than application throws exception "Temporary table resource limit".
Is there any workaround how to fix this? (except "do not open such huge dataset"?)
update: oops i'm sorry there is 300K records, not 3 millions..

A: The error might be from the TQuery rather than the TClientDataSet.  When using a TQuery it creates a temporary table and it might be this limit that you are hitting.  However in saying this, loading 3,000,000 records into a TClientDataSet is a bad idea also as it will  try to load every record into memory - which maybe possible if they are only a few bytes each but it is probably still going to kill your machine (obviously at 1kb each you are going to need 3GB of RAM minimum).
You should try to break your data into smaller chunks.  If it is the TQuery failing this will mean adjusting the SQL (fewer fields / fewer records) or moving to a better database (the BDE is getting a little tired after all).

A: You have the answer already. Don't open such a huge dataset in a ClientDataSet (CDS).
Three million rows in a CDS is a huge memory load (depending on the size of each row, it can be gigantic).
The whole purpose of using a CDS is to work quickly with small datasets that can be manipulated in memory. Adding that many rows is ridiculous; use a real dataset instead, or redesign things so you don't need to retrieve so many rows at a time.

A: over 3 million records is way too much to handle at once.  My guess is that you are performing an export or something like that which requires that many records to be sent down the wire.  One method you could use to reduce this issue would be to have the middle-tier generate an export file, and then deliver that file to the client (preferably compressing first using ZLIB or something simular).
If you are pulling data back to the client for viewing purposes, then consider sending summary information only, and then allowing the client to dig thier way thru the data a portion at a time.  The users would thank you because your performance will go way up and they won't have to dig thru records they don't care about looking at.
EDIT
Even 300,000 records is way too much to handle at once.  If you had that many pennies, would you be able to carry them all?  But if you made it into larger denominations, you could.  if your sending data to the client for a report, then I strongly suggest a summary method... give them the large picture and let them drill slowly into the data. send grouped data and then let them open up slowly.
If this is a search results screen, then set a limit of the number of records to be returned + 1.  For example to display 100 records, set the limit to 101.  Still only display 100, the last record means that there were MORE than 100 records so the customer needs to adjust thier search criteria to return a smaller subset.

A: Temporary table resource limit is not a limit for one single query. it is the limit for all open queries together. so it may be a solution for you to close all other queries at the time.
if it is not possible for you to use ADO connection, also you can design a paging mechanism for querying data page by page.
GOOD LUCK


text:
Q: Tracking geolocation of other users using google maps in real time Since most browsers have HTML5 enabled, tracking the current device and displaying it on the map is possible, however, is there a function for a webapp based device, to update a central database on it's location?
My theory is that a user can POST a form to upload its coordinates, but this would cause it to be slightly of a hassle.
Is there a way, preferably automated, to track a user's geolocation in real time, through a web app?
Before all the downvotes come in, I would like to clarify that yes, I am able to track myself and get geolocation working on my device. What my intention is, is to track others and receive the value, something like a tracker.
edit: totally saw the downvote coming

A: If you want to track other users in real time, you have to use a websocket. For example if you are using node.js as your backend then simply use a package named socket.io, it handles all the heavy duty work for connecting one client to another client
Example code
ClientSide
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');

   // Maybe send some location data through a click of a button
  socket.emit('sendLocation', { latitude: 232.33, longtitude: 232323.33 });

</script>

Serverside
io.on('connection', function(socket) {
   // Socket is listening waiting for the client to send something to the server
   socket.on('sendLocation', function(data) {
       // Emit to everyone that is connected via socket.io
       io.emit('sendToEveryone', data);
   });
});

So the order is
1) Client emit
2) Server listen then will emit it again to the targeted user or all user
Hope it helps

A: *

*I thing this can do it. (for app android)

1: Use spirit level or compass from device android enter link description here
2: When change "spirit level" + timer 1minus -> submit to address new to server.

*

*And if web app you can use refresh browser after frame time.
< html>< head>< meta http-equiv="refresh" content="3">< /head>


text:
Q: How to test a function which should not be exported? I'm working on an angular project and have been writing some test cases for some of the features. Unfortunately I've hit a wall for some reason - I have a function which should NOT be exported but still needs to be tested.
From what I've learned, it seems like I could use rewire, but all of my attempts are producing an insane amount of errors while compiling complaining about Can't resolve 'fs' in node_modules/glob and Can't resolve 'module in 'node_modules/rewire/lib'.
I'm not sure if I'm doing it right. Here's my code:
// my-function.ts
function myFunctionPrivate() { }
export function myFunctionA() { }

// my-function.spec.ts
import * as rewire from 'rewire';

describe('Test myFunction', () => {
    it('should work', () => {
        const app = rewire('./my-function');

        const myFunctionPrivate = app.__get__('myFunctionPrivate');

        console.log(myFunctionPrivate)
    })
})

I was able to fix some of the errors by adding this to the package.json:
"browser": {
  "fs": false,
  "path": false,
  "os": false
}

But I'm still getting errors:
WARNING in ./node_modules/eslint/lib/config/plugins.js
101:25-42 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/config/plugins.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/eslint/lib/config/plugins.js
106:20-45 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/config/plugins.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/eslint/lib/rules.js
118:33-61 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/rules.js
 @ ./node_modules/eslint/lib/linter.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/is-resolvable/index.js
11:2-9 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
 @ ./node_modules/is-resolvable/index.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/eslint/lib/config/plugins.js
125:37-62 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/config/plugins.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/require-uncached/index.js
28:8-25 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/require-uncached/index.js
 @ ./node_modules/eslint/lib/config/config-file.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/eslint/lib/linter.js
540:46-65 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/linter.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/eslint/lib/cli-engine.js
705:23-45 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
Module not found: Error: Can't resolve 'coffee-script' in './node_modules/rewire/lib'
 @ ./node_modules/rewire/lib/moduleEnv.js 168:17-41
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
Module not found: Error: Can't resolve 'coffeescript' in './node_modules/rewire/lib'
 @ ./node_modules/rewire/lib/moduleEnv.js 164:13-36
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

WARNING in ./node_modules/rewire/lib/moduleEnv.js
require.extensions is not supported by webpack. Use a loader instead.
 @ ./node_modules/rewire/lib/rewire.js 6:16-41
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

ERROR in ./node_modules/eslint/lib/rules.js
Module not found: Error: Can't resolve '../conf/replacements' in './node_modules/eslint/lib'
 @ ./node_modules/eslint/lib/rules.js 14:25-56
 @ ./node_modules/eslint/lib/linter.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

ERROR in ./node_modules/eslint/lib/util/module-resolver.js
Module not found: Error: Can't resolve 'module' in './node_modules/eslint/lib/util'
 @ ./node_modules/eslint/lib/util/module-resolver.js 12:15-32
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

ERROR in ./node_modules/require-uncached/node_modules/resolve-from/index.js
Module not found: Error: Can't resolve 'module' in './node_modules/require-uncached/node_modules/resolve-from'
 @ ./node_modules/require-uncached/node_modules/resolve-from/index.js 3:13-30
 @ ./node_modules/require-uncached/index.js
 @ ./node_modules/eslint/lib/config/config-file.js
 @ ./node_modules/eslint/lib/config.js
 @ ./node_modules/eslint/lib/cli-engine.js
 @ ./node_modules/eslint/lib/api.js
 @ ./node_modules/rewire/lib/moduleEnv.js
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

ERROR in ./node_modules/rewire/lib/rewire.js
Module not found: Error: Can't resolve 'module' in './node_modules/rewire/lib'
 @ ./node_modules/rewire/lib/rewire.js 1:13-30
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

ERROR in ./node_modules/rewire/lib/moduleEnv.js
Module not found: Error: Can't resolve 'module' in './node_modules/rewire/lib'
 @ ./node_modules/rewire/lib/moduleEnv.js 5:13-30
 @ ./node_modules/rewire/lib/rewire.js
 @ ./node_modules/rewire/lib/index.js
 @ ./my-function.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts


text:
Q: Unique php string generation I am using
uniqid(md5(time(),false)).uniqid(md5(rand(),false));

to generate unique string. Is this safe to use or there is a chance of collisions? What would you recommend me to use?

A: md5 with time will generate a new unique id evert time but as you are randomizing this generate value there is some chances of collision Instead you can do it like below function
function newId() { return uniqid() . '_' . md5(mt_rand()); }

It will generate a uniqueid and append md5 random value to it so it will always be unique and will be very deficult to brutforce this.


text:
Q: Pathfinding algorithms for continuous maps (e.g. polygons) I try to investigate different algorithms for a short path between two points in a plane with polygonal obstacles.
The vast majority of algorithms I found use discrete maps (Grid Map, visibility graph, Voronoi Roadmap, etc.).
Some books (like "Elements of Robotics" by Ben-Ari or "Introduction to Autonomous Robots" by Nikolaus Correll) mention continuous maps (e.g. raw polygon data), but do not explain corresponding algorithms. They claim memory or efficiency advantages for few and simple obstacles, which could be very interesting for me.
I believe, there should be a clever approach using geometric calculation (e.g. intersection detection) and some algorithmic paradigm (e.g. least cost branch and bound), but I do not want to poorly reinvent the wheel.
Are there any resources for some short(est) path algorithms using continuous maps or useful keywords to search for?

Like suggested, I try to specify some of the terms I used:

*

*Continuous maps

refer to the storage of (continuous) real number values of geometric shapes. Obstacle/Triangle I. would be stored as: A = (3,2), B=(7,5), C=(7,2).

*Discrete maps
 refer to the sub-division into chunks (discretization, e.g. like in a grid map). Obstacle/Triangle I. would now be stored as cell indices:
(3,2), (4,2), (5,2), (6,2), (5,3), (6,3), (6,4)
path-finding in discrete maps is often accomplish by graph based algorithms like Dijkstra or A*.

*Geometric calculation is just a vague term I use for operations of computational geometry I would expect in a path-finding algorithm for continuous maps. (e.g. Translation, perpendicular distance, intersection detection)

A: Another, more often used, term for my problem seem to be Euclidean Shortest Path(s). The distinction between algorithms for Continuous maps and Discrete maps seems to be a bit ambiguous to me.
However, the nearest thing I found to an algorithm for a continuous map is Mitchell's Algorithm for the Continuous Dijkstra Problem (or continuous Dijkstra method).
This algorithm uses wavelets that spread evenly from the starting point. By "diffraction" of the wavelets, they reach areas that cannot be reached directly. This creates a shortest-path map which can be used to identify the Euclidean shortest path to any point in the continuous configuration space.
For more see:

*

*"Euclidean Shortest Paths Exact or Approximate Algorithms" by F. Li and R. Klette

*nice but a bit buggy animation by Ivan Chen

*application by Anton Kovsharov
One may argue, that the created shortest-path map is just a another discretisation of the continuous configuration space. However, I guess the shortest-path map is just an result which can be obtained, if the algorithm is applied to the entire configuration space. If just the shortest path between two points is wanted, the algorithm could stop after reaching the target point.
I remain unsure about the classification of these algorithms but this should answer my question.

A: For the "continuous maps" as you called it, just use Dijkstra on all of you vertices.
The only difference is that you have to check for clipping when calculating the distance between nodes.


text:
Q: How do I create a field using ng-if in a dynamic list (index included)? I've used this method a thousand times to create a "please describe" field when the "other" option is selected, but it is not working when it is part of a dynamic list. Something about the addition of the index is making it not work. How can I make this work in a dynamic list?
Normally, I would try one of these:

        <input type="checkbox" name="discrepancy_resolution_other_{{$index}}" ng-true-value="'Checked'" ng-false-value="'delete'"> Other

        <input type="text" name="discrepancy_resolution_other_content" placeholder="Please describe" required="true">

        <input type="checkbox" name="discrepancy_resolution_other_{{$index}}" ng-true-value="'Checked'" ng-false-value="'delete'"> Other

        <input type="text" name="discrepancy_resolution_other_content_{{$index}}" placeholder="Please describe" required="true">

A: This cannot work:
ng-if="model.discrepancy_resolution_other_{{$index}} === 'Checked'"

Remember simply that you cannot use interpolations {{}} within a ng-if (or ng-show) expression. If your variable is named discrepancy_resolution_other_3 for instance, you could solve your problem doing:
ng-if="getThing(model, $index) === 'Checked'"

And then in your controller implement getThing:
$scope.getThing = function(model, index) {
  if (index === 3) {
    return model.discrepancy_resolution_other_3;
  }
  // etc...
}

However it would be easier to put your variables into an array $scope.model.myArray so you could directly access it from the HTML:
ng-if="model.myArray[$index] === 'Checked'"


text:
Q: POST dynamically added Lists to Controller as Json and redirect view Description
I'm am creating a dynamic table where the user can select regions in a dropdown lists. On "add" the user can also add new table rows with region dropdown lists included. On POST, a list of Regions should be posted to the controller where it´s being saved to the SavingPlan model.
Problem
Ajax is returning null to my controller even though I have saved selected option-data to string arrays which is being posted to the controller.
Addition
I am fairly new to ASP.NET MVC so please have that in mind when commenting. I am open minded towards doing things differently but I´d very much appreciate I someone would be able to guid me and my code in the right direction.
Region Model
   public class Region
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Saving Plan Model
public SavingPlan()
        {
        }

        public SavingPlan(List<Region> regionList)
        {
            RegionList = regionList;
        }

        public int Id { get; set; }

        public ApplicationUser AssessmentUser { get; set; }
        public IEnumerable<Region> RegionLookUp { get; set; }
        public bool IsActive { get; set; }
        public byte RegionId { get; set; }
        public Region Region { get; set; }
        public List<Region> RegionList { get; set; }
    }

SavingPlan - ViewModel
    public class SavingPlan
    {
        public SavingPlan()
        {
        }

        public SavingPlan(List<Region> regionList)
        {
            RegionList = regionList;
        }

        public int Id { get; set; }

        public ApplicationUser AssessmentUser { get; set; }
        public IEnumerable<Region> RegionLookUp { get; set; }
        public bool IsActive { get; set; }
        public byte RegionId { get; set; }
        public Region Region { get; set; }
        public List<Region> RegionList { get; set; }
    }

Controller Action GET - NewSavingPlan
        public ActionResult NewSavingPlan()
        {
            SavingPlanAssessmentView viewModel = new SavingPlanAssessmentView();
            viewModel.SavingPlan = new SavingPlan();

            var regions = _context.Regions
                .ToList();

            viewModel.RegionLookUp = regions;
            return View(viewModel);
        }

Controller Action POST - Save SavingPlan
        [HttpPost]
        public JsonResult SaveList(string RegionList)
        {
            var urlBuilder = new UrlHelper(Request.RequestContext);
            var url = urlBuilder.Action("Index", "Assessments");

            string[] arr = RegionList.Split(',');

            foreach (var item in arr)
            {
                var region = item;
            }

            return Json(new { status = "success", redirectUrl = Url.Action("Index","Home") });

        }

SavingPlan Partial View
@model BBRG.ViewModels.SavingPlanAssessmentView

@Model.Heading

@*@using (Html.BeginForm("Save", "Assessments", FormMethod.Post))
{*@
    @*@Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)*@

    <legend>Saving Plan</legend>

                Region
                 <button id="add" type="button" class="btn btn-link">Add</button>

                    @Html.DropDownListFor(m => m.RegionId, new SelectList(Model.RegionLookUp, "Id", "Name"), "Select Region", new { @class = "form-control Region", id = "Region_1", type="string", name = "Region", selected="false" })

                    <button data-region-id="@Model.RegionId" id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>

        @Html.HiddenFor(m => m.Id)
        <button data-saving-id="@User.Identity" onclick="saveRegion()" type="submit" calss="btn btn-default js-toggle-save">Save</button>

Jquery - Add new table row with dropdownlist
$(document).ready(function () {
    var counter = 2;
    $(function () {

        $('#add').click(function () {
            $('
'
                + ''
                + '<select type="text" value="RegionId" name="Region" id="Region_'+ counter+'" class="form-control Region" " >'
                + $(".Region").html()
                + '</select>'
                + '	'
                + ''
                + '<button data-region-id= id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>'
                + '	'
                + '
').appendTo('#regionTable');
            counter++;
            return false;
        });
    });
});

Jquery and .ajax for POST
    {

}```

A: I found the solution to my problem, I forgot to stringify my .ajax data. If anyone still want to provide me with some constructive input, please don´t hesitate.
               $.ajax({
                   url: "../SavingPlans/SaveList",
                   data: JSON.stringify({ RegionId: commaSeperated }),
                   type: "POST",
                   dataType: "json",
                   contentType: 'application/json; charset=utf-8',
                   success: function (json) {
                       if (json.status == "success") {
                           window.location.href = json.redirectUrl;
                       };
                   }
               });


text:
Q: root resource classes scanning pattern of Jersey framework I have created sample project in eclipse and deployed it in tomcat.
I am using below jar files.
asm-3.1.jar
jersey-core-1.10.jar
jersey-server-1.10.jar
jersey-servlet-1.10.jar
below are classes.
package example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("helloworld")
public class HelloWorldResource {

    @GET
    @Produces("text/plain")
    public String getHello() {
        return "Hello World!";
    }

}

and
package example;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class MyApplication extends Application {
//    @Override
//    public Set<Class<?>> getClasses() {
//        final Set<Class<?>> classes = new HashSet<Class<?>>();
//        // register root resource
//        classes.add(HelloWorldResource.class);
//        return classes;
//    }
}

my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <display-name>JXRSHelloWorld</display-name>
    <servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
</web-app>

My Doubts

*

*How does Jersey framework inject/scan JAX-RS resources. if we don't provide class names explicitly

*Some docs says (links are provided below), we have to explicitly register package name to tell Jersey framework so it can scan those packages and inject AX-RS resources.
Link 1 : https://jersey.java.net/documentation/latest/deployment.html#deployment.servlet.2
Link 2 : http://docs.oracle.com/cd/E19776-01/820-4867/ggnxs/index.html
even if I remove method getClasses() from class MyApplication, It is working fine. My doubt is how does it finds resource HelloWorldResource.java ?
This is my Tomcat's catalina.out logfile's snap:
Feb 6, 2014 7:48:38 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class example.HelloWorldResource

In above code I do not explicitly tell framework to register my class HelloWorldResource as I have commented getClasses method.
Does it scan by annotation like @Path("helloworld") @Produces("text/plain") ?
Thanks,
Niraj


text:
Q: Handling notification alerts that fire when the app is not running, but still show when the app is running Let's say my app is running in the background, and I receive 2 local notifications at the same time.  Alert1 for Notification1 shows, then Alert2 for Notification2 shows on top of Alert1.  When I tap "View" for Alert2, my app enters the foreground, and didReceiveLocalNotification is called for Notification2, everything is all good.
However, Alert1 is still showing (since it was never closed or viewed).  If I tap "View", nothing happens and as expected, didReceiveLocalNotification for Notification1 is NOT called.
Is there a way to either:

*

*clear all Alerts so that Alert1 is not shown when the app is entering foreground for Alert2

*handle the tap for "View" when Alert1 is pressed, since didReceiveLocalNotification is not called

Thanks!

A: Calling cancelAllLocalNotifications also dismisses currently displayed alerts, even if the notification has already fired.
It's mentioned in the Local and Push Notification Programming Guide:

You can cancel a specific scheduled
  notification by calling
  cancelLocalNotification: on the
  application object, and you can cancel
  all scheduled notifications by calling
  cancelAllLocalNotifications. Both of
  these methods also programmatically
  dismiss a currently displayed
  notification alert.

Hence, I need to cancelAllNotifications and reschedule my current scheduled notifications. I tried cancelLocalNotification, but I don't have a reference to the notification because it no longer exists in the scheduledLocalNotifications array since it has already fired.


text:
Q: ¿Cómo abrir archivos con formato .psql? PostgreSQL Me están enviando un archivo con formato .psql y pesa unos 30MB, me dicen que es la base de datos en PostgreSQL, pero con sinceridad no consigo como conectarme para ver los datos de la BD. Agradezco de antemano sus respuestas!

A: (Según lo conversado en los comentarios)
Lo que te están enviando es el export de una BD y lo que tenes que hacer es crear una DB en tu servidor local e importar dicho archivo.
Por ejemplo, desde la línea de comandos:
$ psql -U username dbname < dbexport.psql


text:
Q: Subsetting data from a dataframe and taking specific values from the subsetted values I want to check if values (in example below "letters") in 1 dataframe appear in another dataframe. And if that is the case, I want a value (in example below "ranking") which is specific for that value from the first dataframe to be added to the second dataframe... What I have now Is the following:
Df1 <- data.frame(c("A", "C", "E"), c(1:3))
colnames(Df1) <- c("letters", "ranking")

Df2 <- data.frame(c("A", "B", "C", "D", "E"))
colnames(Df2) <- c("letters")

Df2$rank <- ifelse(Df2$letters %in% Df1$letters, 1, 0)

However... Instead of getting a '1' when the letters overlap, I want to get the specific 'ranking' number from Df1.
Thanks!

A: What you're looking for is called a merge:
merge(Df2, Df1, by="letters", all.x=TRUE)

Also, fun fact, you can create a dataframe and name the columns at the same time (and you'll usually want to "turn off" strings as factors):
df1 <- data.frame(
    letters = c("a", "b", "c"),
    ranking = 1:3,
    stringsAsFactors = FALSE)

A: dplyr package is best for this.
Df2 <- Df2 %>%
    left_join(Df1,by = "letters")

this will show a NA for "D" if you want to keep it.
Otherwise you can do semi_join
DF2 <- Df2 %>%
   semi_join(Df1, by = "letters")

And this will only keep the ones they have in common (intersection)


text:
Q: "Everybody Loves a Lover" Isn't Z part of Everybody? I have a short circuit when I try to think of this formula meaning "Everybody Loves a Lover":
$\forall x \forall y ~[ \exists z (L(x,z) \land L(z,x)) \Rightarrow L(y,x)]$
my problem is that if I divide the universe of all people in $X,Y,Z$. Then we say that for all $X$ and $Y$, $Y$ will love $X$ only if $X$ is lover with atleast one $Z$, this does not tell me that also all of the $Z$ will love every lover $X$.. so it is incomplete in defining "everybody loves a lover" because everybody is missing the $Z$ people. But if $Z$ is just a different name to define the all of the poeple and $Y$ is another way to define the all of the poeple then it is ok. So point is that $X,Y$,$Z$ are the same set right? but we use them separately so to define diverse role in between the different people at different "times"?
Thanks!

A: $$\forall x~\forall y~\Big(\exists z~\big(L(x,z)\wedge L(z,x)\big)\to L(y,x)\Big)$$
The formula says: "$\text{Any $x$ will$\underbrace{\text{ be loved by }}_{\text{may be unrequired}}$any $y$ if that $x$$\underbrace{\text{ loves and is loved by }}_{\text{mutual love}}$some $z$.}$"
Or compactly: "Anyone who is a lover, is loved by everyone."
It does not claim that every lover loves everyone.

However, the PreNex form is indeed:
$$\forall x~\forall y~\forall z~\Big(\big(L(x,z)\wedge L(z,x)\big)\to L(y,x)\Big)$$
"For any $x,y,z$, then $y$ will love $x$ if $x$ loves and is loved by $z$."

A: You can't say that $X$, $Y$, and $Z$ are sets of people, but then also say things like '$Y$ will love $X$ if ...', because at that point you are treating $X$ and $Y$ as individual persons again, rather than as sets of people. Indeed, when you say '$Y$ will love $X$ if ...', then your $X$, $Y$, and $Z$ are no different than variables $x$, $y$, and $z$.
What is going on, though, is that $x$, $y$, and $z$ are all quantified, and when we use several quantifiers in a sentence, all quantifiers quantify over the exact same domain, which in this case is all people.
And so yes, what you say in the end is captures the right idea correct: since the $z$ comes from the exact same domain as the $y$, it will in the end be true that whatever you picked for $z$, which is some person, will at some point also be picked for $y$ (since $y$ is going to range over all persons), and hence also that $z$ will end up loving everybody, as desired, even though you do not explicitly state that about $z$ in the formula.