text:
Q: CTE to loop until next TextData field present Afternoon All,
Apologies immediately. I'm new to using CTE's and they still confuse the pickle out of me.
I'm currently working through some SQL Traces to identify an issue with an API call to our SQL environment and which suspect is causing an extensive delay.
I need to be able to identify how long each query ran for and what Statement Types were occurring. However, The query exists in an RPC:Starting Line (EventClass 11) and the duration/Statement types (ObjectName) exists in a QLTransaction line (EventClass 50) that occurs after the EventClass 11 line. To further complicate it i need the duration across all EventSubClasses and the Statement Type only when the EventSubClass is 0.
The following SQL Fiddle has a sample data range (I've had to redact the TextData for GDPR Purposes but each entry is distinct in this case there are dupolicates in the actual data) :- http://sqlfiddle.com/#!7/88857/4/1
The output I'm hoping to see is as follows:
RowNumber   EventClass  TextData            StartTime          ApplicationName  Duration    EndTime     EventSubClass   ObjectName
244         11          *** REDACTED 1 ***  18/06/2018 12:14   (null)           (null)      (null)      (null)          (null)
245         11          *** REDACTED 2 ***  18/06/2018 12:14   (null)           34791       (null)      (null)          CREATE TABLE, INSERT, sort_init, sort_init, DROPOBJ, FCheckAndCleanupCachedTempTable
258         11          *** REDACTED 3 ***  18/06/2018 12:14   (null)           (null)      (null)      (null)          (null)
261         11          *** REDACTED 4 ***  18/06/2018 12:14   (null)           (null)      (null)      (null)          (null)
262         11          *** REDACTED 5 ***  18/06/2018 12:14   (null)           (null)      (null)      (null)          (null)
263         11          *** REDACTED 6 ***  18/06/2018 12:14   (null)           12402       (null)      (null)          sort_init, sort_init
268         11          *** REDACTED 7 ***  18/06/2018 12:14   (null)           (null)      (null)      (null)          (null)

Many Thanks in advance


text:
Q: ENOTFOUND issue on https get request In my application I'm trying to hit an end point using https and then getting the response.
Route file:
router.get("/get-details", (req, res) => {
  sampleController.getDetails()
    .then((data) => {
      console.log("Data is ", data);
      res.send(data);
    })
    .catch(() => {
      res.status(500).json({
        success: false,
        data: null,
        message: "Failed to lookup the data",
      });
    });
});

Controller file:
const getDetials = () => {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: "https://jsonplaceholder.typicode.com/",
      path: "posts",
      method: "GET",
    };

    const req = https.request(options, (res) => {
      console.log(`statusCode: ${res.statusCode}`);

      res.on("data", (d) => {
        process.stdout.write(d);
      });
    });

    req.on("error", (error) => {
      console.log("Error is ", error);
      reject(error);
    });

    req.end();
  });
};

I am getting this error:

Not sure where I'm making the mistake. Does somebody know what I'm getting wrong here?

A: Try setting up the URL without the protocol and add / in front of the path in options object:
 const options = {
      hostname: "jsonplaceholder.typicode.com",
      path: "/posts",
      method: "GET",
    };

