text:
Q: how many digits does R carry in a numeric calculation (how to increase number of digits in R Numeric) If I do
126.887429023806 + 0.0120214904747417

in R, it returns
[1] 126.8995

Instead of 126.8994505142807417
How do I preserve more decimals?

redpajama_set_name: RedPajamaStackExchange


text:
Q: java annotation for url - what is use case? Im trying to figure out what a annotation does that is created in code i have inherited.
Here is the annotation definition per code:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseUrl {
}

then using dagger 2 ( a dependency injection framework for android), its used like this:
//from a file called applicationModule.java
@Provides
    @Singleton
    Endpoint provideBaseURL(@BaseUrl String url) {
        return getEndPointUrl(url);
    }

I am more concerned about the @BaseUrl annotation. what does it do in this context ?
The project uses Retrofit.

A: I finally found what whats happening and i'd like to share.  Dagger has two ways to help when type alone cannot identify a provider.  Either use @named or @Qualifier annotation.  The @named annotation can be used as default but if you want to create your own annotation for identifying a provider you can use @Qualifier.
So in the example i provided the @BaseURL is nothing more then a @Named tag to attach to a provider. They do the same thing but instead of using the word "Named" which is provided by dagger, you can make your own. The docs are here under qualifier section.


text:
Q: UISlider strange behavior When I customized UISlider and override the minimumTrackTintColor, maximumTrackTintColor, and trackHeight, I noticed the slider had a strange offset when the value approaches the end of the slider.
However, there is no offset when slider is in the middle range. Any idea how to fix it?
Offset when approaching the end:

Normal in the middle range:


text:
Q: Android playing stream m3u using mediaPlayer I'm building an application that play streaming m3u file from web.
I'm using mediaPlayer class and it works.
Here's the code :
String test_path = "http://cast.idvps.com:8000/djwirya.m3u";
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(test_path);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {Log.e("Error", "No Stream");}
        mediaPlayer.start();

It was working perfectly. But, after a whie I compiled it again, there's no sound.
pls help.... THX

A: You need to call mediaPlayer.setOnPreparedListener(this) before the prepareAsync(). This assumes that your activity or whatever has implemented the OnPreparedListener interface. Then you need a callback called onPrepared() in which you can call mediaPlayer.start().
The other thing you need to do is make sure you call mediaPlayer.release() somewhere when your app is ending. Inside of onPause() is probably a good idea.

A: This is a solution.
Sorry I'm french but i'm think that should be ok with google translation.
Link for a solution