Full example:
const getDetials = () => {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: "jsonplaceholder.typicode.com",
      path: "/posts",
      method: "GET",
    };

    const req = https.request(options, (res) => {
      console.log(`statusCode: ${res.statusCode}`);

      res.on("data", (d) => {
        process.stdout.write(d);
      });
    });

    req.on("error", (error) => {
      console.log("Error is ", error);
      reject(error);
    });

    req.end();
  });
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating custom pins for iPhone Mapkit I am trying something a little different.
Instead of a class, I have used MKPinAnnotationView and the inherited image instance. Here is the code for viewForAnnotation. But it doesn't work. Nothing shows at all.
I also tried it using MKAnnotationView and I get the same result.
- (MKAnnotationView *)mapView:(MKMapView *)eMapView viewForAnnotation:(id <MKAnnotation>)annotation {

    int postTag = 0;

    MKAnnotationView *pinView = (MKAnnotationView*)[eMapView dequeueReusableAnnotationViewWithIdentifier:@"Pin"];

    if(pinView == nil) {

        pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"];
        pinView.frame = CGRectMake(0, 0, 25, 25);

    } else {

        pinView.annotation = annotation;

    }

    pinView.image = [UIImage alloc];

    NSString *data_annotation = [annotation getData];

    if([data_annotation length] == 0) {
        pinView.image = [UIImage imageNamed:@"pinYellow.png"];
    //  pinView.pinColor = MKPinAnnotationColorGreen;
    }
    else if(([[data_annotation rangeOfString:@"GRAY"].location != NSNotFound)){
            pinView.image = [UIImage imageNamed:@"pinGray.png"];
    //  pinView.pinColor = MKPinAnnotationColorPurple;
    }
    else {
        pinView.image = [UIImage imageNamed:@"pinRed.png"];
    //  pinView.pinColor = MKPinAnnotationColorRed;
    }

    // Set up the Right callout
    UIButton *myDetailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    myDetailButton.frame = CGRectMake(0, 0, 23, 23);
    myDetailButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    myDetailButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [myDetailButton addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

    // Identify which pin is being selected
    if ([[annotation title] isEqualToString:@"Current Location"]) {
        postTag = 99999;
    } else {
        postTag = [annotation getPinID];

    }

    myDetailButton.tag  = postTag;

    pinView.rightCalloutAccessoryView = myDetailButton;

    //pinView.animatesDrop = YES;

    // Set to show a callout on the pin
    pinView.canShowCallout = YES;

    return pinView;
}


text:
Q: TIFF image, tiff library for visual C++ I want to use tiff library in visual C++ for loading tiff image in the code.. but unable to do that.kindly suggest

A: the most commonly used library would be libtiff.

A: I prefer convert the tiff image to png, then read as png by the lib stb_image.
It was too complex to build the libtiff with dependencies (like zlib, jpeg, etc.). But if you do not need to deal with deflation tiff file, I think config libtiff by NuGet is a much easier solution.


text:
Q: Validate form in magento Javascript with red border in input fields I am validating my form using the following code:
var customForm = new VarienForm('load_mini_form');
This is working fine
screen-shot :
But i want to validate with red border like below image.

Thanks in advance.


text:
Q: How to tell if a file is older than 30 minutes on AIX? I'd like to write a shell script in ksh or bash which exits with 1 if a specific file is older than 30 minutes. (Last modification time is older than half hour).
It would be easy on a Linux or a modern unix, but I have to do it on AIX 5.2 version.
So the constraints:

*

*there is no -mmin -mmax options in 'find'

*there is no -d option in touch  (touch -d '30 minutes ago' temp then find ! -newer temp doesn't work)

*there is no 'stat' command

*there is no %s parameter in the 'date' command  (date +%s doesn't work)

*I'm not allowed to install any software

Could you please help  how can I do it with these constraints?

A: I can do it using just touch, test, and date. (tested on AIX 5.3.0.0)
First you need to create a file 30 minutes in the past (Unfortunately, this requires prior knowledge of the current timezone on the machine. But you may be able to work that into things if need be.)
In this example, the current timezone is EST5EDT (GMT-4). If you're lucky, the machine timezone will be set at GMT and you can just use TZ=00:30:
-bash-3.00# date
Mon 26 Mar 14:22:31 2012
-bash-3.00# touch -t `TZ=04:30 date '+%Y%m%d%H%M.%S'` foo
-bash-3.00# ls -al foo
-rw-r--r--   1 root     system            0 26 Mar 13:52 foo

Now use test to compare the dates:
-bash-3.00# test '/smit.log' -ot foo && echo 'smit.log is older than 30min'
smit.log is older than 30min

A: Use ls.
ls -l lists the last modification time of the file.
You can dissect the output with awk or cut and then parse the date.
Note that on AIX (as on most *nix systems) the format of the date provided by ls depends on how long ago the file was last modified.  See the documentation for specifics.

A: If you have the basics, bash/tsh and sed. You can write a simple script which will test the filetime associated with ls output:
#/bin/bash

LSOUTPUT=`ls -l`
IFS='
'

for f in $LSOUTPUT; do
  echo $f

  _sedout=`echo $f|sed 's/.*....-..-.. ..:\(..\).*/\1/'`

  if [ "$_sedout" -gt 30 ]; then
    echo "Passed!"
  fi

  echo
done

You will have to vary your sed regex to pull the right location, but this should work as long as you have sed. If ls doesn't provide enough detail, I believe there is a command called istat you can use.
If ksh is your shell, the syntax should be very similar to that of bash. I just used that example because I'm on Ubuntu.

A: You can still install GNU find in findutils - http://www-03.ibm.com/systems/power/software/aix/linux/toolbox/alpha.html


text:
Q: How to make the Textbox field accept only Decimal Values in jquery How to make the Textbox field accept only Decimal Values

A: Can use...
http://www.texotela.co.uk/code/jquery/numeric/

A: Try this:
        function is_int(test)
            typeof (a = (typeof test == "function" ? test() : test)) == "number" ? !(a % 1) : false;

returns:

is_int(8) // true

is_int("8") // false

function test() {
        return 12
}

is_int(test()) // true


text:
Q: Update query with inner join - use updated column value to the another column of same table I want to update one column valur from the another updated column in same table with same SQL query. There are 3 tables joined in update query as below:
UPDATE table1
     INNER JOIN table2 ON table2.id = table1.pid
     INNER JOIN table3 ON table3.id = table2.cid
SET
    table1.col1 = "1+2+3",
    table1.col2 = table1.col1 + 5
WHERE
    table1.id = 5

Any help would be appreciated

A: According to your comment, if you want the new_value to be updated in Col1 and Col2 columns, you can use the following update block
UPDATE table1
     INNER JOIN table2 ON table2.id = table1.pid
     INNER JOIN table3 ON table3.id = table2.cid
SET
    table1.col1 = new_value,
    table1.col2 = new_value
WHERE
    table1.id = 5

A: You need to specify the table in the SET statement as the fields are ambiguous.
UPDATE table1
  INNER JOIN table2 ON table2.id = table1.pid
  INNER JOIN table3 ON table3.id = table2.cid
----- (Option1 - Shifting values in a single table) -----
SET
  table1.col1 = table1.col2,
  table1.col2 = table1.col3,
  table1.col3 = table1.col4
----- (Option2 - Assigning values across tables) -----
SET
  table1.col1 = table2.col2,
  table2.col1 = table3.col2,
  table3.col1 = table1.col2
----- (Option2 - Updating values across tables) -----
SET
  table1.col1 = table1.col2 + 1,
  table2.col1 = table2.col2 - 1,
  table3.col1 = table3.col2 + table3.col1
WHERE
  table1.id = 5

NB: SET commands are done in the order listed so may you need to swop the two lines around in the set to get what you want.

SET
  table1.col2 = table1.col1 + 5,
  table1.col1 = "1+2+3"


text:
Q: Issues with manipulating an array obtained from server with web sockets I have some issues in manipulating an array obtained in the callback function in through websockets
Server side code
var io = require('socket.io').listen(app);

io.sockets.on('connection', function (socket) {
    var currentTime = new Date().getTime();
    var startTime = currentTime - (5*60*1000);
    step = 30*1000;
    var stats = [];
    stats["values"] = [1, 2, 3, 4, 3, 4, 5, 8, 2, 3, 4, 1];
    stats["start"] = startTime;
    stats["end"] = currentTime;

    socket.emit('initial', { stats: stats });
    socket.on('echo', function (data) {

    });
});

Client side code
var data;

socket.on('initial', function (stats) {
  data = stats.stats;
});

Now when I try to manipulate the data variable.Like using push and shift
data.values.push(10);
data.values.shift();

I was expecting it to have
2, 3, 4, 3, 4, 5, 8, 2, 3, 4, 1, 10
But I don't know shift operation completely removes all the elements and I get only 10 remaining in the array. What's going wrong?

A: you will get your response object {stats: stats}, but you are interested in the stats property:
var data;

socket.on('initial', function (obj) {
  data = obj.stats;
});


text:
Q: Unity license within release build I have Unity Pro license with Android support. When Unity makes a release build for a platform, how is that I know that build was made using my license ? How to know if someone is using a authentic license or hacked license ? Will such information be stored within the build ?

A:
When Unity makes a release build for a platform, how is that I know that build was made using my license.

Literally, this question doesn't make any sense.  Unity do not need to use your license to build their software.  They own the IP rights to their software, and don't require anyone's Unity license to permit them to do anything.
You probably meant to ask if your license permits you to use a specific Unity build on a particular platform.  The answer to that would be in your license agreement with Unity.  I suggest that you read the licensing FAQs, and if that doesn't answer your question, then ask an IP lawyer to provide you with an answer.

How to know if someone is using a authentic license or hacked license ?

You cannot tell if someone else is using a hacked license.  (And I don't see why you would need to know ... or why you have any right to know.)
How do you know if you are using a genuine license?  If you got it directly from Unity, then it will be genuine.  Otherwise, I guess you could ask Unity to validate your license for you ...

Will such information be stored within the build ?

Within the release build of Unity that you are using?  No!  That's not how license mechanisms work (in general).


text:
Q: Prove that the union of an increasing sequence of theories is a theory

Given the above definition, I am having troubles with proving the following proposition:

My proof goes as follows:
Take an aritary subset of expressions from the union $\bigcup_{i\in \Bbb N}^{\infty} T_{i}$. Let M denote that set. Note that M must be finite by the definition of "deductive rule". For each expression in M, there exists some $T_{n}$ for some natural number $n$ which that expression belongs to. Therefore let us take the "largest" $i$ such that $T_{i}$ is a superset of M. Since $T_{i}$ is a theory and M is a subset of $T_{i}$, then every expression deduced from the expressions in M must be in the set $T_{i}$. Now since $T_{i} \subset \bigcup_{i\in \Bbb N}^{\infty} T_{i}$, then every expression deduced from the expressions in M must be in the union.
Is my above proof correct? Can someone have a look? If that is not correct, can I please ask for a proof for the proposition? Thanks so much.

A: This is indeed correct, the property of being in the deductive closure is proved by a finite set of expressions that it is a deduction of. So if we have a chain of theories, as such an increasing sequence is called, and we have a deduction from their union $\cup_i \mathcal{T}_i$, all statements "above the line" (the premises) come from some $\mathcal{T_i}$, and we can indeed take their maximal index and find a theory among them that contains all of the premises, and thus the conclusion is in this specific theory, and hence in the union.
This hinges essentially on the fact (that a "deductive rule" or "proof") only uses finitely many premises (no infinitary proofs).
This kind of fact (the union of a chain of "blahs" is a "blah") is often a prelude to an appliation of Zorn's lemma in the poset of "blahs" and inclusion.
So in this case , Zorn's lemma would allow us to conclude that any theory is contained in a maximal theory, so that we cannot add a statement and still have a theory, so maximal in inclusion sense.


text:
Q: Место метода main() в порядке инициализации класса в Java Я - новичок в Java. И сейчас меня очень занимает вопрос инициализации класса. Я наткнулся на такое объяснение с примером на странице https://ru.stackoverflow.com/a/847576/396180:
Порядок  инициализации:

*

*Первым инициализируется статический блок инициализации класса

*Затем инициализируются блоки инициализации

*Затем вызывается метод public static void main(String[] args), который является точкой входа в приложение и в самом конце вызывается конструктор класса

Примечание.

*

*Метод, имя которого совпадает с конструктором не вызывается при
инициализации.

*Метод, имя которого main() в моем коде, но который не является
точкой входа, не вызывается при инициализации. Не является он точкой входа, потому как возвращает void и не имеет аргументов.

*Обычные статические методы не вызываются при инициализации.

*Обычные нестатические методы не вызываются при инициализации.

Пример кода:

public class InitClass {
    InitClass(){ // конструктор класса
    System.out.print(" Конструктор ");
    }
    { // блок инициализации
     System.out.print(" 3 ");
    }
    void InitClass(){// имя метода совпадает с именем конструктора но возвращает void
    // метод не вызывается при инициализации
    System.out.print(" метод InitClass ");
    }
    public static void main(String[] args) {
    System.out.print(" 2 ");
    new InitClass();
    }
    public void main(){ //- это обычный метод с именем main
     // имя метода совпадает с именем точки входа, но не имеет аргументов
    // метод не вызывается при инициализации
    System.out.print(" метод main - не точка входа ");
    }
    public static void method(){ // статический метод
    // метод не вызывается при инициализации
    System.out.print("статичные метод с именем  method()");
    }
    static { // статический блок инициализации
    System.out.print(" 1 ");
    }
}

/*
run:
 1  2  3  Конструктор BUILD SUCCESSFUL (total time: 0 seconds)
*/

Я не могу понять: почему, если метод
 public static void main(String[] args) {
         System.out.print(" 2 ");
         new InitClass();  }

вызывается после блока инициализации, мы видим " 2 " раньше " 3 " в блоке инициализации ? Спасибо!

A:
НО и отчего же тогда при выполнении я вижу 1 2 3 Конструктор вместо 1 3 2 Конструктор ?)

то есть 2 вызывается раньше чем 3, потому что метод
public static void main(String[] args)

статический. Статическое вызывается раньше чем нестатическое, поскольку обращение к классу происходит в статической памяти.
Более меннее адекватное понимание статической памяти можно почитать здесь.


text:
Q: Using ExifTool for Bulk Operations I would like to have help please with ExifTool, for the following operations:

*

*I have thousands of pictures scattered across dozens of sub-folders. All sub-folders are nested under a single parent folder, though. How do I tell ExifTool to apply the changes on all files?

*What I would like to do specifically is to "cut" each value under the "Copyright" EXIF tag, and "paste" it to the "UserComment" EXIF tag.
I would like to this for all photos at once, and each photo has to keep its respective value (only now under a different tag), of course.
Again, not all photos have a value in the "Copyright" field, I assume those will be ignored by the software.

*Finally, I would ExifTool to erase every possible metadata but the newly created values under the "Comments" tag.
Help and guidelines will be greatly appreciated.
Thanks!

A: Try this command:
exiftool -r -all:all= -tagsfromfile @ "-UserComment<Copyright" <DIR>
-r is the option to recurse into subdirectories
-all:all= will remove all metadata
-TagsFromFile @ copies tags listed after this option from the current file back into the file
"-UserComment<Copyright" After the TagsFromFile, it will copy the Copyright but redirect it into the UserComment tag.
Make sure and test it first of course.  This command will leave backup files with _original added to the extension.  You can prevent this once you make sure that the command is correct by adding -overwrite_original.


text:
Q: Convert data frame columns to one sound I'm interested in converting my data into a sound. My data is in a dataframe. Each column represents the relative amplitude of sound at a specific frequency. Each row is a sample. Samples are recorded at a fixed sample rate. I've figured out how to get a sound out using the seewave package, but not at the specific frequencies that I want.
Example:
library(seewave)

# some dummy data, 3 columns
set.seed(7)
df <- data.frame(f1=rnorm(600,30,5), f2=rnorm(600,40,10), 3=rnorm(600,30,10))
df[df<0] <- 0

mat <- as.matrix(df)
mat <- t(mat) +0i # istft() only works with complex numbers
sr <- 1000 # sample rate in Hz
freqs <- c(500, 2000, 10000) # desired frequencies of output sounds for each column

sound <- istft(mat,f=sr,ovlp=50,wl=256,output = "Wave") # creates a sound
listen(sound)

istft assumes:

"a complex matrix resulting of a short-term Fourier transform".

My mat object is obviously not in the right format, so I'm not sure what the output actually is. I can't figure out how to force each column from the dataframe to the frequencies stored in freqs.
Any ideas would be great.

A: Actually your code runs but there is a warning saying

1: In xprim * win :
   longer object length is not a multiple of shorter object length

To resolve this, your mat has to have a number of rows that is divisible by 2 and is smaller than your FFT window length (wl):
library(seewave)

# some dummy data, 3 columns
set.seed(7)
N = 128
df <- data.frame(f1=rnorm(N,30,5), f2=rnorm(N,40,10), f3=rnorm(N,30,10))
df[df<0] <- 0

mat <- as.matrix(df)
#no need to transpose
mat <- mat + 0i # istft() only works with complex numbers

sr <- 1000 # sample rate in Hz
freqs <- c(500, 2000, 10000) # desired frequencies of output sounds for each column

sound <- istft(mat, f=sr, ovlp=50, wl=256, output = "Wave") # creates a sound
listen(sound)

The above code will not give you that warning. You can step through the istft code for the example provided in ?istft and for your code to see what is causing the warning.

A: So I managed to do this by synthesising waves using the synth() function. This works through each column of the dataframe and creates an amplitude modulated signal on a carrier frequency. Then, results from all columns are added together.
library(seewave)
library(tuneR)

nsamps <- 600 # number of samples to create
sf <- 10 # sampling frequency of the data in Hz
fout <- 22000 # Sample frequency of output sound (Hz)
dout <- 10 # length of output sound file (seconds)

# some dummy amplitude data, 3 columns
df <- data.frame(f1 = sin((1:nsamps)/180*pi)+1, f2 = sin((1:nsamps)/180*pi + pi)+1, f3 = sin((1:nsamps)/90*pi)+1)

mat <- as.matrix(df)
freqs <- seq(100, 1000, length.out = ncol(mat)) # Carrier frequencies for each data column (Hz)

syn <- 0 # this is the synthesised wave
atemp <- seq(from=1, to=nrow(mat), length.out = fout*dout) # new times
for(ii in 1:ncol(mat)){ # for each data column
  scale_data <- (mat[,ii] - min(mat[,ii]))/diff(range(mat[,ii])) # scale each column between 0 and 1, comment out for absolute amplitudes across all columns
  amp <- approx(x = 1:nrow(mat), y = scale_data, xout = atemp)$y # sample the amplitude data onto the new times
  syn <- syn + synth(f = fout, d = dout, cf = freqs[ii], output = 'wave', a = amp) # build up the total synth wave

}

wave <- Wave(left = syn, samp.rate=fout, bit=16) # create a wave class
listen(wave) # listen to the sound

Here is the code to create a spectrogram plot:
t_win <- 0.5 # window length for spectrogram (s)
n_win <- t_win/(nsamps/sf/dout)*fout # calculate the window length in samples
spectro(wave, f=fout, flim = c(0,1.1), wl = n_win, ovlp = 75) # plot the spectrogram


text:
Q: RecyclerView.Adapter notifyDataSetChanged() using ContentProvider Hello I am using ContentProvider and after deleting elements by clicking a button my adapter does not notify, if i go back and come again the element is deleted. So ContentProvider works but notifyDataSetChanged(); doesn't.
public class CategoriesPreferedAdapter extends RecyclerView.Adapter<CategoriesPreferedAdapter.ViewHolder> {

private List<ModelCategoriesProvider> feedItemList;
private Context mContext;

public CategoriesPreferedAdapter(Context context, List<ModelCategoriesProvider> feedItemList) {
    this.feedItemList = feedItemList;
    this.mContext = context;
}

@Override
public CategoriesPreferedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View itemView = inflater.inflate(R.layout.categories_prefered_adapter, parent, false);

    return new CategoriesPreferedAdapter.ViewHolder(itemView);

}

@Override
public void onBindViewHolder(CategoriesPreferedAdapter.ViewHolder holder, final int position) {
    //holder.titleTextView.setText(mList[position]);
    final ModelCategoriesProvider feedItem = feedItemList.get(position);
    holder.setClickListener(new ItemClickListener() {
        @Override
        public void onClick(View view, int position, boolean isLongClick) {

            Toast.makeText(view.getContext(),""+feedItem.getId()+"  Users Delete",Toast.LENGTH_LONG).show();
            if (isLongClick) {
            }

        }

    });

    holder.title.setText(feedItem.getName());

    Glide.with(mContext)
            .load(Links.ImagePath+feedItem.getImage())
            .centerCrop()
            // .placeholder(R.drawable.ic_porosiicon)
            .crossFade()
            .into(holder.categoryImage);

    System.out.println("image path "+feedItem.getImage());

    holder.delete_category.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //deleteId(feedItem.getId()+"");
            String[] whereArgs = {feedItem.getId()+""};
            int count  = mContext.getContentResolver().delete(UsersProvider.CONTENT_URI,UsersProvider.PID+" =?",whereArgs);
            // System.out.println("count erald mjeshtri + mbreti ndaj thuaj princ ndaj thuaj mbret: "+count);
            //EventBus.getDefault().post(new Db_Update("update"));
            notifyDataSetChanged();

        }
    });

}

@Override
public int getItemCount() {
    return (null != feedItemList ? feedItemList.size() : 0);
}

public static class ViewHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener, View.OnLongClickListener{
    private TextView title,data,type,amount,billnr;
    private ImageView categoryImage,delete_category;
    private ItemClickListener clickListener;
    CardView card_view;

    public ViewHolder(View itemView) {
        super(itemView);
        card_view = (CardView) itemView.findViewById(R.id.card_view);

        title = (TextView) itemView.findViewById(R.id.repoName);
        categoryImage = (ImageView) itemView.findViewById(R.id.imageView_category);
        delete_category = (ImageView) itemView.findViewById(R.id.imageViewfavourites);
        itemView.setTag(itemView);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);

    }

    public void setClickListener(ItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }

    @Override
    public void onClick(View view) {
        clickListener.onClick(view, getPosition(), false);
    }

    @Override
    public boolean onLongClick(View view) {
        clickListener.onClick(view, getPosition(), true);
        return true;
    }
}

}