text:
Q: Mysql creating a new column but already exist Here is my table SQL
CREATE TABLE IF NOT EXISTS `kiln_input_data` (
  `id` int(11) NOT NULL,
  `kiln_num` int(10) NOT NULL,
  `chargenum` varchar(20) NOT NULL,
  `datein` date NOT NULL,
  `dateout` date NOT NULL,
  `drytime` decimal(12,1) NOT NULL,
  `kilnsched` int(5) NOT NULL,
  `target` decimal(12,1) NOT NULL,
  `emc` decimal(12,1) NOT NULL,
  `tdal` decimal(11,1) NOT NULL,
  `opinit` varchar(5) NOT NULL,
  `mca` decimal(12,1) NOT NULL,
  `stda` decimal(11,1) NOT NULL,
  `mcb` decimal(12,1) NOT NULL,
  `sdtb` decimal(11,1) NOT NULL,
  `checkdimension` varchar(20) NOT NULL,
  `bf4` int(11) NOT NULL,
  `bf6` int(11) NOT NULL,
  `bf8` int(11) NOT NULL,
  `bf90` int(11) NOT NULL,
  `bf105` int(11) NOT NULL,
  `_submitted_` date NOT NULL,
  `_fromaddress_` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

All works fine, however, after inserting data from form I get a repeat column stdb appended to the end of the table, not sure why
kiln_input_data

Column  Type    Null    Default Comments
id  int(11) No
kiln_num    decimal(11,0)   Yes     NULL
chargenum   varchar(20) No
datein  date    No
dateout date    No
drytime decimal(12,1)   Yes     NULL
kilnsched   decimal(11,0)   Yes     NULL
target  decimal(12,1)   Yes     NULL
emc decimal(12,1)   Yes     NULL
tdal    decimal(12,1)   Yes     NULL
opinit  varchar(5)  No
mca decimal(12,1)   Yes     NULL
stda    decimal(12,1)   Yes     NULL
mcb decimal(12,1)   Yes     NULL
sdtb    decimal(11,1)   No
checkdimension  varchar(20) No
bf4 decimal(11,0)   Yes     NULL
bf6 decimal(11,0)   Yes     NULL
bf8 decimal(11,0)   Yes     NULL
bf90    decimal(11,0)   Yes     NULL
bf105   decimal(11,0)   Yes     NULL
_submitted_ date    No
_fromaddress_   varchar(20) No
stdb    decimal(12,1)   Yes     NULL


text:
Q: Codename one - BLE scanning on Android 6 not working I'm building an app in CN1 that communicates with a BLE device (BlueGiga BLE module). In android 5.0 an CN1 app works as it should. In Android 6 the same app can't find any BLE devices. I can however connect manually to a specific BLE device (device address preset). So the scanning in Android 6 doesn't work.
Based on this I figured out that I need to turn on GPS location and in the source add:
LocationManager locationManager = LocationManager.getLocationManager();
Is this a bug in CN1 or is it a problem in android?
The default scanner in Android 6 (under Settings -> Bluetooth) and the app BlueGiga don't need to turn on GPS location (BlueGiga is written in Android). I also found the app BLE Scanner that does need to turn GPS location. Is it written in CN1?
Why is it necessary to turn on GPS location for BLE scanning to work on devices with Android 6?

A: The location manager in Android doesn't necessarily map to GPS it maps to "hybrid location" which means it can take location from various sources and combine them into a single location.
I'm not familiar enough with that device but if it provides location it makes sense to "ask for location permissions" which is what we are doing here. As James mentioned in the comments this has nothing to do with the fact that the device is implemented as BLE as that's an external cn1lib and we just invoke the Android API's which abstract that.


text:
Q: why can't I use gnome in my Suse11 box I newly installed a suse11 sp1 box. after the initial installation I do get a pretty gnome based desktop, but after reboot what i get is just a text prompt, the user I login with has
a run level of 5, so I'm puzzled, any of you can give me some tips on it?
In short, my question can be like this: how to enable gnome in Suse11.


text:
Q: More efficient function and for loop I am trying to do a more efficient for loop. I know the existence of sapply, laaply, etc. but I don't know how to implement it in my code.
I have my function which I don't know if it is very efficient. I think I should improve this but I don't know how.
myfun <- function(a, b, c) {
  sum <- 0
  iter <- 0
  while (sum < c) {
    nr <- runif(1, a, b)
    sum <- sum + nr
    iter <- iter + 1
  }
  return(iter)
}

And here is the part which I would like to use an sapply or something similar.
a <- 0
b <- 1
c <- 2
x <- 0
for (i in 1:10^9) {
  x <- x + myfun(a, b, c)
}

Also, I need to make a sapply similar to this
sapply(1:10^9, functie(a ,b ,c))

But the sapply uses 1:10^9 as parameters, instead of a, b, c.

A: I think replicate() is what you may be looking for (I changed your n to something smaller).
set.seed(1234)

n <- 10^2

y <- replicate(n, myfun(a,b,c))
sum(y)
# [1] 462

This matches your prior result.
set.seed(1234)

a <-0
b <-1
c <-2
x <-0
for (i in 1:n){
  x <- x + myfun(a,b,c)
}

x
# [1] 462

A: Recursion
Here is a recursive function f() that does the same job as myfun().
f <- function(s=0) {
  if (s[length(s)] >= 2) {
    return(length(s) - 1L)
  } else {
    f(c(s, s[length(s)] + runif(1, 0L, 1L)))
  }
}

set.seed(42)

f()
# [1] 3

replicate(8, f())
# [1] 4 5 4 4 3 5 3 5

stopifnot(all.equal({set.seed(42);f()}, {set.seed(42);myfun(0, 1, 2)}))

However (and most likely for that reason), it's just cooler, not faster.
Rcpp
Learning from that, we may define the while loop in Rcpp.
library(Rcpp)
cppFunction('
double myfun_cpp() {
  double s = 0;
  int i = 0;
  while (s < 2) {
    s = s + R::runif(0, 1);
    i++;
  }
  return i;
}
')
set.seed(42)

myfun_cpp()
# [1] 3

replicate(8, myfun_cpp())
# [1] 4 5 4 4 3 5 3 5

stopifnot(all.equal({set.seed(42);myfun_cpp()}, {set.seed(42);myfun(0, 1, 2)}))

Now it's lightning fast:
# Unit: milliseconds
#      expr       min        lq      mean    median        uq      max neval cld
#         f 22.244076 22.639439 25.345203 22.927777 24.089196 35.82683   100   c
# myfun_cpp  3.204448  3.260542  3.843632  3.294618  3.347971 13.71213   100 a
#     myfun 16.823981 17.125346 20.605663 17.516248 27.385791 28.63267   100  b

set.seed(42); R <- 1e3
microbenchmark::microbenchmark(
  f=replicate(R, f()),
  myfun_cpp=replicate(R, myfun_cpp()),
  myfun=replicate(R, myfun(0, 1, 2)), times=1e2L,
  control=list(warmup=1e1L))

A: Here are some options

*

*A base R recursion method

f_TIC <- function(x, y, z) ifelse(z <= 0, 0, f_TIC(x, y, z - runif(1, x, y)) + 1)

*

*Rcpp implementation of f_TIC
library(Rcpp)
cppFunction("
int f_TIC_cpp(double x, double y, double z) {
  if (z <= 0) {
    return 0;
  } else {
    return f_TIC_cpp(x, y, z- R::runif(0,1))+1;
  }
}
")

Benchmarking
library(Rcpp)

f <- function(s = 0) {
  if (s[length(s)] >= 2) {
    return(length(s) - 1L)
  } else {
    f(c(s, s[length(s)] + runif(1, 0L, 1L)))
  }
}

f_TIC <- function(x, y, z) ifelse(z <= 0, 0, f_TIC(x, y, z - runif(1, x, y)) + 1)

cppFunction("
double myfun_cpp() {
  double s = 0;
  int i = 0;
  while (s < 2) {
    s = s + R::runif(0, 1);
    i++;
  }
  return i;
}
")

cppFunction("
int f_TIC_cpp(double x, double y, double z) {
  if (z <= 0) {
    return 0;
  } else {
    return f_TIC_cpp(x, y, z- R::runif(0,1))+1;
  }
}
")

myfun <- function(a, b, c) {
  sum <- 0
  iter <- 0
  while (sum < c) {
    nr <- runif(1, a, b)
    sum <- sum + nr
    iter <- iter + 1
  }
  return(iter)
}

set.seed(42)
R <- 1e3
microbenchmark::microbenchmark(
  f = replicate(R, f()),
  f_TIC = replicate(R, f_TIC(0, 1, 2)),
  f_TIC_cpp = replicate(R, f_TIC_cpp(0,1,2)),
  myfun_cpp = replicate(R, myfun_cpp()),
  myfun = replicate(R, myfun(0, 1, 2)),
  times = 1e2L,
  control = list(warmup = 1e1L)
)

and we will see
Unit: milliseconds
      expr     min       lq      mean   median       uq     max neval
         f 11.9342 12.50330 14.161982 13.02100 14.96575 22.7116   100
     f_TIC 20.1925 21.69420 23.678240 22.28255 24.86350 34.1577   100
 f_TIC_cpp  2.0293  2.10080  2.639625  2.17505  2.36190  7.9715   100
 myfun_cpp  1.7351  1.79415  2.094577  1.83810  2.00495  6.7481   100
     myfun  9.1408  9.45240 11.783504 10.32355 14.68815 19.5400   100

A: You're doing it right, in my honest opinion.
Since you don't need to return a vectorized or multi-dimensional result but instead update an existing object at each iteration, the for loop you're suggesting is more than adequate.
If you want to take a look at some great discussion about this topic I suggest you to look at this link: https://r4ds.had.co.nz/iteration.html
Edit: just to address the speed argument
start <- Sys.time()
purrr::map_dbl(1:1000, function(x) y + myfun(a, b, c)) %>% sum
end <- Sys.time()
end - start

# Time difference of 0.02593184 secs

start <- Sys.time()
y <- replicate(1000, myfun(a,b,c))
cumsum(y)[1000]
end <- Sys.time()
end - start

# Time difference of 0.01755929 secs

y <- 0
start <- Sys.time()
for(i in 1:1000){
  y<- y + myfun(a,b,c)
}
end <- Sys.time()
end - start

# Time difference of 0.01459098 secs

A: I would probably solve this using purrr::map(). E.g. like this:
c(1:1e9) %>%
  purrr::map_dbl(
    ~ myfun(a, b, c)
  ) %>%
  sum()

This first calls myfun() the same number of times as the length of c(1:1e9), and stores the results in a numeric vector, then it uses sum() to add the results together.
My tests shows it's a bit faster than using replicate().


text:
Q: Matrix Multiplication MPI stop working I am trying matrix multiplication using MPI. My problem is that when I run my code, it prints the message ARRAY C (C=AxB) and it stops working. Can anyone help me with that?
That's my code.
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
float **A,**B,**C;
int rownumA,colnumA,c,i,j,k,rank,size,nrank,srowA,srowB,smul,node,node1,temp,rrowA,sender;
int rownumB,colnumB,c1,rc;
MPI_Status stat;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if (size < 2 ) {
  printf("Error\n");
  MPI_Abort(MPI_COMM_WORLD, rc);
  exit(1);
  }
nrank=rank-1;
if (rank == 0)
{

//READ AND FILL FIRST ARRAY
FILE *fp;

colnumA=rownumA=0;
fp=fopen("g.txt","r");
if (fp==NULL) exit(1);

//count rows and lines of 2d array
while ((c = getc(fp)) != EOF)
    {
       if (c==' ')
            colnumA++;

        if (c == '\n')
            rownumA++;
    }
    colnumA=(colnumA/rownumA)+1;
fclose(fp);
// end count

//create dynamic array
A =(float **) malloc(rownumA*sizeof(float*));
for(i=0; i<rownumA; i++){
    A[i]= (float *)malloc(colnumA*sizeof(float));
}

//Fill 2d array from file
fp=fopen("g.txt","r");

for (i=0;i<rownumA; i++){
        for(j=0; j<colnumA; j++){
            fscanf(fp,"%f",&A[i][j]);

        }
}
//end add
fclose(fp);

//READ AND FILL ARRAY B

FILE *fp1;
colnumB=rownumB=0;
fp1=fopen("h.txt","r");
if (fp1==NULL) exit(1);

//count rows and lines of 2d array
while ((c1 = getc(fp1)) != EOF)
    {
       if (c1==' ')
            colnumB++;

        if (c1 == '\n')
            rownumB++;
    }
    colnumB=(colnumB/rownumB)+1;
fclose(fp1);
// end count

//create dynamic array
B =(float **) malloc(rownumB*sizeof(float *));
for(i=0; i<rownumB; i++){
    B[i]= (float *)malloc(colnumB*sizeof(float));
}

//Fill 2d array from file
fp1=fopen("h.txt","r");

for (i=0;i<rownumB; i++){
        for(j=0; j<colnumB; j++){
            fscanf(fp1,"%f",&B[i][j]);

        }
}
//end add
fclose(fp1);

if (colnumA != rownumB ){
    printf("\n Error cant mult!\n");
    exit(1);
}

//create dynamic array
C = (float **)malloc(rownumA*sizeof(float *));
for(i=0; i<colnumB; i++){
    C[i]= (float *)malloc(colnumB*sizeof(float));
}
//Init C with 0
for (i=0;i<rownumA; i++){
        for(j=0; j<colnumB; j++){
                C[i][j]=0;
        }
}
srowA=rownumA/nrank;
rrowA=rownumA%nrank;
smul=0;

for (node=1; node<=nrank; node++)
    {
        if (node<=rrowA)
            temp=srowA+1;
        else
            temp=srowA;

    MPI_Send(&smul,1,MPI_INT,node,1,MPI_COMM_WORLD);
    MPI_Send(&temp,1,MPI_INT,node,1,MPI_COMM_WORLD);
    MPI_Send(&colnumA,1,MPI_INT,node,1,MPI_COMM_WORLD);
    MPI_Send(&colnumB,1,MPI_INT,node,1,MPI_COMM_WORLD);
    MPI_Send(&A[smul][0],temp*colnumA,MPI_DOUBLE,node,1,MPI_COMM_WORLD);
    MPI_Send(&B,colnumA*colnumB,MPI_DOUBLE,node,1,MPI_COMM_WORLD);
    MPI_Send(&rownumA,1,MPI_INT,node,1,MPI_COMM_WORLD);
    smul=smul+temp;

    }

    //receive results
    for (node1=1; node1<nrank; node1++)
    {
        sender=node1;
        MPI_Recv(&smul,1,MPI_INT,sender,2,MPI_COMM_WORLD,&stat);
        MPI_Recv(&temp,1,MPI_INT,sender,2,MPI_COMM_WORLD,&stat);
        MPI_Recv(&C[smul][0],temp*colnumB,MPI_DOUBLE,sender,2,MPI_COMM_WORLD,&stat);

    }

    //print results
    //Print at file C array
    FILE *fpr;
    fpr=fopen("results.txt","w");
    if (fpr == NULL) exit(1);
    printf("\n\n /// ARRAY C (C=AxB) /// \n \n \n");
    for (i=0;i<rownumA; i++){
            for(j=0; j<colnumB; j++){
                fprintf(fpr,"%0.3f ",C[i][j]);
            }
            fprintf(fpr,"\n");
}
fclose(fpr);

} //end master

if (rank>0)
    {
            MPI_Recv(&smul,1,MPI_INT,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&temp,1,MPI_INT,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&colnumA,1,MPI_INT,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&colnumB,1,MPI_INT,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&A,temp*colnumA,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&B,colnumA*colnumB,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&stat);
            MPI_Recv(&rownumA,1,MPI_INT,0,1,MPI_COMM_WORLD,&stat);

        for(k=0; j<colnumB ; k++)
    for(i=0; i<temp; i++)
    for(j=0; j<colnumA; j++)
    {
        C[i][k]+=A[i][j]*B[j][k];
    }

    //send results
        MPI_Send(&smul, 1,MPI_INT,0,2,MPI_COMM_WORLD);
        MPI_Send(&temp,1,MPI_INT,0,2,MPI_COMM_WORLD);
        MPI_Send(&C,temp*colnumB,MPI_DOUBLE,0,2,MPI_COMM_WORLD);
    }

  MPI_Finalize();
}

A: Here
//create dynamic array
C = (float **)malloc(rownumA*sizeof(float *));
for(i=0; i<colnumB; i++){
    C[i]= (float *)malloc(colnumB*sizeof(float));
}

the upper bound of the for loop should be rownumA.


text:
Q: Injecting ElementRef to injecable error I have an issue with injecting ElementRef to my Injectable. Here is my code:
import {Injectable, DynamicComponentLoader, ElementRef, Inject} from "angular2/core";
import {Modal} from './Modal';

@Injectable()
export class ModalService{
    constructor(public _dcl:DynamicComponentLoader, public _el:ElementRef){

    }

    createModal(parent){
        this._dcl.loadIntoLocation(Modal,this._el, 'modal')
    }

}

My Modal:
import {Component} from "angular2/core";
@Component({
    selector: 'modal',
    templateUrl: 'app/common/modal/Modal.html'
})

export class Modal{
    constructor(){

    }
}

This yields me to the following error:

No provider for ElementRef! (HomeComponent -> ModalService -> ElementRef)

Why?

A: You can inject ElementRef in a service if this service is provided by a component.
The component :
@Component({
    selector: 'app-rack-view',
    providers: [ MyService ],
})
export class MyComponent {}

The service:
@Injectable()
export class MyService {
    constructor(private elementRef: ElementRef<HTMLDivElement>) {} // OK
}

A: You can't inject ElementRef to a service class, only to a component or directive. ElementRef injects an instance where .nativeElement points to the DOM element the component or directive is attached to but there is no DOM element for a service.
In your example ElementRef can't be any ElementRef. The ElementRef determines where you Modal component is added to the DOM.
I suggest you add one single Modal component somewhere to the DOM that provides the service of showing content as a modal. This component injects a globally shared service and subscribes to events.
Other components that want to use the Modal component also inject the global service and emit a component type to be received by the subscribing Modal component which then uses DynamicComponentLoader to add the passed component to itself to be shown as modal.
For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
There are also several similar questions on SO already.


text:
Q: CSS/HTML Layout divs to fit in fixed-height div I am new to CSS and I am trying to create something unusual.
My code:

div1

div2

div3

div4

div5

div6

div7

let's say screen is 250px height -> the main div height will be 250px too then.
Result:
div1
div2
div3
...

I know that setting float:left; will display them like
div1 div2 div3 div4 div5 ....

I would like to get:
div1 div3 div5 div7
div2 div4 div6

It's like horizontal gallery.
Also, when there would be more divs, is it possible to make main div's width variable and add an x-scrollbar?
This is supposed to work on Internet Explorer 7 and higher only. Also, JavaScript is an option.
Thanks in advance!

A: What you're trying to achieve is quite easy with CSS3: http://jsfiddle.net/Ykkyg/
That fiddle provides the standard CSS for it, and the engine-specific properties for Webkit (Safari, Chrome) and Gecko (Firefox).
There's a couple of problems with this approach though:

*

*First, IE doesn't support it.

*Second, If that column set grows taller than the browser window, you're going to force your user to scroll up and down to read just one continuous piece of text. This sucks.

Without CSS3, you can achieve this effect by carefully sizing all elements a priori, but that doesn't scale, and I'm afraid I know of no generic solution to the problem that doesn't involve some non-trivial javascript.


text:
Q: Fastest serializer and deserializer with lowest memory footprint in C#? I am currently using the binary formatter (Remoting) to serialize and deserialize objects for sending around my LAN.
I have recently upgraded from 2.0 to .NET 3.5. Has 3.5 introduced any new types to improve serialization performance?
I've looked at the DataContractSerializer, but this serializes anything to underlying XML right … which must increase the memory footprint.
What's the fastest serializer for sending objects across my LAN? I don't care a about interop or versioning …. I need speed!
I am open to third-party open source alternatives.

A: I have some benchmarks for the leading .NET serializers available based on the Northwind dataset.
@marcgravell binary protobuf-net is the fastest implementations benchmarked that is about 7x faster than Microsoft fastest serializer available (the XML DataContractSerializer) in the BCL.
Microsoft's JsonDataContractSerializer is pretty slow - over 9x slower that protobuf-net and over 3.6x slower than my own JsonSerializer.

A: In the performance comparison linked by @Luke, notice that DataContractJsonSerializer performs very well compared to the other MS serializers.
Given the ubiquity of JSON, and the ease of which you can use DataContractJsonSerializer, I don't see much reason to use "protocol buffers". JSON will be easier to debug when bouncing between languages and platforms, and it will compress beautifully.
(I love how Google takes CS 101 concepts and becomes famous for implementing them. In C, we call "protocol buffer" "struct"s. They work great.)

A: It sounds like Protocol Buffers might be what you're looking for.
There are three .NET implementations that I'm aware of: protobuf-net, protobuf-csharp-port and Proto#.
The performance comparisons show that Protocol Buffers outperform the built-in serializers in terms of both size and serialization/deserialization speed.

A: As I demonstrated in this answer the generated code might be the fastest serializer. However it is in an early stage and still lacks a couple of features that other serializers offer.


text:
Q: How can I pass value out of anonoymous function I would like to sent response from node server to client instead of greeting the return value of function Stats.calculate(), but I cannot figure out how to do it.
router.post('/calc', (req, res) => {
    request.get('a secret url api', (err,res,bodyJson) => {
        if(err) console.log('error');
        if(res.statusCode !== 200 ) console.log('error');
        Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);
    });
    res.json({greeting: "ciao"});
});

Any suggestions?

A: You can just call res.json inside the callback:
router.post('/calc', (req, res) => {
    request.get('a secret url api', (err, response, bodyJson) => {
        if(err) console.log('error');
        if(response.statusCode !== 200 ) console.log('error');
        var statsResult = Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);

        res.json({result: statsResult});
    });

});


text:
Q: Control usb PTZ camera in a browser using JavaScript I have a Logitech PTZ USB camera. I have prepared a video call functionality using WebRtc. Now what I need is to add Pan, Tilt and Zoom controls within the browser so user can controls the camera based on his need.
Is it possible to implement PTZ control using JavaScript/WebRtc or any other third-party JS?

A: Scott Hanselman wrote a PTZ controller for the Logitech cameras back in 2012: https://www.hanselman.com/blog/CloudControlledRemotePanTiltZoomCameraAPIForALogitechBCC950CameraWithAzureAndSignalR.aspx
The APIs needed for that are not available to Javascript sadly.


text:
Q: Angular + Laravel in IIS occurs CROS problem In local XAMPP server,
I can successfully make a POST request to Laravel localhost server through Angular...
Once I upload my Laravel server file in IIS-6, the Angular comes up the error for CROS...
Please tell me what should I do?
I've installed the file for rewrite_amd64.msi in IIS-6 server
Tried to build a new file and only added the CROS plunins - barryvdh/laravel with the setting for Barryvdh\Cors\ServiceProvider::class to the proper place and it still not works.

A: Found out the reason...
I need to open 'All verbs' not just only GET,POST,OPTION in the php's Module Mapping > Request Restrictions > Verbs


text:
Q: Separate resultset from hashtable into 3 tables  I am using SQL Server 2008 and have a hashtable which contains data about postcode and its related data. If I take the count of records groupby postcode its like this
5000 HA
6000 NW
4000 S2

I would like to know is there any way of devidng the data into three separate tables.
if we running the first set of records which is HA
which will look like
Table1               Table2                   Table3
1st record of HA     2nd record of HA       3rd record of HA
4th record of HA     ....etc

is it possible to achieve using cursor or any suggestion?
Any help will be appreciate
Thank you

A: I can't imagine any possible reason why I would do such a thing. Dividing up into 3 tables will make the data much harder to query later. But if you're stuck with it then I would do something along the lines of this:
BUild a mapping table with three columns A, B, C. Populate the table withthe values you want to go in each table. Shoulf look simliar to this, but woudl go out the the max value you will need.
A   B   C
1   2   3
4   5   6
7   8   9
10  11  12

Create a  temp table using row_number over (don't forget to order by) to so that you can now tell which record is the first HA and which is the second etc.  Now do 3 inserts joining on the number you generated to each column inteh mapping table. If they join to column A insert to tableA, Column B, insert totable B, colmn c insert to table c.


text:
Q: Is my explanation on prepositional phrases correct? Example: My mother is arranging flowers in the vase.
'arranging flowers' is prepositional phrase and it modifies 'in the vase' but not to modify the subject 'My mother'.

A: No Jess, that's not correct.
A prepositional phrase is a phrase with a preposition as its head. 'in the vase' is a prepositional phrase, with the preposition 'in' at its head.
In your sentence, 'arranging' is the main verb and 'flowers' is the direct object.


text:
Q: NSView dataWithPDF inside rect but with background view I wan´t to take a screenshot of a NSView but when I do this, I get an image without the background. All the subviews are show, but not the background. I use this code:
if let image = NSImage(data: background.dataWithPDF(inside: background.bounds)) {
    let imageView = NSImageView(image: image)
    imageView.imageScaling = .scaleProportionallyUpOrDown
    return NSImageView(image: image)
}

I thought, ok when I get only the subviews, then I will make a screenshot of the superview and I thried the following:
if let superview = background.superview, let image = NSImage(data: superview.dataWithPDF(inside: background.frame)) {
    let imageView = NSImageView(image: image)
    imageView.imageScaling = .scaleProportionallyUpOrDown
    return NSImageView(image: image)
}

But I get the same result. Even if I set the background color of my background view I don´t get an image without transparent background.
How can I resolve this?
thank you
Artur

A: I got an Answer:
background.lockFocus()
if let rep = NSBitmapImageRep(focusedViewRect: background.bounds){

    let img = NSImage(size: background.bounds.size)
    img.addRepresentation(rep)

    return NSImageView(image: img)
}
background.unlockFocus()

A: You could have converted the views backing layer.backgroundColor to an image. Then assign the image to a backing image view that sits in the 0th index of your views heirarchy and use the method dataWithPDF -> that will successfully capture a background.


text:
Q: How do I add a timer to my bomb defusal game in java? I want to add timer functionality to my game, can you tell me how to add a 15 second timer to the program? After the time is over I want the output to be displayed as Try Again or something. Code is below:
import java.util.Scanner;

public class Main {

 public static void main(String [] args)
    {
        rules();

        Scanner s = new Scanner(System.in);
        boolean[] cantCut = new boolean[6];

        /* 0 - white
           1 - red
           2 - purple
           3 - black
           4 - green
           5 - orange */

        boolean exploded = false;

        for(int i = 0; i <= 5 ; i++)
        {
            String input;
            input = s.nextLine();
            switch(input)
            {
            case "white":
                if(cantCut[0])
                    exploded = true;
                else
                {
                    cantCut[0] = true; //white
                    cantCut[1] = true; //red
                    cantCut[2] = false; //purple
                    cantCut[3] = false; //black
                    cantCut[4] = false; //green
                    cantCut[5] = false; //orange
                }
                break;
            case "red":
                if(cantCut[1])
                    exploded = true;
                else
                {
                    cantCut[0] = true; //white
                    cantCut[1] = false; //red
                    cantCut[2] = false; //purple
                    cantCut[3] = false; //black
                    cantCut[4] = true; //green
                    cantCut[5] = true; //orange
                }
                break;
            case "purple":
                if(cantCut[2])
                    exploded = true;
                else
                {
                    cantCut[0] = true; //white
                    cantCut[1] = false; //red
                    cantCut[2] = true; //purple
                    cantCut[3] = false; //black
                    cantCut[4] = true; //green
                    cantCut[5] = true; //orange
                }
                break;
            case "black":
                if(cantCut[3])
                    exploded = true;
                else
                {
                    cantCut[0] = true; //white
                    cantCut[1] = true; //red
                    cantCut[2] = true; //purple
                    cantCut[3] = true; //black
                    cantCut[4] = false; //green
                    cantCut[5] = true; //orange
                }
                break;
            case "green":
                if(cantCut[4])
                    exploded = true;
                else
                {
                    cantCut[0] = false; //white
                    cantCut[1] = true; //red
                    cantCut[2] = true; //purple
                    cantCut[3] = true; //red
                    cantCut[4] = true; //black
                    cantCut[5] = false; //orange
                }
                break;
            case "orange":
                if(cantCut[5])
                    exploded = true;
                else
                {
                    cantCut[0] = true; //white
                    cantCut[1] = false; //red
                    cantCut[2] = true; //purple
                    cantCut[3] = false; //black
                    cantCut[4] = true; //green
                    cantCut[5] = true; //orange
                }
                break;
            default:
                System.out.println("Please enter a correct choice");
            }
        }

        if(exploded)
            System.out.println("BOOM!, Terrorists Win");
        else
            System.out.println("Bomb Defused, Counter-Terrorists Win.");
        s.close();
}

 public static void rules() {
        System.out.println("If you cut a white cable you can't cut white or red cable.");
        System.out.println("If you cut a red cable it is not allowed to cut a white, green or orange one.");
        System.out.println("If you cut a purple cable you can't cut a purple, green, orange or white cable");
        System.out.println("If you cut a black cable you have to cut a green one.");
        System.out.println("If you cut a green one you have to cut an orange or white one.");
        System.out.println("If you cut an orange cable you should cut a red or black one.");
        System.out.println("Enter the 6 wires to be cut in the correct order to defuse the bomb:");
}

}


text:
Q: Ruby: Add a method to the class of an input parameter I'm just exploring ruby and was wondering about the theoretical possibility of adding a method to the class of an object.  For example, define a method that takes in a parameter and would add a method to the class of that parameter (not just to the parameter object itself).  Something like this example:
class SomeClass
end

class AnotherClass
end

alpha = SomeClass.new
beta = AnotherClass.new

def AddHelloMethodTo param

 # This is where I'm trying to
 # add a method to the class of the parameter
 def param.class.Hello
  "Hello"
 end

end

AddHelloMethodTo alpha
AddHelloMethodTo beta

gamma = AnotherClass.new

alpha.Hello
beta.Hello
gamma.Hello

(Excuse me if I have syntax errors / typos I'm REALLY new to this!)
Notice how I don't call the AddHelloMethodTo on gamma but I expect Hello to be defined because I added it to the class.
Is this possible?

A: This is the closest to what you had. I took the liberty of changing it to standard Ruby coding style, but notice that the only real change is the first line of add_hello_method_to_class_of:
class SomeClass; end
class AnotherClass; end

alpha = SomeClass.new
beta = AnotherClass.new

def add_hello_method_to_class_of(obj)
  obj.class.send(:define_method, :hello) do
    'Hello'
  end
end

add_hello_method_to_class_of(alpha)
add_hello_method_to_class_of(beta)

gamma = AnotherClass.new

alpha.hello
beta.hello
gamma.hello

Originally, you had
def obj.class.hello

This will work, but it doesn't do what you think it does. This will add a singleton method to the class object itself, but it appears you assume that it will add an instance method. If you want to add an instance method, you need to use Module#define_method like this:
obj.class.define_method(:hello)

Except that Module#define_method is private, so you need to use reflection to circumvent that access restriction:
obj.class.send(:define_method, :hello)

Note that I also changed the name of the method from add_hello_method_to to add_hello_method_to_class_of, since, well it doesn't add the hello method to its argument, it adds it to its argument's class.
However, if you do monkey patching like this, it is generally considered good practice to use mixins instead, since then, the mixin shows up in the object's inheritance chain, which leaves anybody debugging that code at least a fighting chance to figure out where the heck that mysterious hello method is coming from:
# file: hello_extension.rb
module HelloExtension
  def hello
    'Hello'
  end
end

def add_hello_method_to_class_of(obj)
  obj.class.send(:include, HelloExtension)
end

# some other file
require 'hello_extension'

class SomeClass; end
class AnotherClass; end

alpha = SomeClass.new
beta = AnotherClass.new

add_hello_method_to_class_of(alpha)
add_hello_method_to_class_of(beta)

gamma = AnotherClass.new

alpha.hello
beta.hello
gamma.hello

Now, you can easily debug this code:
gamma.class.ancestors
# => [AnotherClass, HelloExtension, Object, Kernel, BasicObject]

If someone wonders where the hello method is coming from, then it doesn't take much to figure out that a mixin called HelloExtension probably has something to do with it. And following standard Ruby naming conventions they even know to look in a file named hello_extension.rb
You can even do this:
gamma.method(:hello).source_location
# => ['hello_extension.rb', 3]

A: Your example (once you fix a small syntax error) adds a class method to the class instead of an instance method.
To define an instance method, you could use class_eval and define the method as if you were in the middle of defining the class:
def AddHelloMethodTo param
  param.class.class_eval do
    def Hello
      "Hello"
    end
  end
end

Now all previous and future instances of the object's class will have access to the Hello method.


text:
Q: Python update data with pymsql Hi when I update data with sql, I get a string error. Please help me.
This is  my error:
TypeError: not enough arguments for format stringimport pymysql.connect string error

My code is as follows:
db = mysql.connector.connect(user='root', password='1234', host='localhost', database='sosyalbe')
cursor = db.cursor()
cursor.execute("SELECT * FROM siparisler WHERE siparis_durum ='İptal'")

order = cursor.fetchone()
id = order[0]

dss = 10
cursor.execute("UPDATE siparisler SET urun_baslangic = '%s' WHERE order_id ='%s'" %dss % id)  #errror

cursor.execute("UPDATE siparisler SET urun_baslangic = (?) WHERE id = (?)" (dss, id))   #ERROR

please help !

A: You're missing a comma between the string and tuple of arguments. Also, note that the %ss should not be surrounded with quotes, as they are not string literals:
cursor.execute("UPDATE siparisler SET urun_baslangic = %s WHERE order_id = %s", (dss, id))


text:
Q: jQuery find the element with same tag on click i have a following scenario in my html page i want to select the attribute of the clicked element

1

2

3

4

5

6

7

8

9

10

Following is my jQuery on click

A: Your jQuery selector should be:
$('.section1 > div')

: is a filter, e.g. $('.checkbox:checked') - will select all elements with class checkbox and filter checked from the set. Read more on jQuery selectors here
Also, avoid using language attribute for your script tag, - it is approx. 10 years long as it is deprecated.

A: In your jQuery selector, replace the ':' in ':div' with a space, indicating you want to select the DIV elements.

A: .section1:div the colon is wrong. Try this:
 $(document).ready(function () {
     $('.section1 div').click(function() {
         alert($(this).attr("id"))
     });
 })

A: I don't know if this is what you mean?
$(document).ready(function () {
    $('.section1 div').click(function() {
        alert(this.id)
    })
});

But if you want to have a second selection, you can't use the same ID's.
Use this:

1

2

3

4

5

6

7

8

9

10

1

2

3

4

5

6

7

8

9

10

$(document).ready(function () {
    $('.section1 div[data-info]').click(function() {
        alert($(this).data("info") + " clicked within selection " + $(this).parent().attr("class"));
    })
});

The .section1 div[data-info] selects all DIV elements within the .selection1 which have an attribute named data-info. This can be done using the [].


text:
Q: How do I use Google Cloud APIs without the SDK? I am using the google cloud client libraries in C# and would like to if can run the release build of my project on another computer without the sdk installed. i.e just using an exe and the corresponding libraries.

A: Absolutely!  After creating your program, if you don't want the additional library dlls to be hanging around, you'll need to merge them into your exe.  By default they are just outputted into your Debug / Release directory (where the exe resides).
To merge them all together, personally I've used Fody Weaver alot, it's very simple and did everything automatically for me: https://github.com/Fody/Fody
Alternatively on big projects I've used ILMerge as well, more on that's already been answered here: Merge DLL into EXE?


text:
Q: Loading flash on selenium webdriver On my ubuntu server I can't get firefox to load any flash element though the plugin is listed as being installed. I even built the plugin manually.
Plugin listed:http://puu.sh/rz74I/2d0bfbaa07.png
Page tested on: http://www.adobe.com/software/flash/about/
The page will not load the flash element at all using selenium.
from selenium import webdriver
ff = webdriver.Firefox()
ff.get('http://www.adobe.com/software/flash/about/')
ff.save_screenshot('test.png')
ff.close()

produces a weird result, this is using Xvfb as well.


text:
Q: Handling exceptions with INSERT-EXEC with linked server stored proc and table results I am trying to capture failures for a remote (via linked server) stored procedure called within a local stored procedure. If the remote procedure fails (error connecting to server, etc) I want the return value or an indicator for this so I can capture this and log it. If it doesn't fail, I want the results which would be used within the local procedure and processed as a temp table.
DECLARE @myTable TABLE(id INT,
        TransDAte date,
        Description nvarchar(25))

INSERT INTO @myTable

select * from openquery(MyLinkedServer, 'EXEC   [MyDatabase].[dbo].[RemoteStoredProc]')

The below link is on the right track but I have two differences. One, my table is multiple fields that I need to return (In the example, @RC is a list of INTs) and I am just selecting the data to use in the local stored procedure, I do not need to commit or rollback transactions.
Handling exceptions in stored procedures called using insert-exec blocks
I have tried adding catch/try statements to both the local and remote procedures but they don't capture the failures correctly.
This doesn't seem to work:
Create PROCEDURE thisTEST
AS

DECLARE @myTable TABLE(tableid INT,
        TransDAte date,
        Description nvarchar(25))

BEGIN TRY
    INSERT INTO @myTable
     select * from openquery(MyLinkedServer, 'EXEC  [MyDatabase].[dbo].[RemoteStoredProc]')
END TRY

BEGIN CATCH
    print 'Create entry in error log table'
END CATCH

-- This doesn't work because the remote procedure failure is not captured. When the procedure fails, the sproc attempts to insert the error message into the tableid field)
Create procedure RemoteStoredProc
AS

BEGIN TRY

Select transactionid, transactiondate, myDescription from SourceTable

END TRY

BEGIN CATCH
print 'Error with getting data'

END CATCH

I tried adding an output parameter but I don't know how to execute an Insert-Exec procedure with output and/or results
Create procedure RemoteStoredProcWParam(@sprocFailed INT OUT)

AS

BEGIN TRY

Select transactionid, transactiondate, myDescription from SourceTable

SET @sprocFailed = 0

END TRY

BEGIN CATCH
Set @sprocFailed = 1
print 'Error with getting data'

END CATCH

It looks like the best option is an output parameter with a cursor to store table results but I don't think that will work either.  I am used to using SSIS but don't want to have to rewrite two entire (complicated) stored procedures. Any help would be appreciated. Thanks in advance


text:
Q: Use output of sed for a while read loop I want the while loop to ignore blank (empty) lines and lines that contain #
I tried including sed -e 's/#.*$//' -e '/^$/d' on the input file and piping this into the while loop. This did not work.
file=$(sed -e 's/#.*$//' -e '/^$/d' foo.txt)

while IFS=: read -r f1 f2 f3 f4; do

Command

done <"$file"

A: You're trying to open that output as a filename, which it almost certainly isn't.
Run sed in a subshell and redirect its output to while loop instead.
while IFS=: read -r f1 f2 f3 f4; do
    # do something
done < <(sed -e 's/#.*$//' -e '/^$/d' foo.txt)

For anyone interested in how the syntax used in this answer works, see the bash-hackers' wiki on process substitution, and for why this syntax is better than sed ... | while read ..., see BashFAQ #24.

A: You can use grep:
grep -Ev '^\s*$|^\s*#' foo.txt | while IFS=: read -r f1 f2 f3 f4; do
    Command
done

A: use grep -v:
-v, --invert-match        select non-matching lines


text:
Q: Generalizing Bienaymé's Formula Prove the general case of Bienaymé's Formula: if $X_i$, $i=1,2,...,n$, are pairwise independent random variables on a sample space $S$, then
$$V(X_1 + X_2 + ... + X_n) = V(X_1) + V(X_2) + ... + V(X_n)$$
using the fact that
$$(\sum_{i=1}^n a_i)^2 = \sum_{i=1}^n a_i^2 + 2\sum_{1 \le i \lt j \le n}a_ia_j$$
I am able to work out the proof for the case with two random independent variables as follows:
$$V(X+Y) = E((X+Y)^2) - E(X+Y)^2$$
$$=E(X^2 + 2XY + Y^2) - (E(X) + E(Y))^2$$
$$=E(X^2) + 2E(XY) + E(Y^2) - E(X)^2-2E(X)E(Y) - E(Y^2)$$
$$=E(X^2) -E(X)^2 + E(Y^2) - E(Y^2)$$
$$=V(X) + V(Y)$$
Following that model, I have
$$V(\sum_{i=1}^n X_i)$$
$$=E((\sum_{i=1}^n X_i)^2) - (E(\sum_{i=1}^n X_i))^2$$
$$=E(\sum_{i=1}^n X_i^2 + 2\sum_{1 \le i \lt j \le n}X_iX_j) - (E(\sum_{i=1}^n X_i))^2$$
But that's where I get stuck on how to proceed with the second term.

A: For example you can do like this. Let $X_{1}+X_{2}+ ... + X_{n-1}= Y$, which is independent of $X_{n}$, as it is completely defined by the means of $X_{1} , ... , X_{n-1}$.
So as you have for two. Than you'll have $Var(X_{1}+ ... +X_{n-1}+ X_{n}) = Var(Y+X_{n})= Var(Y)+Var(X_{n})$, and so on.


text:
Q: spring batch remains in EXECUTING I created a job which uses reader of type
org.springframework.batch.item.database.HibernateCursorItemReader to execute a query.
The problem is database connection in this case is hitting connection limit (I have a oracle error ORA-12519, TNS:no appropriate service handler found) and, surprisingly, I noticed exit_code=EXECUTING and status=STARTED on BATCH_STEP_EXECUTION table.
If I run again the job it will respond  "A job execution for this job is already running" and if I issue -restart on this task, it complains with message "No failed or stopped execution found for job".
How does spring batch manages these fatal failure situations? Do I have to remove these execution information manually or is there a reset option?
Thank you for any help

A: the current release of Spring Batch (2.2.0) doesn't appear to have an out of the box solution for this situation.  as discussed in this question, 'manual' intervention in the database may be required.  alternatively, if this is a particular job that is hanging (that is, you know the job name), you can do the following as well;

*

*use the JobExplorer.findRunningJobExecutions(jobName)

*go through the list of executions and 'fail' them (JobExecution.upgradeStatus(BatchStatus.FAILED))

*save the change using JobRepository.update(jobExecution)

A: Just an FYI why this problem of connection limit occurs when using a CursorItemReader (JDBCCursorItemReader or HibernateCursorItemReader)
The cursorItemReader opens a separate connection even if there is already a connection opened for the transaction (Reader -> Processors -> Writer). So, each step execution needs two connections even if it is in a single transaction and hitting the same db. This causes the connection bottleneck and so the number of db connections should be double the number of threads configured in thread pool to execute the steps in parallel.
This can also be resolve if you provide a separate connection to your CursorReader.
JdbcPagingItemReader is another implementation of ItemReader which uses the same connection opened for the transaction.


text:
Q: Issue with netstat not being specific enough and giving errors So, I have this command which stores incoming traffic to a file.
' watch -n 0 "netstat -nat | grep "22"" > log.txt '

However, the output saved in the txt file is this:
' [12dtcp[12;12H0[19G0 185.193.18.249:80[45G1.1.1.9:2024[12;69HSYN_RECV '
' [12dtcp[12;12H0[19G0 185.193.18.249:80[45G1.1.1.8:2024[12;69HSYN_RECV '

Which is a pain as I just want the source addresses saved in the file  (in this case 1.1.1.9 then new line 1.1.1.8). And for it to only log save new_syn connections (not established too).
Is it possible to use netstat and do this? Thanks a lot guys.
Ps. I have spent hours trying to research this but am having 0 luck!


text:
Q: Automapper Ignore complex properties Im using Automapper v6.2 with profiles and Autofac to register those profiles, my Domain classes have properties that my Models does not have as I dont need them (For example an Id or other properties that only needs to be saved on my dB)
For example:
public class TurnoProfile : Profile
{
    public TurnoProfile()
    {
        CreateMap<Turnos, TurnoModel>()
            .ForMember(d => d.Id, s => s.MapFrom(src => src.Id))
            .ForMember(d => d.Descripcion, s => s.MapFrom(src => src.Descripcion));

        CreateMap<TurnoModel, Turnos>()
            .ForMember(d => d.Id, s => s.MapFrom(src => src.Id))
            .ForMember(d => d.Descripcion, s => s.MapFrom(src => src.Descripcion))
            .ForMember(d => d.Alumnos, s => s.Ignore());
    }
}

Domain object (EF 5)
public partial class Turnos
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Turnos()
        {
            Alumnos = new HashSet<Alumnos>();
        }

        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        public string Descripcion { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Alumnos> Alumnos { get; set; }
    }

Model:
public class TurnoModel
{
    #region Fields
    public int Id { get; set; }
    public string Descripcion { get; set; }
    #endregion
}

As you can see I dont want Alumnos to be mapped, this is a 1 to many relationship, I want to ignore which Alumnos have certain Turnos.
But I have the following error:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
============================================================
TurnoModel -> Turnos (Destination member list)
Prog_II.Data.Model.TurnoModel -> Prog_II.Data.Domain.Turnos (Destination member list)

Unmapped properties:
Alumnos


text:
Q: how to get data from mysql in php based on url? i have a page table in mysql db with 'page_name', 'title', content, 'author' fields. I want to get it with php like http://www.domain.com/index.php?page=page_name . How do i do it ? pls help

A: Access the GET parameter using the super global $_GET array:
$pagename = $_GET['page'];

Then write a query for the database. Note that you have to escape every data that comes from the outside:
$sql = "SELECT * FROM page_table WHERE page_name = '%s' LIMIT 1";
$sql = sprintf(%sql, mysql_real_escape_string($pagename));

Then execute the query and check that it worked.
$result = mysql_query($sql);
if(!$result) {
    // error occured
}

Use the function mysql_fetch_assoc to access the data:
$data = mysql_fetch_assoc($result);

You can now access all data in this asscociative array:
echo $data["title"];

A: *

*Connect to the database server and select a datbase (e.g. using mysql_connect and mysql_select_db)

*Create a SQL query using values from the $_GET array

*Send the query to the database (e.g using mysql_query)

*Retrieve the result (e.g. using mysql_fetch_array)

*Display the data from the result (e.g. using echo)

A: You could do something like this:
<?php
   // get page
   $page_name = $_GET["page"];

   // Do the query
   $q = mysql_query("SELECT * FROM `pages_table` WHERE `page_name` LIKE '$page_name'");
   // loop the get the results
   while($result = mysql_fetch_assoc($q){
       $db_title = $result["title"];
       $db_content = $result["content"];
       $db_author = $result["author"];
   }

   //put the data together and echo
   echo "

$db_title

$db_content

Author: $db_author

   ";

?>

Dont forget to connect to the db first! And do some checks on the $_GET[] for sql injections!!
EDIT
Depends on your php installation. If you don't have magic quotes enabled you could do something like $page_nameClean = addslashes($page_name); when you do a query or if you know that you are only going to use numbers to get the page (ex: domain.com?page=1232) you could do a check:
if(is_numeric($page_name)){
   // get the page out of the DB
}else{
   // Show an error message
}

Or have a look at this: avoid code injections


text:
Q: How do I read the following arrow function How can I read the following arrow function in English?  I can understand that there are 2 parameters namely dispatch and getState.  How do I read the remaining part?
How to write it as a normal function?
    const apiMiddleware = ({ dispatch, getState}) => next => action => {

A: Written as a normal function, the declaration will look like this:
const apiMiddleware = function({ dispatch, getState}){
 return function(next) {
    return function(action) {
      return something;
  }
 }
}

I suggest you to read this great article about higher order arrow functions here

A: I hope you find this response useful.
let squarevalue = input => { input * input }

let multiplyvalue = (input, multiplier) => { input * multiplier }

A: This is what it might look like if it were written in es5 syntax

var apiMiddleware = function apiMiddleware(_ref) {
  var dispatch = _ref.dispatch;
  var getState = _ref.getState;
  return function (next) {
    return function (action) {
      console.log('action function body');
    };
  };
};

A: Writing this:
const apiMiddleware = ({ dispatch, getState}) => next => action => {

As a normal function (by normal I mean no arrows):
const apiMiddleware = function({dispatch, getState}) {
    return function(next) {
        return function(action) {
            //Rest of the code
        }
    }
}

And here's how you'd write it in ES5:
var apiMiddleware = function(data) {
    var dispatch = data.dispatch;
    var getState = data.getState;
    return function(next) {
        return function(action) {
            //Rest of the code
        }
    }
}

A: That's one of the ES6 nice features called object destructuring. This one is also interesting and may be related to your code in question:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators
Try pasting the code into this and see the transformed script as vanilla JS: https://es6console.com/

A: you can use the following babel compiler to convert the es6 code into es5 -
babel compiler


text:
Q: Stuck on Unpivot / Pivot Combo SQL Server 2008 I can't seem to get my head around this problem where I think I need a combination of pivot and unpivot in SQL Server 2008:
I have a table as follows:
Sale       | Month | Count  | Budgeted | Actual
------------------------------------------------
NewSale    | 1     | 120    | 45.23    | 50.10
NewSale    | 2     | 30     | 3.10     | 1.2
NewSale    | 3     | 70     | 45.00    | 100.32

I need to pivot so that the months are as columns, but unpivot so I get the Count, Budgeted, Actual as rows, so it is like so...
Type      | 1      | 2     | 3
-----------------------------------
Count     | 120    | 30    | 70
Budgeted  | 45.23  | 3.10  | 45.00
Actual    | 50.10  | 1.2   | 100.32

I've tried this so far, but I can't work out how to put the pivot in there:
select
 *
from YTD
pivot
(
    sum([Count]), sum([Budgeted]), sum([Actual])
    for [Month] in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
)
as figures

This gives me a syntax error as you can't have more than one calculation in the pivot (as far as what I understood from the error.
Help!!!

A: declare @T table
(
  Sale varchar(10),
  [Month] int,
  [Count] int,
  Budgeted money,
  Actual money
)

insert into @T values
('NewSale',     1,      120,     45.23,     50.10),
('NewSale',     2,      30,      3.10,      1.2),
('NewSale',     3,      70,      45.00,     100.32)

select [Type], [1], [2], [3]
from
(
  select [Month],
         cast([Count] as money) as [Count],
         Budgeted,
         Actual
  from @T
) as T
unpivot
(
  Value for [Type] in ([Count], Budgeted, Actual)
) as U
pivot
(
  sum(Value) for [Month] in ([1], [2], [3])
) as P

Try on SE-Data.

A: You need to do 3 selects and union the result to get a table that looks like that.
For example
  Select 'Count' as [Type], 120 AS 1, 40 AS 2, 70 AS 3
  UNION ALL
  Select 'Budgeted' as [Type], 45.23 AS 1, 3.10 AS 2, 45.00 AS 3
  UNION ALL
  Select 'Actual' as [Type], 50.1 AS 1, 1.2 AS 2, 100.32 AS 3

Will look like your example
So just replace each of those selects with a piviot that returns the row you want and you GTG


text:
Q: Law of Quadratic Reciprocity Equivalent Statement
Let $p,q$ be two distinct odd primes. Then $(\frac{q}p)=1 \iff p=\pm\beta^2 \pmod{4q}$ for some odd $\beta$. Show that this statement is eqivalent to the Law of Quadratic Reciprocity.

I'm trying to grapple with what the question is actually asking me to show.
Do I split into various cases of what $p$ and $q$ could possibly be (ie. $1 \pmod 4$ and $3 \pmod 4$) and then show that in each case, the statement holds?

A: We do one of the four cases. Because $p$ and $q$ both of the shape $4k+1$ is "too easy" and does not fully illustrate the problems we can bump into, we deal with the case  $p$ of the form $4k+3$ and $q$ of the form $4k+1$.
Suppose that $(q/p)=1$, with $p$ of the form $4k+3$ and $q$ of the form $4k+1$. We want to show that $p\equiv \pm \beta^2\pmod{4q}$ for some odd $\beta$.
Note that by Quadratic Reciprocity we have $(p/q)=1$. So $p$ is a quadratic residue modulo $q$. This means that $p\equiv \alpha^2\pmod{q}$ for some $\alpha$.  But $-1$ is a quadratic residue of $q$, since $q$ is of the form $4k+1$. So $-1\equiv \gamma^2\pmod{q}$ for some $\gamma$, and therefore
$$p\equiv -(\alpha\gamma)^2\pmod{q}.$$
Without loss of generality we may assume that $\alpha\gamma$ is odd. If it isn't,  replace it by $q-\alpha\gamma$.
Since the square of an odd number is congruent to $1$ modulo $4$, we have  $$p\equiv -(\alpha\gamma)^2\pmod{4}.$$
It follows that $p\equiv -(\alpha\gamma)^2\pmod{4q}$.
The reverse direction is straightforward. Reverse directions are not really needed if we deal with the "forward" direction in all four cases.

A: This an approach through which you have not to split into cases, but have to be more careful.
The canonical, or traditional, reciprocity law is: Let $p, q$ be primes. Then $$(\frac{q}p)=(\frac{p}q)(\frac{-1}q)^{\frac{p-1}{2}}$$.
Now, if $p\equiv \pm \beta^2\pmod {4q}$, then $(\frac{q}p)=(\frac{\pm1}q)(\frac{-1}q)^{\frac{p-1}{2}}$, where the sign is determined by $\pm p\equiv 1\pmod 4$, i.e. $\pm1=(-1)^{\frac{p-1}{2}}$. Hence it follows that $(\frac{q}p)=1$. Conversely, if $(\frac{q}p)=1$, then $(\frac{p}q)=(\frac{-1}q)^{\frac{p-1}{2}}$, so $(\frac{(-1)^{\frac{p-1}{2}}p}q)=1$, namely, $p\equiv\pm\beta^2\pmod {4q}$.
Also, we have to travel back in this directin. That is, we have to show that, if our statement holds, then so does the traditional statement. So, let us see what our statement means: $p\equiv \pm\beta^2\pmod{4q}$ means that $(-1)^{\frac{p-1}{2}}p\equiv \beta^2 \pmod{q}$, or, equivalently, $(\frac{(-1)^{\frac{p-1}{2}}p}q)=1$. But his is nothing else than our traditional law.

Conclusion:
  This particular formulation needs barely any errort to verify its equivalence with the classical one, once one realizes how the plus or minus sign in the statement is determined by $p$.

Barring errors. Thanks in advance.

A: Just to show that I'm on the right track, I'll try solving the easier case and hopefully somebody can check it for me.
Suppose that $(q/p)=1$, with $p$ of the form $4k+1$ and $q$ of the form $4k+1$. We want to show that $p\equiv \pm \beta^2\pmod{4q}$ for some odd $\beta$.
Note that by Quadratic Reciprocity we have $(p/q)=1$. So $p$ is a quadratic residue modulo $q$. This means that $p\equiv \alpha^2\pmod{q}$ for some $\alpha$.  But $1$ is a quadratic residue of $q$. So $1\equiv \gamma^2\pmod{q}$ for some $\gamma$, and therefore
$$p\equiv (\alpha\gamma)^2\pmod{q}.$$
Without loss of generality we may assume that $\alpha\gamma$ is odd. If it isn't,  replace it by $q-\alpha\gamma$.
Since the square of an odd number is congruent to $1$ modulo $4$, we have  $$p\equiv (\alpha\gamma)^2\pmod{4}.$$
It follows that $p\equiv (\alpha\gamma)^2\pmod{4q}$.
(I suppose we can just take $\gamma=1$ here?)


text:
Q: merging list of multiple data frames I'm trying to merge all the data frames in my current environment into one data frame, initially I tried
Reduce(function(x,y) merge(x,y,by="Date"),list(ls()))

But this didn't work, just returning the a list of data frame names.
I know it will work if I do
Reduce(function(x,y) merge(x,y,by="Date"),list(df1,df2,df3....))

But why doesn't the initial attempt work?
Both
typeof(list(ls()))
typeof(list(df1,df2,df3))

Return type "list"
What can I do if there are so many data frames I can't input them all into the Reduce function?

A: Try this:
lst = lapply(Filter(function(x) class(get(x))=='data.frame', ls(env=globalenv())), get)
Reduce(function(x,y) merge(x,y,by="Date"),lst)


text:
Q: .NET ODATA - XML Serializer - Deserialize nested objects I have the following XML
<?xml version="1.0" encoding="UTF-8"?>
<feed xml:base="xxx" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns="http://www.w3.org/2005/Atom">
    <id>xxx</id>
    <title>xxx</title>
    <updated>2018-02-12T11:33:38.737Z</updated>
    <link href="xxx" rel="self" title="xxx"></link>
    <entry>
        <id>xxx</id>
        <category term="xxx" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"></category>
        <title></title>
        <updated>2018-02-11T22:04:10.990Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:ID m:type="Edm.Int64">123456789</d:ID>
                <d:AutoNumber m:type="Edm.Int64">313800</d:AutoNumber>
            </m:properties>
        </content>
    </entry>
    <entry>
        <id>xxx</id>
        <category term="xxx" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"></category>
        <title></title>
        <updated>2018-02-11T22:04:10.990Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:ID m:type="Edm.Int64">987654321</d:ID>
                <d:AutoNumber m:type="Edm.Int64">313800</d:AutoNumber>
            </m:properties>
        </content>
    </entry>
</feed>

I want to Deserialize this XML and store the data on SQL Server using the following models;
[XmlType(TypeName = "feed", Namespace = "http://www.w3.org/2005/Atom")]
public class Feed
{
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "updated")]
    public DateTime? Updated { get; set; }

    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "entry")]
    public List<Entry> Entries { get; set; }

    public Feed()
    {
        Entries = new List<Entry>();
    }
}

public class Entry
{
    [XmlElement(ElementName = "ID")]
    public long? ID { get; set; }

    [XmlElement(ElementName = "AutoNumber")]
    public long? AutoNumber{ get; set; }
}

I use the following method;
public void LoadXml()
{

    XmlSerializer serializer = new XmlSerializer(typeof(Feed), "http://www.w3.org/2005/Atom");

    using (StreamReader sr = new StreamReader("myfile.xml"))
    {
        Feed readFeed = serializer.Deserialize(sr) as Feed;
        foreach(var entry in readFeed.Entries)
        {
            System.Console.WriteLine(entry.ID);
            System.Console.WriteLine(entry.AutoNumber);
        }
        Console.WriteLine(readFeed.Updated);
    }
}

The Feed class gets mapped correctly, the entry class is not mapped correctly as it sits inside the "content type" and "m:properties" tags. How can I map the  properties ID and AutoNumber to the Entry Class?


text:
Q: frame-based counters or timers? I have this frame-based counter I use instead of the timer-class because everything in my game is frame-based. This counter ensures that everything runs fine even when used on old computers.
I would like to know if it makes sense to create a tenth-second-frame-based-counter (or even a twentieth-second-frame-based counter). Basically it would be nearly the same counter like the one below except for the fact that the framesPerSecond-variable is divided by 10 or 20 and instead of using seconds I use tenthsesonds or twentiethseconds.
Is that a good or bad idea? Is there basically a difference between frame-based counters and timers when used on old computers?
I'm not sure about this topic therefore I ask.
{
import flash.events.*;

public class BasicFrameTimer extends EventDispatcher
{
    public static const TIME_IS_UP:String = "timesup";
    public var countUp:Boolean = false;
    public var min:int = 0;
    public var max:int;
    public var maxSet:Boolean = false;
    public var seconds:int;
    private var frameCount:int;
    public var started:Boolean = false;
    private var framesPerSecond:int;

    public function BasicFrameTimer(framesPerSecond:int) {
        this.framesPerSecond = framesPerSecond;

    }

    public function start():void {
        frameCount = 0;
        started = true;
    }

    public function stop():void {
        started = false;
    }

    public function reset():void {
        if (countUp) {
            seconds = 0;
        } else {
            seconds = max;
        }
    }

    public function update():void {

        if (started) {
            frameCount++;
            if (frameCount > (framesPerSecond)) {
                frameCount = 0;

                if (countUp) {
                    seconds++;

                    if (maxSet == true && seconds == max) {
                        stop();
                        dispatchEvent(new Event(TIME_IS_UP));
                    }
                } else {
                    seconds--;
                    if (seconds == min) {
                        stop();
                        dispatchEvent(new Event(TIME_IS_UP));
                    }
                }
            }

        }

    }

}
}

A: There is a difference between a Timer and using a frame event with implications for how the stage is updated, not just on old computers.
You can set the suggested frames-per-second settings as part of the .fla file, and the compiled .swf will do its best to keep up with the suggested setting. If it can't, it starts skipping frames to keep up.
If you've defined some interactions, such as an animation, to happen on frame events, or via a frame counter, they will execute with the frames, meaning that a higher fps will cause a faster animation. If, instead, the animation relies on a timer, they will execute along with the timer.
Executing with a timer will preserve real-time interactions at the cost of some choppiness for animations. A good way to test that you've correctly implemented a timer for an update cycle is to bump the fps down to 1 or 2 and see if the animation completes within the same amount of time (±1s).
As you've tagged game-development, I'd recommend using a combination.
A cycle using Timer should be used to check input, load resources and check game state (input, load, update)
A cycle using ENTER_FRAME should be used to modify drawable assets (render)
A cycle using EXIT_FRAME should be used to unload resources (unload);
The reason for the combination is that you'll be able to perform the simple calculations on a regular time interval, but you wont waste time with any rendering-specific logic until rendering is actually necessary. Additionally, it will allow your time-critical assets to stay in sync even on slow machines.

A: The best way to achieve frame-rate independant animation is to use the getTimer() function. It returns the number of milliseconds that have elapsed since the Flash VM started.
You should only perform your screen updates once per frame.
With getTimer() you can determine the precise number of milliseconds that have elapsed since the last frame (the last screen update). Using this value, you can easily make the necessary adjustments to the display list.
For instance, using this technique, a Sprite moving at 1 pixel per 50ms could effectively move at the same speed on all systems, even if the system is only capable of updating the screen once every 500ms.


text:
Q: Probability density function $\max\{2,X\}$ Let $X$ be a random variable with a PDF $f(x)=\frac{1}{9}x^2\mathbb{1}_{(0,3)}(x)$. Find the distribution and PDF of $Y=\max\{2,X\}$ .
$F_X(t)=\int\limits_0^tf(x)dx=\int\limits_0^t\frac{1}{9}x^2dx=\frac{t^3}{27}$
$Y=\begin{cases}
                    2 &\text{for $X \in (0,2)$} \\
                    X &\text{for $X \in [2,3)$}
\end{cases}$
$F_Y(t)=\Bbb P(Y \leq t)=\Bbb P(\max\{2,X\}\leq t)=\Bbb P(2\leq t, X\leq t)= \ ?$
PDF:
$f_Y(t)=\begin{cases}
                    C &\text{for $X \in (0,2)$} \\
                    \frac{1}{9}x^2 &\text{for $X \in [2,3)$}
\end{cases}$
$\int\limits_0^2Cdt+\int\limits_2^3\frac{1}{9}t^2dt=2C+\frac{19}{27}=1$, then:
$C=\frac{4}{27}$

A: The pdf is correct and you can find the CDF as well by integrating the pdf, but if you wish to find $\Pr\{\max(X,2)\le t\}$ directly, I suggest you the following way:
$$
\Pr\{\max(X,2)\le t\}{=
\Pr\{\max(X,2)\le t|X<2\}\Pr\{X<2\}\\+
\Pr\{\max(X,2)\le t|X\ge 2\}\Pr\{X\ge 2\}
}
$$

A: First observe that Y-support is the following: $y \in[2;3]$
Then observe that $P(Y=2)=F_X(2)=\int_0^2 f(x)dx=\frac{8}{27}$
Concluding, Y-distribution is the following
$$ F_Y(y) =
\begin{cases}
0,  & \text{if $y<2$} \\
\frac{8}{27},  & \text{if $y=2$} \\
\frac{y^3}{27},  & \text{if $2<y<3$} \\
1,  & \text{if $y\geq 3$}
\end{cases}$$
As you can see the distribution function has "a jump" in $Y=2$ thus the rv is not absolutely continuous (it is a mixed distribution)
So technically the PDF (as it is defined only for continuous rv) does not exist.
Actually there is a generalization of density called "mixed density", or "mixed PDF". You can calculate it by derivating F where the variable is continuous and calculating $p(y_0)=F_Y(y_0^+)-F_Y(y_0^-)$ where Y is discrete (in your case in $Y=2$)

Here is a drawing of the transformation function. The line in red is $Y=max(2;X)$

As you can see, when $X \in (0;2]$, a mass of probability $p=\frac{8}{27}$ is concentrated in a singleton: $Y=2$. This means that the resulting Law of Y is discret in this point...in the rest of Y-support, Y is continuous being $Y=X$


text:
Q: How to find out installed versions of the .NET frameworks by using a PowerShell command? Is there a way to find out installed versions of the .NET framework by using a PowerShell command?

A: The installed .NET frameworks are listed in the registry. There is a built-in registry provider in PowerShell, so you can query it like you'd query a filesystem path:
gci "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP"


text:
Q: Перенос текста в Label from tkinter import *
root = Tk()
root.geometry('600x400')
label = Label(root, text='аааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааа',
              font='Georgia') #74
label.grid(row=0, column=0)

В переменной label хранится 74 "а", это предел (учитывая шрифт и разрешение 600x400), дальше символы уходят за экран. Так вот, помогите мне сделать так, чтобы символы не уходили за экран, а переносились на другую строку.

A: Как вариант можно получить фактическую ширину текста, посчитать примерную ширину символа, посчитать сколько символов поместится в нужной ширине окна, потом с помощью функции wrap из модуля textwrap разбить на строки и вывести текст в label еще раз:
from tkinter import *
from textwrap import wrap

root = Tk()
root.geometry('600x400')

text = 'a'*74

label = Label(root, text=text, font='Georgia')
label.grid(row=0, column=0)

# Принудительно обновляем интерфейс,
# чтобы появилось окно и можно было получить фактическую ширину текста:
root.update()

width = label.winfo_width()

if width > 600:
    char_width = width / len(text)
    wrapped_text = '\n'.join(wrap(text, int(600 / char_width)))
    label['text'] = wrapped_text

root.mainloop()

Функция wrap также корректно делает перенос по словам:

В некоторых случаях текст может выходить за границы экрана, т.к. в строке может оказаться много символов, ширина которых больше средней рассчитанной (для моноширинных шрифтов такой проблемы нет). Чтобы решить эту проблему, можно в цикле уменьшать количество символов, по которому будет проходить перенос, пока текст не станет помещаться:
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " \
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, " \
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea  commodo " \
"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse " \
"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non " \
"proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

label = Label(root, text=text, font='Georgia')
label.grid(row=0, column=0)

# Принудительно обновляем интерфейс,
# чтобы появилось окно и можно было получить фактическую ширину текста:
root.update()

if label.winfo_width() > root.winfo_width():
    # Вычисляем среднюю ширину символа
    average_char_width = label.winfo_width() / len(text)
    # Приблизительно рассчитываем количество символов, которое помещается в окне
    chars_per_line = int(root.winfo_width() / average_char_width)
    # В цикле уменьшаем это количество, пока текст не станет помещаться
    while label.winfo_width() > root.winfo_width():
        wrapped_text = '\n'.join(wrap(text, chars_per_line))
        label['text'] = wrapped_text
        root.update()
        chars_per_line -= 1

Результат без коррекции (во второй строке выход за границы окна):

Результат с коррекцией:


text:
Q: DSE 2 solr nodes, both go down when 1 is unavailable I'm currently migrating my existing SOLR cloud implementation to a Datastax Enterprise (3.2.1) Solr implementation.
I have 8 DSE nodes, 6 cassandra nodes and 2 solr nodes. When either of the solr nodes goes down, the other one also fails to do queries with the following exception:
ERROR [http-8983-98] 2013-11-22 20:03:32,447 SolrDispatchFilter.java (line 641) Error request exception: java.io.IOException: Unavailable shards for ranges: [(-6148914691236517206,-3074457345618258604], (-3074457345618258604,-2], (-9223372036854775807,-6148914691236517206], (-2,0]]
java.lang.RuntimeException: java.io.IOException: Unavailable shards for ranges: [(-6148914691236517206,-3074457345618258604], (-3074457345618258604,-2], (-9223372036854775807,-6148914691236517206], (-2,0]]
    at org.apache.solr.handler.component.CassandraHttpShardHandler.checkDistributed(CassandraHttpShardHandler.java:40)
    at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:178)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:135)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1839)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:667)
    at com.datastax.bdp.cassandra.index.solr.CassandraDispatchFilter.execute(CassandraDispatchFilter.java:176)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:359)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:155)
    at com.datastax.bdp.cassandra.index.solr.CassandraDispatchFilter.doFilter(CassandraDispatchFilter.java:139)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.datastax.bdp.cassandra.audit.SolrHttpAuditLogFilter.doFilter(SolrHttpAuditLogFilter.java:194)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.datastax.bdp.cassandra.index.solr.auth.CassandraAuthorizationFilter.doFilter(CassandraAuthorizationFilter.java:95)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.datastax.bdp.cassandra.index.solr.auth.DseAuthenticationFilter.doFilter(DseAuthenticationFilter.java:102)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.IOException: Unavailable shards for ranges: [(-6148914691236517206,-3074457345618258604], (-3074457345618258604,-2], (-9223372036854775807,-6148914691236517206], (-2,0]]
    at com.datastax.bdp.cassandra.index.solr.dht.OptimizedShardSelectionStrategy.select(OptimizedShardSelectionStrategy.java:59)
    at com.datastax.bdp.cassandra.index.solr.dht.ShardRouter.endpointsToContact(ShardRouter.java:579)
    at com.datastax.bdp.cassandra.index.solr.dht.ShardRouter.route(ShardRouter.java:184)
    at org.apache.solr.handler.component.CassandraHttpShardHandler.checkDistributed(CassandraHttpShardHandler.java:36)
    ... 29 more