A: I had the same problem like your problem and I solved this problem in this way:
In mine, I have an array "arrayBootable" that I fill recycled view with it.
You can use your ArrayList name and call this method when you want to notify your recycler
public static void notifyRecycler(){
  arrayBootable.clear();
  arrayBootable.addAll(bootable());
  favouriteAdapter.notifyDataSetChanged();
}

A: Deleting from ContentProvider is fine, but you did not remove from the AdapterList, before notifyDataSetChange, delete from ArrayList like
feedItemList.remove(position);
Hope it helps.

A: Make sure you are calling notifyChange in the delete method of your content-provider. The way it works is, when the data attached to any view is updated, the notifyChange method notifies that view about the update. So, make sure, you have called  getContext().getContentResolver().notifyChange(uri, null); inside the delete method in you CP.
The other reason may be, you are initialising the arraylist/list attached to the recyclerview adapter more than once. In that case, the link to the list is lost from the adapter and you have to setAdapter again. The recommended way is to call clear followed by addAll on the list.
like this:
list.clear();
list.addAll(your_new_data);

Let me know if it helps.
Thanks!

A: Try using notifyDataSetChanged() inside a runnable that posts data on UI thread through a handler.
Define your handler in a Utility method
private static Handler mainHandler = new Handler(Looper.getMainLooper());

public static void postOnUiThread(Runnable runnable) {
        mainHandler.post(runnable);
    }

Then in your code :
Utility.postOnUiThread(new Runnable() {
            @Override
            public void run() {
                // call notifyDataSetChanged here
            }
        });


text:
Q: Facebook android login crashing app I'm working on a third party Facebook Android app. I've got the code working well so far but my app crashes when I add the Facebook login code below:
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;

public class MainFragment extends Fragment {

    private static final String TAG = "MainFragment";
    private static final int REAUTH_ACTIVITY_CODE = 100;

    private ProfilePictureView profilePictureView;
    private TextView userNameView;

    private final List<String> permissions;

    public MainFragment() {
        permissions = Arrays.asList("user_status", "read_stream", "friends_about_me", "friends_work_history", "friends_activities",
                "friends_birthday", "user_checkins", "friends_checkins", "user_education_history", "friends_education_history", "user_events",
                "friends_events", "user_groups", "friends_groups", "user_hometown", "friends_hometown", "user_interests", "friends_interests",
                "user_likes", "friends_likes", "user_notes", "friends_notes", "user_online_presence", "friends_online_presence", "user_interests",
                "friends_interests", "user_likes", "friends_likes", "user_notes", "friends_notes", "user_online_presence", "friends_online_presence",
                "user_religion_politics", "friends_religion_politics", "user_status", "friends_status", "user_subscriptions",
                "friends_subscriptions", "user_videos", "friends_videos", "user_website", "friends_website", "user_work_history",
                "friends_work_history", "read_friendlists", "read_mailbox", "read_requests", "read_stream", "xmpp_login", "email", "user_location",
                "user_photos", "friends_photos");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);
    }

    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a
        // new callback to handle the response.
        Request request = Request.newMeRequest(session,
                new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                // Check for an open session
                Session session = Session.getActiveSession();
                if (session != null && session.isOpened()) {
                    // Get the user's data
                    makeMeRequest(session);
                }

                    if (user != null) {
                        // Set the id for the ProfilePictureView
                        // view that in turn displays the profile picture.
                        profilePictureView.setProfileId(user.getId());
                        // Set the Textview's text to the user's name.
                        userNameView.setText(user.getName());
                    }
                    {
                if (response.getError() != null) {
                    // Handle errors, will do so later.
                }
            }
        }});
        request.executeAsync();
    }

    private UiLifecycleHelper uiHelper;
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(final Session session, final SessionState state, final Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main, container, false);

        // Find the user's profile picture custom view
        profilePictureView = (ProfilePictureView) view.findViewById(R.id.sidebar_profile_picture);
        profilePictureView.setCropped(true);
        // Find the user's name view
        userNameView = (TextView) view.findViewById(R.id.sidebar_profile_name);
        LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(permissions);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        // For scenarios where the main activity is launched and user
        // session is not null, the session state change notification
        // may not be triggered. Trigger it if it's open/closed.
        Session session = Session.getActiveSession();
        if (session != null &&
               (session.isOpened() || session.isClosed()) ) {
            onSessionStateChange(session, session.getState(), null);
        }

        uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REAUTH_ACTIVITY_CODE) {
            uiHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        uiHelper.onSaveInstanceState(bundle);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (state.isOpened()) {
            Log.i(TAG, "Logged in...");

            getView().setVisibility(View.GONE);
        } else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");
        }
    }}

Is there anyone that can help me figure out what is causing the app to crash?
Here is my main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
              android:background="#324D82" >

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        <ImageView
                android:id="@+id/splash_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:gravity="center"
                android:src="@drawable/icon" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:textColor="#FFFFFF"
                android:textSize="28sp"
                android:fontFamily="sans-serif-condensed"
                android:textStyle="normal"
                android:text="FrontPage for Facebook" />
         </LinearLayout>
         <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:textColor="#FFFFFF"
                android:textSize="10sp"
                android:fontFamily="sans-serif-condensed"
                android:textStyle="normal"
                android:text="Version 1.0" />
    </LinearLayout>

   <com.facebook.widget.LoginButton
        android:id="@+id/authButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        />

</LinearLayout>

Here is my sidebar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/sidebar_profile_height"
    android:id="@+id/sidebar_profile"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/sidebar_profile_cover"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/test_image1"
        android:scaleType="centerCrop"
        android:contentDescription="@string/pref_user_profile"/>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/sidebar_profile_selector"
        android:gravity="center_vertical">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="center_vertical"
            android:paddingTop="6.0dip">

            <com.facebook.widget.ProfilePictureView
                android:id="@+id/sidebar_profile_picture"
                android:src="@drawable/test_profile_pic"
                android:layout_width="42.0dip"
                android:layout_height="42.0dip"
                android:scaleType="centerCrop"
                android:contentDescription="@string/pref_user_profile"
                android:padding="2.0dip"
                android:background="@drawable/profile_picture_border"
                facebook:preset_size="small" />

            <TextView
                android:id="@+id/sidebar_profile_name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8.0dip"
                android:text="@string/test_title_text"
                android:textSize="@dimen/title_text"
                android:textColor="@color/white"
                android:gravity="center_horizontal"/>

        </LinearLayout>
    </RelativeLayout>
    </RelativeLayout>
</LinearLayout>


text:
Q: Command-line equivalent of "Open With gedit"? I'm a Mac user trying to make the switch to Ubuntu Linux (with the Gnome DE).  But as I've always relied heavily on the "open" and "edit" commands in Terminal on the Mac, I'm trying to find (or create) similar functionality in Linux.  Today I'm wrestling with "edit", which should open the given document(s) in a new gedit window if they weren't already open, but if they were already open, just bring that window to the front.
Unfortunately, that's not what the gedit command does.  It works great if the file isn't already open, but if it is, it opens it in a new window (without bringing it to the front), and gives me a scary warning that the file "is already open in another window" with "Edit Anyway" and "Don't Edit" buttons.
But if I right-click on a file in Files (or whatever the Gnome equivalent of the Finder is called), and select the "Open With gedit" command, it does exactly what I want: brings the existing editor to the front, or opens a new one.
How can I do that exact same operation from the command line?

A: I'm reading there that you can use xdg-open for that.
Not sure it will actually do exactly what you want as I just found it myself, but at least it will open a file of any type with the appropriate application!
Edit: I tried it yesterday after having walked away from the WiFi: it does what you are asking for! So either opens a new window or brings an already open window to the front.


text:
Q: AttributeError: 'GzipFile' object has no attribute '_buffer' when reading from gzip file When I attempt to read from a .gz file line by line with the gzip module in Python, I get a crash:
  File "/home/user/path/to/example.py", line 40, in run
    for line in handle:
  File "/home/user/.conda/envs/py38/lib/python3.10/gzip.py", line 399, in readline
    return self._buffer.readline(size)
AttributeError: 'GzipFile' object has no attribute '_buffer'

Here's my code:
import gzip

handle = gzip.open("path/to/file.txt.gz", "w")
for line in handle:
    print(line)

I'm using Python 3.10 on Linux.

A: The problem is that you have opened the file in write mode, not read mode.
Correct code:
import gzip

handle = gzip.open("path/to/file.txt.gz", "r")
for line in handle:
    print(line)

By changing the "w" to a "r" in the gzip.open() call, we choose to open the file in read mode rather than write mode.
(Note for reference: this error has a non-obvious cause and I couldn't find this elsewhere on here, so documenting both the error and the solution to help others)


text:
Q: Cannot create an instance of class MainViewModel_android I try to create instance of ViewModel, but get an error.
Process: com.example.popularmovies, PID: 20601
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.popularmovies/com.example.popularmovies.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.popularmovies.data.MainViewModel
MainActivity:
public class MainActivity extends AppCompatActivity {
    private MainViewModel viewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);

MainViewModel
public class MainViewModel extends AndroidViewModel {

    public static MovieDatabase database;
    public final LiveData<List<Movie>> movies;

    public MainViewModel(@NonNull Application application) {
        super(application);
        database = MovieDatabase.getInstance(getApplication());
        movies = database.movieDao().getAllMovies();
    }

    public Movie getMovieById(int id) {
        try {
            return new GetMovieTask().execute(id).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void deleteAllMovies() {
        new DeleteMoviesTask().execute();
    }

    public void insertMovie(Movie movie) {
        new InsertTask().execute(movie);
    }

    public void deleteMovie(Movie movie) {
        new DeleteTask().execute(movie);
    }

    public LiveData<List<Movie>> getMovies() {
        return movies;
    }

    public static class DeleteTask extends AsyncTask<Movie, Void, Void> {
        @Override
        protected Void doInBackground(Movie... movies) {
            if (movies != null && movies.length > 0) {
               database.movieDao().deleteMovie(movies[0]);
            }
            return null;
        }
    }

    public static class InsertTask extends AsyncTask<Movie, Void, Void>  {
        @Override
        protected Void doInBackground(Movie.. movies) {
            if (movies != null && movies.length > 0) {
                database.movieDao().insertMovie(movies[0]);
            }
            return null;
        }
    }

    public static class DeleteMoviesTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void.. integers) {
            database.movieDao().deleteAllMovies();
            return null;
        }
    }

    public static class GetMovieTask extends AsyncTask<Integer, Void, Movie> {
        @Override
        protected Movie doInBackground(Integer.. integers) {
            if (integers != null && integers.length > 0) {
                return database.movieDao().getMovieById(integers[0]);
            }
            return null;
        }
    }
}

DataBase:
@Database(entities = {Movie.class}, version = 1, exportSchema = false)
public abstract class MovieDatabase extends RoomDatabase {

    private static final String DB_NAME = "movies.db";
    private static MovieDatabase database;
    private static final Object LOCK = new Object();

    public static MovieDatabase getInstance(Context context) {
        synchronized (LOCK) {
            if (database == null) {
                database = Room.databaseBuilder(context, MovieDatabase.class, DB_NAME).build();
            }
        }
        return database;
    }

    public abstract MovieDao movieDao();
}

A: Perhaps this misstake is just from copy pasting your code here, but you seem to have syntax probems in your viewmodel.
Your class ends before the constructor. This seems to be the complete class:
public class MainViewModel extends AndroidViewModel {
    public static MovieDatabase database;
    public final LiveData<List<Movie>> movies;
}

Just remove } and perhaps add it to the end of the class, although it looks like it is not needed (but your IDE should have complained about this syntax problem?)


text:
Q: adding users by contacts ios I have an app where users create accounts by username and password. However, I also want users to be able to add friends via their mobile #. Is there a security reason as to why I would need to verify their number if my design goes as follows:
User A enters her # into app, which saves to database
User B gives app access to his contacts. User A is a contact in User B's address book. When the database is queried for all #'s in User B's contacts book, we find User A's # and User A is returned.
How could there be a security flaw if User A entered a false #?

A: That would definitely cause security issues. Of course, for an app like this, you would need some way to verify the data that you are receiving. What if one if the contacts phone numbers are wrong? Some phone numbers change all the time now and it would be difficult keeping up to date with them all.
But on a bigger note than that, I don't think this one would fly with Apple. I've never designed an app that needed to access more than one contact at a time and the user was fully aware of which contact he/she was importing to a database. But for an app to automatically upload multiple contacts from a users address book for intent to be stored on a remote database might cause security flags to be raised at Apple during the review process. So the app may never see light of day on the Apple Store.
If you really want to implement something similar, make sure users verify their phone number before use and instead of storing the users contacts on a server, just store the verified phone number. Then you can use the contacts in your phone to check mobile numbers that have been verified of other users and which ones have an account linked to them.


text:
Q: Suse 10.3 won't do anything after openssl upgrade. /lib64/libc.so.6: version `GLIBC_2.7' not found I upgraded my openssl version with the command:
rpm -i --nodeps openssl-0.9.8p-1.x86_64.rpm