I can't figure out why this happens, it should be fault tolerant right?
Anyone has some ideas how to fix this?

A: Do you have replication factor of one.  If so the error is saying that the node cannot be queried therefore complete results cannot be returned.


text:
Q: How to put custom Gradle plugins on an another projects build classpath? I have a published gradle plugin which looks something like this:
|__root
|     |
|     |
|     |__java
|     |    |__SomeJavaClass.java
|     |    |__SomeJavaClass2.java
|     |
|     |__kotlin
|          |__MyPluginClass.kts
|          |__MyTaskClass.kts
|          |__Utils.kts

I would like to include this plugin as a project in my multi project build instead of publishing it to a repo for easier developement.
This plugin has 3 Kotlin files Project A is using. MyPluginClass.kts has my own plugin class, MyTaskClass.kts has my own task class and Utils.kts contains only kotlin functions. The java classes are used in MyPlugin and MyTask.
It is being put on Project A's build.gradle.kts classpath as
classpath("com.my:custom.plugin:version")

A very simplified project structure I would like to achieve:
root
|
|__Project A
|     |
|     |__build.gradle.kts
|     |__x.gradle.kts
|     |__y.gradle.kts
|     |__settings.gradle
|
|__Project build-logic
|     |
|     |__build.gradle.kts
|     |
|     |__java
|     |    |__SomeJavaClass.java
|     |    |__SomeJavaClass2.java
|     |
|     |__kotlin
|          |__MyPluginClass.gradle.kts
|          |__MyTaskClass.gradle.kts
|          |__Utils.gradle.kts