And now I get following error for almost every command I enter:
/lib64/libc.so.6: version `GLIBC_2.7' not found (required by /lib64/libcrypto.so.0.9.8)

Will a simple update of GLIBC be enough? Like
rpm -i --nodeps glibc-2.9-2.9.x86_64.rpm

I'm kind of scared to try that because of the damage i've already caused.

A: Yeah, well, requiring --nodeps should be a big flashing sign that you're about to shoot yourself in the foot. Replacing core packages with some random rpm from the internet is unlikely to be successful, as you've noticed. Better luck next time, dude.
FWIW, you might be able to install the original openssl rpm by booting from a CD and playing with chroot.
Or, since Suse 10.3 isn't supported anymore anyway, you might as well update the entire system while you're at it.


text:
Q: mdadm RAID5 3*3TB, 1 Drive with data I have one disk (sdd) on which I currently have stored my data. I now have got two new 3TB disks (sdb&sdc) and want to create a RAID5 array over all three disks.

*

*sdb: gpt table, empty partition sdb1

*sdc: gpt table, empty partition sdc1

*sdd: gpt table, btrfs-partition sdd1 with my data

My plan looks like this:

*

*Create RAID5 array md0 over sdb1 and sdc1

*Create a btrfs filesystem on it.

*Copy the data from sdd1 to md0

*Re-partition(=wipe) sdd

*Grow the array onto sdd1

I currently am stuck at creating the 2-disk RAID5 array. I built the array
# mdadm --create --verbose /dev/md0 --level=5 --raid-devices=2 /dev/sdc1 /dev/sdb1
mdadm: layout defaults to left-symmetric
mdadm: layout defaults to left-symmetric
mdadm: chunk size defaults to 512K
mdadm: size set to 2900832256K
mdadm: automatically enabling write-intent bitmap on large array
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md0 started.

and /proc/mdstat shows that it's doing the initial sync:
I have one disk (sdd) on which I currently have stored my data. I now have got two new 3TB disks (sdb&sdc) and want to create a RAID5 array over all three disks.

*

*sdb: gpt table, empty partition sdb1

*sdc: gpt table, empty partition sdc1

*sdd: gpt table, btrfs-partition sdd1 with my data

My plan looks like this:

*

*Create RAID5 array md0 over sdb1 and sdc1

*Create a btrfs filesystem on it.

*Copy the data from sdd1 to md0

*Re-partition(=wipe) sdd

*Grow the array onto sdd1

I currently am stuck at creating the 2-disk RAID5 array. I built the array
# mdadm --create --verbose /dev/md0 --level=5 --raid-devices=2 /dev/sdc1 /dev/sdb1
mdadm: layout defaults to left-symmetric
mdadm: layout defaults to left-symmetric
mdadm: chunk size defaults to 512K
mdadm: size set to 2900832256K
mdadm: automatically enabling write-intent bitmap on large array
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md0 started.

and /proc/mdstat shows that it's doing the initial sync:
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
        md0 : active raid5 sdb1[2] sdc1[0]
          2900832256 blocks super 1.2 level 5, 512k chunk, algorithm 2 [2/1] [U_]
          [>....................]  recovery =  0.6% (19693440/2900832256) finish=308.8min speed=155487K/sec
          bitmap: 0/22 pages [0KB], 65536KB chunk

    unused devices: <none>

top shows, that during this time, md(adm) uses ~35% CPU:
  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
  989 root      20   0       0      0      0 S  29.1  0.0   0:17.69 md0_raid5
  994 root      20   0       0      0      0 D   6.6  0.0   0:03.54 md0_resync

So far so good. This should take ~6 hours. On my first try I had to reboot my server and thus stop the array after ~5h an the second time my sdb drive mysteriously disappeared, so I also had to restart the system.
The array started itself automatically, but the progress bar is gone:
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
md127 : active (auto-read-only) raid5 sdb1[2] sdc1[0]
      2900832256 blocks super 1.2 level 5, 512k chunk, algorithm 2 [2/1] [U_]
      bitmap: 0/22 pages [0KB], 65536KB chunk

unused devices: <none>

and top reports no CPU-use.
So I tried stopping and assembling it manually:
~# mdadm --stop /dev/md127
mdadm: stopped /dev/md127
~# mdadm --assemble --verbose /dev/md0 /dev/sdc1 /dev/sdb1
mdadm: looking for devices for /dev/md0
mdadm: /dev/sdc1 is identified as a member of /dev/md0, slot 0.
mdadm: /dev/sdb1 is identified as a member of /dev/md0, slot 1.
mdadm: added /dev/sdb1 to /dev/md0 as 1
mdadm: added /dev/sdc1 to /dev/md0 as 0
mdadm: /dev/md0 has been started with 1 drive (out of 2) and 1 rebuilding.

Although it says it's rebuilding, mdstat shows no sign of that:
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
md0 : active (auto-read-only) raid5 sdc1[0] sdb1[2]
      2900832256 blocks super 1.2 level 5, 512k chunk, algorithm 2 [2/1] [U_]
      bitmap: 0/22 pages [0KB], 65536KB chunk

unused devices: <none>

also top again shows no CPU use.
So I searched the web for a method to manually force a sync and found --update=resync, but trying this also doesn't yield a victory:
~# mdadm --stop /dev/md0
mdadm: stopped /dev/md0
~# mdadm --assemble --verbose --force --run --update=resync /dev/md0 /dev/sdc1 /dev/sdb1
mdadm: looking for devices for /dev/md0
mdadm: /dev/sdc1 is identified as a member of /dev/md0, slot 0.
mdadm: /dev/sdb1 is identified as a member of /dev/md0, slot 1.
mdadm: Marking array /dev/md0 as 'clean'
mdadm: added /dev/sdb1 to /dev/md0 as 1
mdadm: added /dev/sdc1 to /dev/md0 as 0
mdadm: /dev/md0 has been started with 1 drive (out of 2) and 1 rebuilding.
root@server:~# cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
md0 : active (auto-read-only) raid5 sdc1[0] sdb1[2]
      2900832256 blocks super 1.2 level 5, 512k chunk, algorithm 2 [2/1] [U_]
      bitmap: 0/22 pages [0KB], 65536KB chunk

unused devices: <none>

(still no CPU-use)

After two days of trying to fix it myself I would be very thankful for any help or advice

A: Since there's nothing on the raid array, the easy option is to just wipe everything and start over:

*

*mdadm /dev/md127 --fail /dev/sdb1; mdadm /dev/md127 --fail /dev/sdc1; mdadm /dev/md127 --remove failed

*wipefs -a /dev/sdb1; wipefs -a /dev/sdc1
Incidentally, I recommend creating a degraded RAID 5 array and then adding the third disk to it.  A rebuild is usually faster than a reshape, though there's an increased chance of data loss if a disk fails during the rebuild (you do have a backup, don't you?)

*

*mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sdc1 /dev/sdb1 missing

*Create the new filesystem

*Copy the data

*wipefs -a /dev/sdd1

*mdadm /dev/md0 --add /dev/sdd1


text:
Q: Converting second order non linear differential equations to first order systems I have been asked to "convert the pair of second order differential equations (9), (10) into a system of 4 first order ordinary differential equations". The equations (9) and (10) are as follows:
$$\ddot z= -\frac{-GM_E}{(r_0+z)^2} + (r_0+z)(\omega_0+\dot \phi)^2 + \frac{F_r}{m}$$
and
$$\ddot \phi = -2 \frac{(\omega_0+\dot\phi)\dot z}{r_0+z}+\frac{F_\theta}{m(r_0+z)}$$
I assume this will involve something to do with setting say $f=\dot z$ and $g=\dot\phi$ as that's what you would do in the linear case, but I'm not sure where to go from here.

A: You have solved it yourself: in your own notations,
$$\dot z = f \\
\dot \phi = g \\
\dot f = -\frac{-GM_E}{(r_0+z)^2} + (r_0+z)(\omega_0 + g)^2 + \frac{F_r}{m} \\
\dot g = -2 \frac{(\omega_0 + g)f}{r_0+z}+\frac{F_\theta}{m(r_0+z)} .$$
(Note that the system is not linear.)

A: Let:
$z = x_1$
$z' = x_1' = x_2$
$z'' = x_1'' = x_2' = -\dfrac{-GM_E}{(r_0+x_1)^2} + (r_0+x_1)(\omega_0+x_4)^2 + \dfrac{F_r}{m}$
$\phi = x_3$
$\phi' = x_3' = x_4$
$\phi'' = x_3'' = x_4' = -2 \dfrac{(\omega_0+x_4)x_2}{r_0+x_1}+\dfrac{F_\theta}{m(r_0+x_1)}$
So now, we have a system of four-first order ordinary differential equations with $x_1', x_2', x_3', x_4'$.


text:
Q: How can I keep a div fixed to the bottom of the window without having it overflow? I'm trying to pin a footer div to the bottom of a page div and have the footer always stay at the bottom of the screen.
Setting the style for the footer to "position:fixed; bottom:0;" as shown:
#idFoot {background-color: silver; height:20px; width:100%; position:fixed; bottom:0;}
does a nice job of setting the footer to the bottom of the screen but the footer's right edge is out of the viewport as you can see here:

Why is it overflowing like this? How can I get it to line up with the edge of the containing  page div?
Is this the best way to get a div inside another div to span the outer div's entire width and get it to stick to the bottom of the screen?
I've attached all my code using stackexchange's code snippet feature but it renders my page in a very different manner than Chrome.
You can, however, still see that the footer fixed to the bottom is overflowing:

* {outline: 1px solid blue;}
html                        {background-color:lightblue;}
body                        {background-color:lightgreen; overflow:hidden}

div, p, h1, h2, h3, h4, h5  {FONT-FAMILY: Arial, Helvetica, sans-serif, Verdana; font-size:10pt}

#idPage                     {background-color:lightyellow; height:100%; overflow:auto; }

#idFoot                     {background-color: silver; height:20px; width:100%; position:fixed; bottom:0;}

    <title>Attempt 7</title>
    <link rel="stylesheet" href="style.css">

A: Here's a solution. Most body margins defaults are 8px so we'll set a css variable to that, set the body margin to that value then use that to the margin in the footer rule.

* {
  outline: 1px solid blue;
}

html {
  background-color: lightblue;
  height: 100vh;
}

body {
  --margin: 8px;
  background-color: lightgreen;
  overflow: hidden;
  height: 100%;
  margin: var(--margin);
}

div,
p,
h1,
h2,
h3,
h4,
h5 {
  FONT-FAMILY: Arial, Helvetica, sans-serif, Verdana;
  font-size: 10pt;
}

#idPage {
  background-color: lightyellow;
  overflow: auto;
}

#idFoot {
  background-color: silver;
  height: 20px;
  left: var(--margin);
  right: var(--margin);
  position: fixed;
  bottom: 0;
}

A: if you're using position: absolute, it's better to stretch the footer div using right:0; left:0.
also give to the parent position: relative
  #idPage {background-color:lightyellow; position: relative; }

  #idFoot {background-color: silver; height:20px; position:fixed; bottom:0;
           left: 0; right: 0;}


text:
Q: Code displaying second image first I made this code which displays different traffic lights at different intervals. It works , however when I run the code it starts from the second image.
"red-yellow 2.jpg"

I obviously want the traffic light to start with my first image, but I have no idea what the problem is.
Code:
<!DOCTYPE html>

JavaScript Code

Traffic Light

<button type="button" onclick="ChangeLight()">Change Light</button>

A: Your function should be like this,
function ChangeLight() {

if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');

var obj = list[nextlight];
firstlight.src = obj.src;
//firstlight.alt = obj.src;
timer = setTimeout(ChangeLight, obj.interval);
nextlight++;
}

A: This may sound Stupid but did you try

this could be because "only" can be considered as a class.
also avoid spaces in the images. use hypen instead

A: You need to put down line nextlight = nextlight + 1;, final code would be like this
function ChangeLight() {
  if (nextlight == list.length)
    nextlight = 0;
  var firstlight = document.getElementById('traffic');
  var obj = list[nextlight];
  firstlight.src = obj.src;
  nextlight = nextlight + 1;
  //firstlight.alt = obj.src;
  timer = setTimeout(ChangeLight, obj.interval);
}


text:
Q: What is the difference between accessing vector elements using an iterator vs an index? What advantages are there in accessing vector elements using an iterator vs an index?

A: Why are iterators better than indexes?

*

*In the cases where index is not available (like with std::list, for
example).

*In the case where a generic function accepting an iterator
is called.

*When writing a function template that is supposed to work with
more than one container type.

*They exist to create uniformity among all containers and ability to use
all containers' iterators as well as regular pointers in all standard
algorithms.

*Iterators can point to sequences that don't exist except as a concept.
For instance, you can make an iterator class that steps through prime
numbers without actually having to build a container of primes.

However, if ignoring container types that do not support random access (list, set, etc.), iterators still offer

*

*Pointer like semantics (think of string::iterator vs. char *).

*Generalized concept usable beyond iteration over elements inside a
container.

*Better performance than container member functions in a few cases.

A: Modularity is the answer. Suppose you wrap your logic in a function call (a good practice). In that case making it receive iterator  will make it generic, so that it can operate on a C style array (pointer), an C++ stl vector or anything really that behaves like an iterator container, such as a linked list for instance.

A: I say its portability across containers.
If you write a code using vectors and use index to iterate then the code cannot be changed to other containers easily later .
typedef std::vector<int> myContainer; //only change here for std::list

for ( myContainer::iterator iter = actualContainer.begin();
      iter != actualContainer.end();
      ++iter)
{}

In the above code if you want to change from vector to list, it is very easily possible. If you had used the index then it won't be possible.
Otherwise since the vector uses random access iterators it should be the same. ( index or iterator anything is ok)

A: This question was asked by me recently regarding performance.
You might want to take a look at the answers I got.
Check the following link: Iterators vs. indexes
The discussion was mainly about performance, which turned out to be platform dependant, with minor changes in each platform.


text:
Q: How can I make Ubuntu 15.10 run/boot normally? I recently installed a fresh copy of Ubuntu 15.10 on my laptop. Everything went fine right up to the moment when I had my first system boot. I logged in by typing the password as usual, like in the others previous versions but this time I had nothing to see but my cursor and just the wallpaper. I can t use the system at all, it just freezes at the purple screen. I am using a laptop with an intel pentium dual core processor and 6370m ati graphics card which worked in Trusty Tahr.

A: Add the parameter radeon.modeset=0 the to the end of the linux line before booting !
Highlight the Ubuntu menu entry -> press the "e" key -> add the parameter -> press F10.
To make this solution permanent add the parameter to GRUB settings /etc/default/grub.
You can do this as follows ... when not already installed before - install the package gksu.
Open a terminal and execute :
sudo apt-get install gksu

Then execute :
gksudo gedit /etc/default/grub

Add radeon.modeset=0 to this line : GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
that it reads : GRUB_CMDLINE_LINUX_DEFAULT="quiet splash radeon.modeset=0"
Then execute :
sudo update-grub

In case you have AMD Catalyst drivers installed - they have known issues with kernel 4.2.
There is a workaround fix in wily-proposed but it is recommended to wait until it is tested.
Use the open source radeon drivers in the meantime until the final Catalyst fix is released.
Uninstall the proprietary AMD drivers from a virtual console :
On login screen press Ctrl + Alt + F1 - enter user name and password and then execute :
sudo apt-get purge fglrx
sudo reboot

In this case first boot without adding the parameter to see whether it will work for you.

A: Or use kernel 4.1 which has long term support, it works perfectly with Catalyst on 15.10 ;) That's how i solved the same problem.


text:
Q: removing special chars and adding a dash between words php mysql I am trying to strip all special chars and add a dash between all the words.
Example:
Example text:
How to make something, something else, and other stuff.
Example string:
$string = "How to make something, something else, and other stuff.";

Example of how it should look:
How-to-make-something-something-else-and-other-stuff
I need a function that will strip all special chars but also add the dashes between every word "but also not adding dashes after the last word". Anyone have any ideas of how I should do this? I assume this is fairly simple. probably a preg_replace with regex which would solve the special char problem but adding the dashes is where I get confused and am not sure what to do.

A: Assuming the string is in utf-8:
$string = 'Höw to máke sòmething, something else, and other stuff';
$string = preg_replace('/[^a-z0-9]+/i','-',
   iconv('UTF-8','ASCII//TRANSLIT',$string));
$string = trim($string,'-');

A: After you've removed the non-alpha characters, you can explode() on spaces and then implode() with dashes.

A: I would explode the string at the spaces and then implode it with dashes like this:
$string = trim($string); // removes white space from ends
$string = preg_replace("/[^A-Za-z0-9]/","",$string); // removes special chars
$string = explode(' ', $string); // separates the words where there are spaces
$string = implode('-', $string); // puts the words back into a sentence separated by dashes
echo $string;

this can be condensed obviously - but for simplicity these are the steps needed.


text:
Q: What is the simplest way to find the XML node position of a value? I want to find the XML node position of stateInput
For example, if I select the state "Alabama" from the datalist I want my code to return the XML node position of "Alabama" so that related attributes such as "population" can also be retrieved in the results.
What is the simplest solution to this problem?
Note: in this test, I manually set the node position variable = 2. Currently, regardless of the selected state, Node position of state input = 2, State node = California, etc. That's only a correct match if California is selected.

var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myButton").click();
    }
});

function testResults() {
    document.getElementById("stateInput").innerHTML = myInputId.value;
}

var parser, xmlDoc, x, i;
var text =
"<STATE_DATA>" +
"<UNIT>" +
"<STATE>Wisconsin</STATE>"+
"<GDP>232,300,000,000</GDP>"+
"<POPULATION>5,800,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Alabama</STATE>" +
"<GDP>165,800,000,000</GDP>" +
"<POPULATION>4,900,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>California</STATE>" +
"<GDP>2,500,000,000,000</GDP>" +
"<POPULATION>39,600,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Texas</STATE>" +
"<GDP>1,600,000,000,000</GDP>" +
"<POPULATION>28,300,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Michigan</STATE>" +
"<GDP>382,000,000</GDP>" +
"<POPULATION>10,000,000</POPULATION>" +
"</UNIT>" +
"</STATE_DATA>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

var a = 2; /*I want: var a = XML node position of stateInput*/
document.getElementById("stateNodePosition").innerHTML = a;

document.getElementById("stateNode").innerHTML =
xmlDoc.getElementsByTagName("STATE")[a].childNodes[0].nodeValue;

document.getElementById("populationNode").innerHTML =
xmlDoc.getElementsByTagName("POPULATION")[a].childNodes[0].nodeValue;
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="testResults()">submit</button>

<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>

State input:

Node position of state input:

State node:

Population node:

A: Iterate through all STATEs and find the one whose textContent is the state you want, and then you can access its parent to get to its UNIT. The only changes are in testResults:

var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
    document.getElementById("myButton").click();
  }
});

function testResults() {
  const { value } = myInputId;
  const foundState = [...xmlDoc.querySelectorAll('STATE')]
    .find(possibleMatch => possibleMatch.textContent === value);
  const unit = foundState.parentElement;
  console.log(unit.innerHTML);
  document.getElementById("stateInput").innerHTML = value + ' has pop ' + unit.children[2].textContent;
}

var parser, xmlDoc, x, i;
var text =
  "<STATE_DATA>" +
  "<UNIT>" +
  "<STATE>Wisconsin</STATE>" +
  "<GDP>232,300,000,000</GDP>" +
  "<POPULATION>5,800,000</POPULATION>" +
  "</UNIT>" +
  "<UNIT>" +
  "<STATE>Alabama</STATE>" +
  "<GDP>165,800,000,000</GDP>" +
  "<POPULATION>4,900,000</POPULATION>" +
  "</UNIT>" +
  "<UNIT>" +
  "<STATE>California</STATE>" +
  "<GDP>2,500,000,000,000</GDP>" +
  "<POPULATION>39,600,000</POPULATION>" +
  "</UNIT>" +
  "<UNIT>" +
  "<STATE>Texas</STATE>" +
  "<GDP>1,600,000,000,000</GDP>" +
  "<POPULATION>28,300,000</POPULATION>" +
  "</UNIT>" +
  "<UNIT>" +
  "<STATE>Michigan</STATE>" +
  "<GDP>382,000,000</GDP>" +
  "<POPULATION>10,000,000</POPULATION>" +
  "</UNIT>" +
  "</STATE_DATA>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");

var a = 2; /*I want: var a = XML node position of stateInput*/
document.getElementById("stateNodePosition").innerHTML = a;

document.getElementById("stateNode").innerHTML =
  xmlDoc.getElementsByTagName("STATE")[a].childNodes[0].nodeValue;

document.getElementById("populationNode").innerHTML =
  xmlDoc.getElementsByTagName("POPULATION")[a].childNodes[0].nodeValue;
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="testResults()">submit</button>

<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>

State input:

Node position of state input:

State node:

Population node:


text:
Q: How to make a floating div which show another div when we click it I am trying to create a div (show) at top-right of the window which look like button. If the user click it then another div (form) should open up along with div (show) sliding down. So i used jquery slideToggle to Take Care of it. Now, if I click the div (show) it slideToggle div (form) but this two divs moves the third div (ano) down. That is this two affect other divs. I want this two div open up like a slider without affecting other I guess it should come at the top index. Here is the code

     Here are some content

     click me

     different div

A: Try It:
.ano
{
background-image:url('pic1.jpg');
position:absolute;
top:20px;
}

Hope it will Help you..!!

A: Here is how you could do it. You could wrap the form and show in another div, that is fixed in the top right corner:
.sitInCorner {
    position:fixed;
    top:0;
    right:0;
    width:15%;
}

DEMO
This will always make the .show and .form be in the top right corner, no matter what, and it will not effect any other elements on the page.
Hope this does what you want! ^_^
Edit:
If you want the .form tag to start out hidden, add this to the CSS:
display:none;

DEMO


text:
Q: How to recreate views without restart activity? So I got a custom spinner which is setup as needed when activity starts. It shows default value and it is closed by default. Then there are several scenarios for each item in that spinner. But I need to reset everything on the screen in case of error dialog appear. So if error appears my activity need to looks like it is just created from scratch?

A: I like the answer in the comment. You can extract the spinner to a method and call the method as and when you like. No need to start the spinner with the activity.


text:
Q: Classloader being called before missingProperty Let's say I have a script called Utils.groovy:
package hello

def testMethod() {
    log.info("hello world")
}

def propertyMissing(String name) {
    System.out.println("Loading ${name}.groovy")
    GroovyScriptEngine gse = new GroovyScriptEngine("vars")
    gse.loadScriptByName("${name}.groovy").newInstance()
}

It makes a reference to a property which doesn't exist, log. However log exists as a class that will be loaded by the Groovy script engine:
void info(Object message) {
    println(message)
}

If Utils.groovy itself is loaded by the GroovyScriptEngine, it will call the propertyMissing method and dynamically load log.groovy.
Here is the example code that loads Utils.groovy:
package hello

class Main {
    static void main(String... args) {
        GroovyScriptEngine gse = new GroovyScriptEngine("src")
        Class<Script> scriptClass = gse.loadScriptByName("hello/Utils.groovy")
        def utils = scriptClass.newInstance()

        //def utils = new Utils()

        utils.testMethod()
    }
}

And here is the output:
Loading log.groovy
hello world

Now, instead of being loaded by the GSE, let's instantiate a new instance of Utils.groovy and execute it directly (by commenting out the first three lines in the above example and uncommenting the next line):
package hello

class Main {
    static void main(String... args) {
        //GroovyScriptEngine gse = new GroovyScriptEngine("src")
        //Class<Script> scriptClass = gse.loadScriptByName("hello/Utils.groovy")
        //def utils = scriptClass.newInstance()

        def utils = new Utils()

        utils.testMethod()
    }
}

However, it fails to call the propertyMissing method on Utils.groovy and instead attempts to load log.groovy directly from the classpath. However. since info isn't a static method, if fails with this error:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static log.info() is applicable for argument types: (java.lang.String) values: [hello world]
Possible solutions: info(java.lang.Object), find(), any(), find(groovy.lang.Closure), is(java.lang.Object), any(groovy.lang.Closure)
    at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1518)
    at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1504)
    at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:52)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at hello.Utils.testMethod(Utils.groovy:4)
    at hello.Utils$testMethod.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
    at hello.Main.main(Main.groovy:11)

However. I noticed that if I change the name of the log property to something that doesn't exist on the classpath (loggy.info for example, and kept the log.groovy filename the same), it does end up calling the propertyMissing method (but fails because it can't find the non-existant script):
Loading loggy.groovy
Exception in thread "main" groovy.util.ResourceException: Cannot open URL: file:/home/wlaw/test/vars/loggy.groovy
    at groovy.util.GroovyScriptEngine.getResourceConnection(GroovyScriptEngine.java:408)
    at groovy.util.GroovyScriptEngine.loadScriptByName(GroovyScriptEngine.java:552)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap.invoke(PojoMetaMethodSite.java:213)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at hello.Utils.propertyMissing(Utils.groovy:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaClassImpl.invokeMissingProperty(MetaClassImpl.java:890)
    at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1854)
    at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:3773)
    at groovy.lang.GroovyObjectSupport.getProperty(GroovyObjectSupport.java:38)
    at groovy.lang.Script.getProperty(Script.java:58)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:310)
    at hello.Utils.testMethod(Utils.groovy:4)
    at hello.Utils$testMethod.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
    at hello.Main.main(Main.groovy:11)

So it looks like the propertyMissing method will only be called if 1. the script is instantiated directly and it refers to a missing property whose name is not on the classpath or 2. the script is loaded by the GSE.
So my question is, is there a reason why Groovy attempts to locate a class first instead of calling propertyMissing for objects not loaded by the GSE? And is there a way I can change this behavior?
Note: both vars and src are in the classpath of the project.
Also note: I am running these files by first running them through groovyc and then with java.

A: If "log" is a type it will be resolved as such during compilation. If you want "log.info(...)" to always try for a dynamic property, you can write "this.log.info(...)". Groovy lets you write class literals shorter, so "log" is interpreted as "log.class", which explains the static method search for "info".


text:
Q: Ionic ion-modal height with keyboard bug I have a ion modal which i want to show of 60% of my screen, but when keyboard appears the modal resizes to 60% of the screen (including keyboard) so it shrinks a lot. I want the modal to stay the same size (ideally the size of its contents). Pictures explain a lot.
This is the css
.ion-modal.modal {
  width: 90%;
  min-height: 0 !important;
  height: 60% !important;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: #fff;
  -webkit-box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5); }

And this the html
<ion-modal-view id="details_modal" class="ion-modal">
STUFF
</ion-modal-view>

A: I fixed this issue using <ion-content overflow-scroll="false"></ion-content>

overflow-scroll="false"

fix the issue for me.


text:
Q: Why would certain browsers request all pages on my ASP.Net Web site twice? Firefox is issuing duplicate requests to my ASP.Net web site. It will request a page, get the response, then immediately issue the same request again (well, almost the same -- see below). This happens on every page of this particular Web site (but not any others). IE does not do this, but Chrome also does this.
I have confirmed that there is no Location header in the response, and no Javascript or meta tag in the page which would cause the page to be re-requested (if any of these were true, IE would be re-requesting pages as well).
I have confirmed this behavior on multiple Firefox installs on multiple machines. Versions vary, but all are 3.x.
The only difference between the two requests is the Accepts header. For the first request, it looks like this:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

For the second request, it looks like this:
Accept: */*

The Content-Type response header in all cases is:
Content-Type: text/html; charset=utf-8

Something else odd -- even though Firefox requests the page twice, it uses the first response and discards the second. I put a counter on a page that increments with every request. I can watch the responses come back (via the Charles proxy). Firefox will get a "1" the first time, and a "2" the second time. Yet it will display the "1," for some reason.
Chrome exhibits this exact same behavior. I suspect it's a protocol-level issue, given the difference in Accepts header, but I've never seen this before.

A: Check you don't have any img tags with empty src attributes.
FireFox (and apparently Safari and Chrome) will interpret this as a request to the site, giving you the duplicate request.
There is a Mozilla support request about it, and a nice article here discussing what each browser (and each version) does in this scenario.


text:
Q: How to get x y coordinates from a Matplotlib scatterplot graphic I have a Widget into my GUI hosting a scatterplot graphic. I managed to include a pick event but am not able to get the x y coordinate by clicking a plot only the print('yahoo') works. My code is based on the following article: see link (section: Simple picking example).
How can I get the coordinates of the point (e.g. x=20 and y=50 which is one my five points) by clicking the point on the scatterplot?
Front-end code:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(595, 393)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setMinimumSize(QtCore.QSize(0, 200))
        self.widget.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.widget.setObjectName("widget")
        self.gridLayout.addWidget(self.widget, 0, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 595, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Back-end code:
import sys
import matplotlib.pyplot as plt
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from front_end import Ui_MainWindow

class Graph_init(FigureCanvas):

    def __init__(self, parent=None):

        fig = Figure()
        fig.patch.set_facecolor("None")
        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        FigureCanvas.mpl_connect(self, 'pick_event', self.onclick)

    def onclick(self, event):
        print('yahoo')
        thisline = self.event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()

class Graph_populate(Graph_init):

    def compute_initial_figure(self):

        x = [10,20,30,40,50]
        y = [100,50,150,200,75]
        size = [1000,2000,3000,5000,2000]

        self.axes.scatter(x,y,s=size,color='blue', picker=1)
        self.axes.patch.set_facecolor('None')

class GUI(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(GUI, self).__init__(parent)
        self.setupUi(self)
        self.sc = Graph_populate(self.widget)
        self.gridLayout.addWidget(self.sc, 0, 1, 1, 1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    prog = GUI()
    prog.showMaximized()
    sys.exit(app.exec_())

Thank you

A: You are plotting a scatterplot. Hence you may have a look at the third part of the pick_event_demo, where a scatterplot is treated.
The idea would be to get the index of the picked datapoint and take the data at that index out to obtain the coordinates.
def onclick(self, event):
    ind = event.ind[0]
    data = event.artist.get_offsets()
    xdata, ydata = data[ind,:]
    print ((xdata, ydata))

Note that those are the coordintes of the data point, not those of the mouseclick (which is how I understand the question).


text:
Q: Inserting Contents Of Text File Into HTML Say I've got a .txt file that looks something like this:
heyo.txt:

heyo

heyo!

If I want the contents of heyo.txt rendered somewhere on the inside of a View (say, after the view is done loading), then how do I go about doing that?
Is there a way to accomplish this in ASP.NET in a way that is similar to PHP's readfile() function?  I've tried using Response.WriteFile with no success:
@{ Response.ContentType = "text/html"; //(and "text/xml")
   Response.WriteFile(Url.Content("~/Content/heyo.txt"));
 }

Using "text/html" replaces the entire page with the contents of heyo.txt, and "text/xml" throws "XML Parsing Error: junk after document element".

A: The standard way of accomplishing this in ASP.NET MVC, is to do this in the controller instead with a FileResult using the File method of the controller.
For example:
public ActionResult MyAction()
{
    return File("~/Content/heyo.txt", "text/html");
}


text:
Q: how can I send emails from react using sendinblue? I am working in React applications (using the .net core in the back-end)
I have to send emails from the client side , we have to use sendinblue instead of mailgun , I need your help

A: You should not send emails from the client side.
Consider that in doing so, you're going to expose your API Key to any client, leading to a severe vulnerability for your application (anyone could impersonate you and send emails as if they were you).
In order to really make that work, you should perform an AJAX request to your server and there, connect to the Sendinblue API and make the request to send the email. In this case, the API Key could be safely stored in your server.


text:
Q: Loop into Javascript object and show in table I am using JavaScript JSON object. I am not sure this is the right way to write JSON object :-
var address={
    details:{
        "martin":[{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}],
        "luthar":[{"full_name":"Luther king"},{"address":"Boston"},{"phone":"9856568789"}],
        "jonson":[{"full_name":"Jonson vierra"},{"address":"New york"},{"phone":"98654567887"}]
    }
}

Now, I want to show every elements of each person in a table. I can do this manually by writing:

Like this for all 3 people, but I want to grab full details of every person by using a loop.
How can I do this easily by using a loop?

A: I would do something along these lines:
for (var i in address.details)
{
    document.write('
' + address.details[i][0]['full_name'] + '	' + address.details[i][1]['address'] + '	' + address.details[i][2]['phone'] + '
');
}

To follow up this code should output a table with the data you require:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>An XHTML 1.0 Strict standard template</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />

A: for (var personName in address.details) {
  if (address.details.hasOwnProperty(personName)) {
    address.details[personName]
    //  [{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}]
    // you could now loop through the personName's array
  }
}

Do you have control over the data structure at all? It seems a little convoluted?


text:
Q: What does "This change has been a long time coming" mean?
This change has been a long time coming.

So what does this sentence really mean — the change has taken a long period of time to finally occur?  Or something different?

A: This is a special idiom in the English language. It doesn't strictly mean what it says. Its meaning is really:
This change has been needed for a long time, and now finally it is coming.

The emphasis is that it should have happened, or it was needed a long time ago, and now we are finally getting around to doing it.
For example, when the government passed laws to regulate the banks, some might say the change had been a long time coming because, in their opinion, the banks had been abusive of their unregulated status, and so finally that wrong had been righted.
Regardless of what you think of banking regulation, that would be the meaning. Not that it took a long time to happen, but rather than it had been needed for a long time.


text:
Q: Workflow for using SVN for many variations of some base documents (job applications) For some time now I'm using pdfLaTeX for writing my job applications, which normally contain 3 pdf documents all created with LaTeX:

*

*the letter of motivation

*the CV and more information about my projects

*diploma, certificates, etc.

I now noticed that it would have been good to use version control of the different versions to document the differences or take notes about what was changed.
I already used version control with the svn-multipackage for my dissertation, but that is only a "linear" process where I save a "snapshot" and don't have different versions in parallel.
=> So  what would be an appropriate workflow for SVN to handle those documents
under the following conditions:

*

*it should be clear in the .tex source which document/version was taken as "template" for the actual file, but this shall not be visible in the pdf
(to avoid the potential employer seeing "ah, this is application number 323a ...")

*I'll create a directory for each application "somewhere" outside my svn repository,
-> I think this would be done by an export of an existing version - is that correct?
(That directory will also contain other documents with information about the company, the job etc., which will not be managed by svn)

*If the documents are finished, is it correct to save them in the repository by 'update'?

*How could I create different "main versions"
(e. g. one focussing on jobs in IT business which puts more emphasize on my computer skills and another one for the more "technical" jobs where those computer skills are not shown in detail)

*Would it be a problem for SVN if in the custom directory of each application I change the name of LetterOfMotivation.tex to LetterOfMotivation_CompanyXY.tex?
I suppose when I do that and then send it back to the repository, SVN would be confused and not recognize the new document as a changed version of LetterOfMotivation.tex?

I'm sorry if that sounds like stupid questions, but I have no experience with the "real" use of svn up to now. :-(

A: A lot of questions!
Most of these have already been answered on TeX-SE, though

*

*I don't think there's a TeX solution for that, but you can write your own post-commit SVN hooks that modify all your source files, adding the version string, commit date, and whatnot as a comment in the beginning of each file. See this on how to create repository hooks. Admittedly, this is not for the faint of heart and you'll need to write a script or two.
An alternative solution is to keep your SVN info as PDF metadata when you store them in the repository, and to strip it when sending it to an employer. Writing metadata is easy - see this question, for example. You might need something like pdftk (the definitive PDF manipulation tool) for the job, again with a small script.

*Yes, svn export is the way to do it if you don't want to have the SVN metadata in your exported tree (I do this when I'm sending stuff to people, or want to make changes that are not going back in the same branch/repo). You can always commit back the changes if you like, but all the information about previous revisions is lost in the exported tree.

*No! You issue svn commit to write your changes to the repository. svn update will update your local tree from the repository, which will wipe out all the changes you've made. For new files and directories not currently tracked by SVN, you have to do svn add first.

*This is a matter of maintaining different branches in the repository, which with SVN is more hassle than it's worth -- unless you don't care about merging them back, in which case it's fine. The SVN book has more information on branching and merging. If you do care deeply about branching, SVN is terrible at that -- Mercurial or another distributed version control system is does merging with considerably less pain.

*This is done by svn rename. Do not use the normal file renames that your operating system supplies, otherwise what SVN would do is to remove the first version and then add the other one, which is not what you want to do.
But there is probably a better way to handle this: use SVN tags. Tags are simply more descriptive labels to specific revisions. For example, your program with 1.0 version is taken from revision 32167, and 1.1 is revision 33341. Instead of remembering revision numbers, you can use tags to check out exactly the code that was used to produce the particular version. You can do the same in your case -- add a tag for each revision you send to a company (e.g. Company XYZ-a, and then use the normal SVN mechanisms to retrieve a specific version you'd like to use.
Now that I'm looking at these answers, I'm more and more convinced that SVN is not the right revision control system for you. If you plan to do extensive branches and merges, and maintain a plethora of different versions simultaneously, Mercurial or git might be better choices. Here is the excellent Mercurial tutorial written by Joel Spolsky, that will explain in simple terms all you ever need to know about Mercurial.


text:
Q: Sorting subitems of a TreeView in WPF when editing them I have a 2 levels TreeView that is filled with a collection items that each one has another  collection of items.
class A
{
    public List<B> collection;
}

List<A> treeViewCollection;

I'm using a ListCollectionView to sort these items using a converter in the case of the collection inside the collection as recommended here:
How to sort TreeView items using SortDescriptions in Xaml?
The problem that I've found is that the ListCollectionView does not resort the items when they are edited so I've created my own ListCollectionView class to attach to the items property notification. What I don't know is what to do now when I detect that an item has changed to resort the ListCollectionView. If I call Refresh() on the ListCollectionView I lose the selection at the TreeView, I've seen somewhere about raising the CollectionChangedNotification with a Replace action (and that sounds as a good idea to me) but it has no effect on the TreeView.
Any idea on how to update the TreeView sorting without losing all the selections and expanded items?
Thanks.


text:
Q: How to rearrange data I am trying to rearrange the data that I have to be displayed differently.
From the 4 rows, I have to the 18 rows below as per the image. Please help.

A: try it like this:
={"Team name","Player name","Country","Gender";
 QUERY({B2:B, G2:I; B2:B, J2:L; B2:B, M2:O; B2:B, P2:R; B2:B, S2:U},
 "where Col2 is not null order by Col1", 0)}