I'm trying to create plugins from those kotlin files and include them in my main build because i need them precompiled, but i cant seem to find a way to put them on Project A's classpath when build.gradle is running there. Is it even possible? what would be the proper solution?
I'm using gradle 7.3

A: You can combine multiple, independent, Gradle projects using composite builds. The same is also true for Gradle plugins.
Including a Gradle plugin from another directory is documented in the Testing Gradle plugins section.
So if you have a shared-build-logic project that provides a Gradle plugin with an ID my.shared-build-logic, and you want to use that in project-a.
my-projects/
├── shared-build-logic/
│   ├── src/
│   │   └── ...
│   ├── build.gradle.kts
│   └── settings.gradle.kts
└── project-a/
    ├── src/
    │   └── ...
    ├── build.gradle.kts
    └── settings.gradle.kts

Then you need to include shared-build-logic in your project-a Gradle settings file.
// my-projects/project-a/settings.gradle.kts

rootProject.name = "project-a"

pluginManagement {
  includeBuild("../shared-build-logic")
}

Now, so long as shared-build-logic correctly provides a Gradle plugin, in project-a you can reference that plugin.
// my-projects/project-a/settings.gradle.kts

plugins {
  id("my.shared-build-logic")
}

A: Finnaly figured out. I didn't create plugins from build-logic, left them as kotlin files. Since it is a separate gradle project, i can just build the project and point project A's classpath to the produced jar file like
buildscript {
    dependencies {
        classpath(files("path.to.the.jar"))
    }
}

this way i can access methods and the MyTask from Project A.
The other issue was that i wanted to apply MyPlugin like
plugins{
    id("my-plugin-name")
}

which wasnt working, i guess because it is a class. But now since i had the whole project jar on my build classpath, i can do this:
apply<my-plugin-name>()


text:
Q: Cypress assert API response with value that is generated in the API I want to assert that my api response contains one parameter that is generated in the api like an ID.
I am aware that i can't predict the value but it's possible to validate the type of the value?
For example my response payload is the following:
{
json: "request"
id: "TX8982XASA"
}
I want to assert the ID value.
To assert a return payload i use the following:
expect(response).to.have.property(key, value)
The response is the object that is returned from the API and the key = ID. In this case the value is "TX8982XASA" but since it's always generated i can't use it directly.

A: Two assertions seem appropriate to run in this instance - existence and typeof.
// property exists
expect(response).to.have.property(key)
// or
expect(response).to.have.property('id')

// property has type
expect(typeof response[key]).to.eq('string')  // whatever type it is
// or
expect(typeof response.id).to.eq('number')


text:
Q: How i can replace a value in a query using node/adonis? Actually my table users have one column called permission that stores values: 1,2 and 3.
I have this query that i return all users and i need to replace the value permissions to: 1 replace to 'Admin' 2 replace to 'Normal User' 3 replace to 'Students'
I try this way:
async index({request}) {
    const page = request.input('page')
    const pageSize = request.input('pageSize')
    const users = await User.query().paginate(page, pageSize)
    for(let i=0; i<users.rows.User;i++){
        console.log(users)
        if(users[i].rows.User.permission === 1){
            users[i].rows.User.permission = 'Admin'
        }
    }
    return users
}

But my for() is not findind the users.
How i can change this value? There's a way to do this using the lucid models?

A: Try to change you loop like :
...

users.rows.forEach((user, index, users) => { // see below
   if(user.permission === 1){
       users.rows[index].permission = 'Admin'
   }
   ...
})

return users

^ Help : is it possible to change values of the array when doing foreach in javascript?
Some information
users[i].rows.User.permission is wrong. Try it :
// Do not use .User
users.rows[i].permission


text:
Q: "the specified file was not found" error on server 2k12 when accesing Network drive In win server2012 icreate the network drive and create one folder on it i share the folder also now when i am trying to access it it showing the error "the specified file was not found"

A: Check the permissions for both the share, and the folder/file in question
Share permissions :-
Access this by Right Click folder that has been shared> properties > Sharing tab > Advanced Sharing.

Then click 'Permissions'

It is normal practice to allow everyone full permissions to the share.
NTFS (file) permissions :-
Access this by Right Click folder that has been shared> properties > security tab > 'edit' button.

add a valid domain/local user and ensure that they at least have the read and list folder contents permission.


text:
Q: Mongoose specifying an _id on upsert (Query) In my chat application, every user has a dictionary of unread messages which looks like this :
Unread Dictionary
{
    _id: // reference to their user_id,
    events: [] // array of ObjectIds
}

I want to make a mongoose findByIdAndUpdate query where ) search by ID and $push a new ObjectId into the events array.
If the document doesn't exist, I would like for it to upsert the document assigning it the _id used for the update query and initializing the array with the element being $push ed in the update query.
EDIT:
Here is an example of the query I would like to make:
Model.findByIdAndUpdate(user_id, {$push: {events: event_id}}, {upsert: true}, function (err, updatedDoc) {});
If the document doesn't exist and it decides to upsert, will it use the user_id I used to search to assign the _id on the upserted document? OR will mongo assign it's own _id? I'm looking for something that does the former.

A: The question is too long, but I hope my answer will help someone. We can use $setOnInsert to specify field only used on insert:
const idUsedOnInsert = new mongoose.Types.ObjectID();

const document = await Model.findByIdAndUpdate(
      user_id,
      { $push: { events: event_id }, $setOnInsert: { _id: idUsedOnInsert } },
      { upsert: true }
    );

if(document){
    console.log('Update');
} else {
    console.log('Insert');
}

A: Mongoose will use the _id you passed as the object _id when upserting.
You can try that on your console.
Create an ObjectId: const id = ObjectId(),
then query with <Model>.findByIdAndUpdate(id, { name: 'Albert' }, { upsert: true }).
And also, if you want to receive the object when it's upsert, you need to pass new: true within the query options, or else you will receive null for upserts*
*that's because by default, mongoose/MongoDB returns the find query's result instead the update's result, if you'd have queried an update on an existing object, you'd receive the old object in case you didn't pass the new: true option.
https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option


text:
Q: In Entity Framework, how do I create an Association Property in code? I would like to create an Association Property with the following setup:
public class ClassType1{
    [Key]
    public int type1_ID { get;set; }
    public int type2_ID { get;set; }  // In database, this is a foreign key linked to ClassType2.type2_ID
    public ClassType2 type2Prop { get;set; }
}

public class ClassType2{
    [Key]
    public int type2_ID { get;set; }
}

My problem is that type2Prop can't find it's foregin key.  It is trying to look for "type2Prop_ID", which does not exist, when it should really be looking for "type2_ID".  Here is the error I get:
{"Invalid column name 'type2Prop_ID'."}

How do I tell it which property to use as ClassType2's key?

A: Try a ForeignKeyAttribute on type2Prop:
using System.ComponentModel.DataAnnotations.Schema;

public class ClassType1
{
  [Key]
  public int type1_ID { get; set; }

  public int type2_ID { get; set; }  // In database, this is a foreign key linked to ClassType2.type2_ID

  [ForeignKey("type2_ID")]
  public virtual ClassType2 type2Prop { get; set; }
}

public class ClassType2
{
  [Key]
  public int type2_ID { get;set; }
}

You can also do it using the Fluent API in a refactor-proof way (i.e. if you change the name of your property in the future, the compiler will let you know you have to change the mapping as well).  It's a bit uglier for simple cases like this, but it's also more robust.  In your DbContext class, you could add something like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<ClassType1>().HasRequired(x => x.type2Prop)
                                   .WithMany()
                                   .HasForeignKey(x => x.type2_ID);
}

A: public class ClassType1{
    [Key]
    public int type1_ID { get;set; }
    [ForeignKey("type2Prop")]
    public int type2_ID { get;set; }  // In database, this is a foreign key linked to ClassType2.type2_ID
    public ClassType2 type2Prop { get;set; }
}

public class ClassType2{
    [Key]
    public int type2_ID { get;set; }
}


text:
Q: Exceptions in Hbase Region Server I continuously see these logs getting printed in hbase region server logs.
10.0.5.133 is the machine where hbase java client is present.
It keeps on disconnecting and connecting. Any reason why this is happening ?
Any mismatch in client library /server version ? Any other reason ? I tried to google this but could not found any helpful link.
2015-12-25 20:24:03,210 DEBUG [RpcServer.reader=9,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54538 because read count=-1. Number of active connections: 30
2015-12-25 20:24:03,213 DEBUG [RpcServer.reader=2,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54564 because read count=-1. Number of active connections: 29
2015-12-25 20:24:08,350 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:54642; # active connections: 26
2015-12-25 20:24:18,358 DEBUG [RpcServer.reader=8,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54642 because read count=-1. Number of active connections: 29
2015-12-25 20:24:30,543 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:54799; # active connections: 28
2015-12-25 20:24:40,547 DEBUG [RpcServer.reader=0,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54799 because read count=-1. Number of active connections: 29
2015-12-25 20:24:41,870 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:54864; # active connections: 29
2015-12-25 20:24:51,877 DEBUG [RpcServer.reader=8,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54864 because read count=-1. Number of active connections: 28
2015-12-25 20:25:00,634 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:54982; # active connections: 27
2015-12-25 20:25:10,645 DEBUG [RpcServer.reader=6,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:54982 because read count=-1. Number of active connections: 30
2015-12-25 20:26:30,169 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55511; # active connections: 26
2015-12-25 20:26:40,176 DEBUG [RpcServer.reader=3,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55511 because read count=-1. Number of active connections: 32
2015-12-25 20:26:41,117 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55594; # active connections: 30
2015-12-25 20:26:44,607 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55623; # active connections: 31
2015-12-25 20:26:51,129 DEBUG [RpcServer.reader=7,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55594 because read count=-1. Number of active connections: 26
2015-12-25 20:26:54,614 DEBUG [RpcServer.reader=2,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55623 because read count=-1. Number of active connections: 23
2015-12-25 20:27:01,926 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55731; # active connections: 31
2015-12-25 20:27:11,938 DEBUG [RpcServer.reader=5,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55731 because read count=-1. Number of active connections: 29
2015-12-25 20:27:14,711 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55776; # active connections: 28
2015-12-25 20:27:24,719 DEBUG [RpcServer.reader=3,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55776 because read count=-1. Number of active connections: 28
2015-12-25 20:27:36,791 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:55938; # active connections: 24
2015-12-25 20:27:45,008 DEBUG [RpcServer.listener,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: connection from 10.0.5.133:56013; # active connections: 27
2015-12-25 20:27:46,799 DEBUG [RpcServer.reader=4,port=60020] ipc.RpcServer: RpcServer.listener,port=60020: DISCONNECTING client 10.0.5.133:55938 because read count=-1. Number of active connections: 29

A: Looks like the client connection load is way more than default max client connection limit of 30. You might want to consider bumping up that configuration.
Here's more information: http://archive.cloudera.com/cdh/3/hbase-0.90.1-cdh3u0/configuration.html

hbase.zookeeper.property.maxClientCnxns
Property from ZooKeeper's
  config zoo.cfg. Limit on number of concurrent connections (at the
  socket level) that a single client, identified by IP address, may make
  to a single member of the ZooKeeper ensemble. Set high to avoid zk
  connection issues running standalone and pseudo-distributed.
Default: 30


text:
Q: Can we add two different NSOperations under didFinishLaunchingWithOptions I have been trying these for past two days and getting stuck at same point.
I really would appreciate any help in this.
Is it possible to add two different NSOperations while loading the applications under didFinishLaunchingWithOptions.
Like I have two different XML URL which parses the data and uses NSOperation to add the data in DB.
Currently, when I parse two different URLs and use NSOperations, the first NSOperationQueue has the elements from the first URL meaning it is not releasing after it finishes.
Can any one help me in this ?
Sagos

static NSString *string1 = @"abc.com/abc1.xml";;
NSURLRequest *URL1 =[NSURLRequest requestWithURL:[NSURL  URLWithString:string1]];
self.URL1Connection =[[[NSURLConnection alloc] initWithRequest:URL1 delegate:self] autorelease];
static NSString *string2 = @"abc.com/abc2.xml";;
NSURLRequest *URL2 =[NSURLRequest requestWithURL:[NSURL URLWithString:string2]];
self.URL2Connection =[[[NSURLConnection alloc] initWithRequest:URL2 delegate:self] autorelease];

A: @fluchtpunkt:
I have two different XML URLs which has data in each one of them which I populate separately. Both the XML File structure are different and hence I have two different NSOperations to parse through the file and add them in their database.
I am not sure how to add the NSOperation in my viewcontroller which if possible will be of great help, since I am have two different View Controllers for both the URLs.

A: Ok, to prevent more not-answers and red dots by you I'll write a general workflow.
Here is how I would solve this problem. I would create a NSOperation that does both downloading and parsing. And I would ignore the "NSOperation + Networking = You're doing it wrong!"-Sayers for now.
Create a NSOperation with a url and a delegate (this could be the viewcontroller which will show the data), do a synchronous fetch of the data (i.e. NSData *data = [NSData dataWithContentsOfURL:url];) Then parse the data when it's there. And when it's done you tell the delegate that the data is ready.
This will eliminate the slightly more complex task to distinguish between an arbitrary number of xml downloads. Because (I think) this was your problem. You've added two NSOperations to the queue when one of them was finished. So the other one was running with incomplete data. And if I had to make a guess I would say you mixed the downloaded data of both too.
Add the NSOperationQueue to you appDelegate and add the NSOperations to this queue.

As a side-note, when you have comments or additions to your question you should put them in the question. Answers are for answers to the question only. If you want to post more than once, and like the dialogue with other developers you should have a look at a forum. For example this or this but there are many more. But they usually suck, and nobody (exaggeration) gives good answers there because nobody want's to read 50 posts on 3 pages to get the picture. That's why we try to put everything relevant into the question. It's much easier for people who want to answer your question.
So next time if somebody asks for more information or code please edit the question and add the information there. You should never post an answer if you don't answer the question.


text:
Q: Steam app data files using twice the expected disk space on Mac OS Monterey My son wanted a game from steam, which said it required 40GiB disk space. Sure, done. Installed, but I noticed it was using 80GiB disk space, but didn't think much of it, until it decided to auto-patch and ran out of disk space.
Digging into the install, there's a single file, as reported by the Finder & ls, that is ~37GiB in size. It is using ~75GiB disk space according to the Finder and du.
sh$ pwd
/Users/zz/Library/Application Support/Steam/steamapps/common/Tropico 6/Tropico6.app/Contents/UE4/Tropico6/Content/Paks
sh$ ls -l pakchunk0-MacNoEditor.pak
-rwxr-xr-x  1 zz  staff  40001130623 31 Mar 17:12 pakchunk0-MacNoEditor.pak
sh$ du -k pakchunk0-MacNoEditor.pak
78127216        pakchunk0-MacNoEditor.pak
sh$ ls -lh pakchunk0-MacNoEditor.pak
-rwxr-xr-x  1 zz  staff    37G 31 Mar 17:12 pakchunk0-MacNoEditor.pak
sh$ du -h pakchunk0-MacNoEditor.pak
 75G    pakchunk0-MacNoEditor.pak

Searching around, I see mention of timemachine snapshots (tmutil listlocalsnapshots shows none), sparse files (no, they generally show the opposite, large eof and small usage), APFS compression (stat -f %f pakchunk0-MacNoEditor.pak returns zero, and afscexpand does nothing).
What could this be? A bad fallocate(2) by steam (does Mac OS X even have that)? A copy of the file in another logical fork? Multiple write heads leading to some weird internal fragmentation? Something else? What weird thing has Apple managed to do this time?
So, the question is, what could possibly cause a 40GB file to require 80GB on Mac OS X? Is this an APFS bug?
PS: fwiw, a Duplicate+Delete+Rename in the Finder fixed this one file (ie. released 40GB disk space), and I assume thanks to the APFS clone functionality, did so without copying any data. And on a second attempt, I noticed that just doing the duplicate released the space.