text:
Q: Android ListView with custom ArrayAdapter error when using setOnItemClickListener I've attached an xml file to modify the style of my objects shown in a list view creating a custom ArrayAdapter class. Now I want to set a listener that tells me which item has been selected by the user. Not only it gives error messages but also it doesn't execute any code within the method. I tried going back to a simple listView without a custom adapter (using one of the default ones) and it works. I already looked up here and googled the error message and it seems a problem related to SELinux permissions but I haven't changed any of those also because I have no idea on how to do it.
This is the error message:

W/RenderThread: type=1400 audit(0.0:5784638): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=21556 scontext=u:r:untrusted_app:s0:c164,c256,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0

This is the adapter:
public class CustomAdapter extends ArrayAdapter<Schedule> {

public CustomAdapter(Context context, ArrayList<Schedule> items) {
    super(context, R.layout.custom_row, items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater myInflater = LayoutInflater.from(getContext());

    View customView = myInflater.inflate(R.layout.custom_row, parent, false);

    Schedule item = getItem(position);

    TextView scheduleName = customView.findViewById(R.id.customRow_scheduleName);
    TextView scheduleStart = customView.findViewById(R.id.customRow_startDate);
    TextView scheduleEnd = customView.findViewById(R.id.customRow_endDate);

    scheduleName.setText(item.getName());
    scheduleStart.setText(item.getStartDate());
    scheduleEnd.setText(item.getEndDate());

    return customView;
}}

This is the main class which contains the listView
public class MainActivity extends AppCompatActivity implements CreateNewScheduleFragment.OnInputListener {

private ArrayList<Schedule> scheduleCollection;

private ListAdapter customAdapter;

ListView scheduleListView;
Button newScheduleBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    newScheduleBtn = findViewById(R.id.addNewSchedule);

    scheduleCollection = new ArrayList<>();

    //String[] array = {"pippo", "pluto"};

    customAdapter = new CustomAdapter(this, scheduleCollection);
    scheduleListView = findViewById(R.id.scheduleListView);
    scheduleListView.setAdapter(customAdapter);//new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));

    // #################### DEBUG
    scheduleCollection.add(new Schedule("Scheda 1", "14-3", "21-04", "ciao"));
    scheduleCollection.add(new Schedule("Scheda 2", "22-05", "5-06", "ciao"));
    ((ArrayAdapter<Schedule>)customAdapter).notifyDataSetChanged();
    // #################### DEBUG

    scheduleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("info", "I'm item in position " + String.valueOf(position));
        }
    });}

This is the layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:background="@drawable/fragment_rounded_corners"
    android:padding="8dp"
    android:layout_margin="10dp">

    <TextView
        android:id="@+id/customRow_scheduleName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="8dp"
        android:layout_marginTop="0dp"
        android:maxWidth="200dp"
        android:text="Scheda 1"
        android:textColor="@color/colorTextIcons"
        android:textSize="35dp" />

    <TextView
        android:id="@+id/customRow_startDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="20dp"
        android:layout_toStartOf="@+id/customRow_endDate"
        android:text="14-03"
        android:textColor="@color/colorTextIcons"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/customRow_endDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:text="21-05"
        android:textColor="@color/colorTextIcons"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/customRow_startDate"
        android:layout_alignStart="@+id/customRow_startDate"
        android:layout_marginBottom="10dp"
        android:text="period:"
        android:textColor="@color/colorTextIcons" />

    <Button
        android:id="@+id/customRow_cancelBtn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:background="@drawable/ic_cancel_black_24dp"/>

</RelativeLayout>

And this is the custom object class:
package com.example.fabri.gymine;

import android.util.Log;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Schedule {

    private ArrayList<Workout> workouts;
    private String name;
    private String startDate, endDate, filePath;

    public Schedule(String name, String startDate, String endDate, String filePath) {
        this.name = name;
        this.startDate = startDate;
        this.endDate = endDate;
        this.filePath = filePath;
        workouts = new ArrayList<>();

        //loadScheduleFromFile();
    }

    public void removeWorkout(Workout w){
        workouts.remove(w);
    }

    public int workoutCount(){
        return workouts.size();
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String getStartDate() {
        return startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    private String myReadLine(BufferedReader br) throws IOException{
        String tmp = br.readLine();
        Log.i("Letto", tmp);
        return tmp;
    }
}

A: @Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if an existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.custom_row, parent, false);
    }
}

Also use
   scheduleListView.setAdapter(customAdapter);

after
scheduleCollection.add(new Schedule("Scheda 1", "14-3", "21-04", "ciao"));
scheduleCollection.add(new Schedule("Scheda 2", "22-05", "5-06", "ciao"));


text:
Q: how to solve Cannot instantiate the type Workbook in java? Hi i want to copy a excel sheet from one folder to other folder but a error is being occured regularly Cannot instantiate the type Workbook i am not able to understanding this syntax error please see my code in below -
 package com.esurfer.db;

 import java.text.SimpleDateFormat;

 import com.esurfer.db.DBConn;
 import com.esurfer.db.GetExcelNo;

 import jxl.Cell;
 import jxl.CellType;
 import jxl.DateCell;
 import jxl.Sheet;
 import jxl.Workbook;
 import jxl.*;

 public class DemoFile {

// import data from excel to mysql
public boolean importdata() {

    //Create a new Workbook by excel file path
    Workbook wb = new Workbook("d:\\test\\book1.xls");

    //Create a Worksheets object with reference to
    //the sheets of the Workbook.
    WorksheetCollection sheets = wb.getWorksheets();

    //Copy data to a new sheet from an existing
    //sheet within the Workbook.
    sheets.addCopy("MySheet");

    //Save the excel file.
    wb.save("d:\\test\\mybook.xls");

    return true;
 }

private static java.sql.Timestamp getCurrentTimeStamp() {

    java.util.Date today = new java.util.Date();
    return new java.sql.Timestamp(today.getTime());

}
}

Please suggest me solve this syntax error
Thanks

A: Workbook is an abstract class, so you cannot create an instance of it.
What you can do is using its static factory method:
Workbook sourceWb = Workbook.getWorkbook(new File("d:\\test\\book1.xls"));

You can learn more at this tutorial or the API.
Take a look at getWorkbook() and createWorkbook()

A: Workbook workbook = Workbook.getWorkbook(new File("d:\\test\\book1.xls"));
You should read how it's done before doing it.

A: You have to use:
Workbook.createWorkbook(new File("d:\\test\\book1.xls"));

To create an Workbook. You cannot instantiate the class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerBI - Execute MO_GLOBAL.SET_POLICY_CONTEXT() on Connect I connecting to an Oracle database with an read only account through PowerBI.  I am looking to run a query on tables/views that the account may not have the correct view privileges.  I can run the query under the same account by using the statement below in Oracle SQL Developer.
begin
MO_GLOBAL.SET_POLICY_CONTEXT('S', #MY NUMBER HERE#);
end;

Is there a way to do this in PowerBI, or in the ODBC Oracle Driver setup, so it executes on connect or in line with my SQL statement that I am running to get my data?


text:
Q: CefSharp3 Can't navigate back I am currently using CefSharp.MinimalExample.Wpf (CEF branch 1750 and CefSharp 33.0.0) to evaluate my issue. I just added a button to the MainView.xaml like this <Button Command="{Binding WebBrowser.BackCommand}">Back</Button>. The buttons enable state is updated on loading a site (once the site is loaded it is pressable). But clicking on it doesn't work to navigate back.
My second approach was to execute a java script snippet on click browser.ExecuteScriptAsync("history.back()"); But this doesn't work either.
Any ideas?

A: I have the same problem, but your answer gave me an idea, I hope my solution works for you.
The first page showed by the browser is like a blank page, so, when this blank page is loaded, I assign the URL, through FrameLoadEnd event of the browser.
I have a flag to avoid assign the URL more than one time.
Browser.FrameLoadEnd += delegate
                        {
                            if (!flag)
                            {
                                Browser.Address = "http://www.google.com.mx";
                                flag = true;
                            }
                        };

Looks like with this the problem is solved.

A: My investigation result is that if you set the URL too early - on creation of the browser object ChromiumWebBrowser until up to about 250ms (try&error value on my machine) - at least the back-function and JavaScript-injection won't work. The Initialized event is not a solution because it is too early. Apart from this the site will be rendered fine and you can browse the web. This was the part which distracted me and let me search elsewhere.


text:
Q: Version control solution for a build system that produces a 4GB ISO I have a software project that at the last stage of its build, after creating all the jar files and related scripts/configuration files, I need to plant it in a CentOS ISO that has a kickstart config file that runs some postinstall scripts and installs some customized RPMs.
The project is on an SVN repository and being built from there. I can't insert the files of the iso into the repository because SVN doesn't handle a 4GB repository.
On the other hand, the problem is that some of the RPMs in the ISO might change from version to version, and when I want to build an older version of the project I'm in a bad place because the RPMs are not in the SVN repository.
Is there a good version control solution that I can use just for the 4GB of ISO that can handle this amount of data?
Is there a non-version-control solution to what I'm trying to do?
I would prefer to produce as less changes as possible to the existing SVN repository's structure, as there are many scripts and stuff that depend on it.
Will appreciate all kinds of answers and suggestions.
Thanks!

A: If you really need to store large artifacts (ISO, RPM, ...) for which:

*

*you don't need to compare the differences from one version to another

*you don't need to make parallel evolutions (read-only artifacts)

then you don't actually need a VCS (Version Control System).
You need an artifact repository, like for instance Nexus.
See "Best practice to store .jar files in VCS (SVN, Git, …)"
You will version in your SVN repo a text file with the necessary references to the artifact repository and its SHA1/MD5 key used when said artifacts have been stored.
The combinations of those two repositories will allow complete reproducibility, while scaling nicely (in term of repository size), since an artifact repository (contrary to a VCS) is only limited by disk space.

A: If you need reproducible build outputs, then you need to version the complete set of build inputs. That includes the RPMs, or at least a manifest of their versions if they can be reliably obtained from somewhere. Saving the generated ISO would be an exercise in futility.

A: I guess you can either check out GIT (http://git-scm.com/) - free, or Perforce (http://www.perforce.com) (costs). I think both can handle 4GB files in their repositories.

A: What about git? (http://git-scm.com)

A: Why do you have to store the ISOs or RPMs in version control?
Why not store the scripts and/or configs that can rebuild the ISOs and RPMs you need?


text:
Q: Steganography Lsb information hold capacity I know that using LSB means that u can store messages at around 12% of the image carrier size.
 I made a java program that splits a message into n fragments and fills the image carrier with these fragments until the 12 % are all occupied.I do this so that by cropping the image,the message wouldn't get lost.
 The problem is that the resulting image is distorted and different from the original image.I thought that if I fill only 12% of the image,more exactly the LSB of the image,the image wouldn't get distorted.
    int numHides = imLen/(totalLen*DATA_SIZE); // the number of messages I can store in the image
    int offset = 0;
    for(int h=0; h < numHides; h++) //hide all frags, numHides times
    for(int i=0; i < NUM_FRAGS; i++) {//NUM_FRAGS ..the number of fragments
          hideStegoFrag(imBytes, stegoFrags[i], offset);//the method that hides the fragment into the picture starting at the offset position
          offset += stegoFrags[i].length*DATA_SIZE;
    }

   private static boolean hideStegoFrag(byte[] imBytes,byte[] stego,int off){
     int offset=off;
     for (int i = 0; i < stego.length; i++) { // loop through stego
      int byteVal = stego[i];
      for(int j=7; j >= 0; j--) { // loop through 8 bits of stego byte
         int bitVal = (byteVal >>> j) & 1;
         // change last bit of image byte to be the stego bit
         imBytes[offset] = (byte)((imBytes[offset] & 0xFE) | bitVal);
         offset++;
      }
    }
    return true;
}

The code for transforming the Buffered Image into bits
       private static byte[] accessBytes(BufferedImage image)
       {
        WritableRaster raster = image.getRaster();
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        return buffer.getData();
       }

The code that creates the new image with a provided name and the buffered image of the source image
      public static boolean writeImageToFile(String imFnm , BufferedImage im){
    try {
        ImageIO.write(im, "png", new File(imFnm));
    } catch (IOException ex) {
        Logger.getLogger(MultiSteg.class.getName()).log(Level.SEVERE, null, ex);
    }
return true;

}

A: The output image you have posted is a 16-color paletted image.
The data I am seeing shows that you have actually applied your changes to the palette index, not to the colors of the image. The reason you are seeing the distortion is because of the way the palette is organized, you aren't modifying the LSB of the color, you're modifying the LSB of the index, which could change it to a completely different (and very noticeable, as you can see) color. (Actually, you're modifying the LSB of every other index, the 16-color form is 4 bits per pixel, 2 pixels per byte.)
It looks like you loaded raw image data and didn't decode it in to RGB color information. Your algorithm will only work on raw RGB (or raw grayscale) data; 3 bytes (or 1 for grayscale) per pixel. You need to convert your image to RGB888 or something similar before you operate on it. When you save it, you need to save it in a lossless, full color (unless you actually can fit all your colors in a palette) format too, otherwise you risk losing your information.
Your problem actually doesn't lie in the steganography portion of your program, but in the loading and saving of the image data itself.
When you load the image data, you need to convert it to an RGB format. The most convenient format for your application will be BufferedImage.TYPE_3BYTE_BGR, which stores each pixel as three bytes in blue, green, red order (so your byte array will be B,G,R,B,G,R,B,G,R,...). You can do that like so:
public static BufferedImage loadRgbImage (String filename) {
    // load the original image
    BufferedImage originalImage = ImageIO.read(filename);
    // create buffer for converted image in RGB format
    BufferedImage rgbImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    // render original image into buffer, changes to destination format
    rgbImage.getGraphics().drawImage(originalImage, 0, 0, null);
    return rgbImage;
}

If you are frequently working with source images that are already in BGR format anyways, you can make one easy optimization to not convert the image if it's already in the format you want:
public static BufferedImage loadRgbImage (String filename) {
    BufferedImage originalImage = ImageIO.read(filename);
    BufferedImage rgbImage;
    if (originalImage.getType() == BufferedImage.TYPE_3BYTE_BGR) {
        rgbImage = originalImage; // no need to convert, just return original
    } else {
        rgbImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        rgbImage.getGraphics().drawImage(originalImage, 0, 0, null);
    }
    return rgbImage;
}

You can then just use the converted image for all of your operations. Note that the byte array from the converted image will contain 3 * rgbImage.getWidth() * rgbImage.getHeight() bytes.
You shouldn't have to make any changes to your current image saving code; ImageIO will detect that the image is RGB and will write a 24-bit PNG.


text:
Q: import csv with pandas Please am using this common; data = pd.read_csv('diabetes_train.csv') to import my csv-file but the result is not clear
Number of times pregnant;Plasma glucose concentration;Diastolic blood pressure;Triceps skin fold thickness;2-Hour serum insulin;Body mass index;Age;Class
0   1;85;66;29;0;26.6;31;negative
1   1;89;66;23;94;28.1;21;negative
2   5;116;74;0;0;25.6;30;negative
3   10;115;0;0;0;35.3;29;negative
4   4;110;92;0;0;37.6;30;negative
... ...
662 1;128;88;39;110;36.5;37;positive
663 0;123;72;0;0;36.3;52;positive
664 6;190;92;0;0;35.5;66;positive
665 9;170;74;31;0;44;43;positive
666 1;126;60;0;0;30.1;47;positive
667 rows × 1 columns

the values are seperated from their respective columns,what should i do?

A: You need to set the separator parameter sep=… [pandas-doc] to a semicolon (;):
data = pd.read_csv('diabetes_train.csv', sep=';')
For the given sample data, this gives us:
>>> data
   Number of times pregnant  Plasma glucose concentration  Diastolic blood pressure  ...  Body mass index  Age     Class
0                         1                            85                        66  ...             26.6   31  negative
1                         1                            89                        66  ...             28.1   21  negative
2                         5                           116                        74  ...             25.6   30  negative
3                        10                           115                         0  ...             35.3   29  negative
4                         4                           110                        92  ...             37.6   30  negative
5                         1                           128                        88  ...             36.5   37  positive
6                         0                           123                        72  ...             36.3   52  positive
7                         6                           190                        92  ...             35.5   66  positive
8                         9                           170                        74  ...             44.0   43  positive
9                         1                           126                        60  ...             30.1   47  positive

[10 rows x 8 columns]


text:
Q: Check if the difference between two unsigned integers is at most 1 I'm looking for a quick way to check whether or not the difference between two unsigned integers is at most 1.
Obviously, I can do it directly via x <= y + 1 && y <= x + 1.
Another way is via x == (x + y) / 2 || y == (x + y) / 2.
But I've figured there must be a bit-wise trick to achieve that.
So I would be happy to hear suggestions.
You may assume that the two input types are identical, and that there is no overflow in adding them.

A: Since wraparound works, how about just x - y + 1 <= 2. And since -n - 1 is one's complement, i.e ~, and Solidity integers have wraparound just like C unsigned integers, then you could also use -~x - y <= 2 which has one constant less.
#include <stdio.h>

void test(unsigned int a, unsigned int b) {
    printf("%d and %d: ", a, b);
    printf("method1 %d ", a - b + 1 <= 2);
    printf("method2 %d\n", -~a - b <= 2);
}

int main(void) {
    test(1, 1);
    test(1, 2);
    test(1, 3);
    test(1, 4);
    test(2, 1);
    test(3, 1);
    test(4, 1);
}

Output:
1 and 1: method1 1 method2 1
1 and 2: method1 1 method2 1
1 and 3: method1 0 method2 0
1 and 4: method1 0 method2 0
2 and 1: method1 1 method2 1
3 and 1: method1 0 method2 0
4 and 1: method1 0 method2 0

In Solidity, bit twiddling does not really help you that much - you need to look into the gas cost table for different operations. The first does 3 verylow arithmetic operations and two pushes, the second one does 4 verylow arithmetic operations and one push, so they should be more or less comparable.

A:
I'm looking for a quick way to check whether or not the difference between two unsigned integers is at most 1.

Often a quick way ends up with a solution that works most of the time but not all - thus leaving a bug for some future coder to solve.
That is the case here with various proposed solutions.
A good alternative it to form a test harness to 1) test for correctness 2) allow profiling to assess performance.
A good approach is to let the compile optimize a certainly correct solution like ref() or methodC().

Below is a functional test harness.
#include <assert.h>
#include <limits.h>
#include <stdio.h>

int ref(unsigned int a, unsigned int b) {
  assert(UINT_MAX <= LLONG_MAX);
  long long al = a;
  long long bl = b;
  long long diff = al - bl;
  return diff >= -1 && diff <= 1;
}

int method1(unsigned int a, unsigned int b) {
  return a - b + 1 <= 2;
}

int method2(unsigned int a, unsigned int b) {
  return -~a - b <= 2;
}

int method3(unsigned int a, unsigned int b) {
  return ~a + b >= -2u;
}

int method_OP1(unsigned int x, unsigned int y) {
  return x <= y + 1 && y <= x + 1;
}

int method_OP2(unsigned int x, unsigned int y) {
  return x == (x + y) / 2 || y == (x + y) / 2;
}

int methodC(unsigned int a, unsigned int b) {
  return a < b ? ((b - a) <= 1) : ((a - b) <= 1);
}

typedef int (*fun)(unsigned int, unsigned int);

int test1(const char *s, fun f, unsigned int a, unsigned int b) {
  int y1 = ref(a, b);
  int y2 = f(a, b);
  if (y1 != y2) {
    printf("%-10s %10u and %10u: ", s, a, b);
    printf("ref %d ", y1);
    printf("method %d\n", y2);
  }
  return y1 != y2;
}

int main(void) {
  fun f[] = {method1, method2, method3, method_OP1, method_OP2, methodC};
  char *s[] = {"method1", "method2", "method3", "method_OP1", "method_OP2",
      "methodC"};
  int fn = sizeof f / sizeof f[0];
  unsigned u[] = {0, 1, 2, 3, //
      UINT_MAX - 3, UINT_MAX - 2, UINT_MAX - 1, UINT_MAX};
  int n = sizeof u / sizeof u[0];
  for (int fi = 0; fi < fn; fi++) {
    for (int ia = 0; ia < n; ia++) {
      for (int ib = 0; ib < n; ib++) {
        if (test1(s[fi], f[fi], u[ia], u[ib]) && 0) {
          ia = n;
          break;
        }
      }
    }
  }
}

Output failures
method1             0 and 4294967295: ref 0 method 1
method1    4294967295 and          0: ref 0 method 1
method2             0 and 4294967295: ref 0 method 1
method2    4294967295 and          0: ref 0 method 1
method3             0 and          1: ref 1 method 0
method3             0 and 4294967295: ref 0 method 1
method3             1 and          2: ref 1 method 0
method3             2 and          3: ref 1 method 0
method3    4294967292 and 4294967293: ref 1 method 0
method3    4294967293 and 4294967294: ref 1 method 0
method3    4294967294 and 4294967295: ref 1 method 0
method_OP1 4294967294 and 4294967295: ref 1 method 0
method_OP1 4294967295 and 4294967294: ref 1 method 0
method_OP1 4294967295 and 4294967295: ref 1 method 0
method_OP2 4294967292 and 4294967292: ref 1 method 0
method_OP2 4294967292 and 4294967293: ref 1 method 0
method_OP2 4294967293 and 4294967292: ref 1 method 0
method_OP2 4294967293 and 4294967293: ref 1 method 0
method_OP2 4294967293 and 4294967294: ref 1 method 0
method_OP2 4294967294 and 4294967293: ref 1 method 0
method_OP2 4294967294 and 4294967294: ref 1 method 0
method_OP2 4294967294 and 4294967295: ref 1 method 0
method_OP2 4294967295 and 4294967294: ref 1 method 0
method_OP2 4294967295 and 4294967295: ref 1 method 0

If we use "You may assume that the two input types are identical, and that there is no overflow in adding them." then method_OP2() failures can be forgiven.  This assumption does not directly cover
failures of other approaches.

A: A relatively simple expression that is correct for all inputs is
(x - y + (y > x)) <= 1

(assuming that > yields 0 or 1, as in C).


text:
Q: Multiple jquery-ui sliders with a set range limit I am attempting to setup multiple groups of jquery-ui sliders on a page. Each group is to be configured to have a set range limit. The code below (found from Combined total for multiple jQuery-UI Sliders ) works as intended if there is a single group of sliders on the page.
The issues arise when there are multiple groups of sliders on a single page. When there are multiple sliders the second group set appears to follow the limit rules along with the last selected slider from the first group. The first group does not appear to follow any limits for its group of sliders.
Script Code below:
var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
if(uls[i].id.indexOf('sliders')==0){

var sliders = $("#sliders" +i+ " .slider");

var size = 1000;
var size_step = 100;

sliders.each(function() {
var value = parseInt($(this).text(), size_step),
  availableTotal = size;

$(this).empty().slider({
  value: 0,
  min: 0,
  max: size,
  range: "max",
  step: size_step,
  animate: 100,
  slide: function(event, ui) {
    // Update display to current value
    $(this).siblings().text(ui.value);

    // Get current total
    var total = 0;

    sliders.not(this).each(function() {
      total += $(this).slider("option", "value");
    });

    // Need to do this because apparently jQ UI
    // does not update value until this event completes
    total += ui.value;
    var max = availableTotal - total;

    // Update each slider
    sliders.not(this).each(function() {
      var t = $(this),
      value = t.slider("option", "value");

      t.slider("option", "max", max + value)
        .siblings().text(value + '/' + (max + value));
      t.slider('value', value);
    });
  }
});
});
}
}

Page code listed below:
Slider 1

    0

    0

Slider 2

    0

    0

    0

I have setup a jsfiddle of my code and a example with two groups of sliders at:
http://jsfiddle.net/Y5ZLL/1640/

A: I made this plugin a few days ago. It supports multiple sets of groups:
https://github.com/jhovgaard/jquery.rangegroup


text:
Q: bash, sed, awk: extracting lines within a range How can I get sed to extract the lines between two patterns, write that data to a file, and then extract the lines between the next range and write that text to another file? For example given the following input:
pattern_a
line1
line2
line3
pattern_b
pattern_a
line4
line5
line6
pattern_b

I want line1 line2 and line3 to appear in one file and line4 line5 and line6 to appear in another file. I can't see a way of doing this without using a loop and maintaining some  state between iterations of the loop where the state tells you where sed must start start search to looking for the start pattern (pattern_a) again.
For example, in bash-like psuedocode:
while not done
  if [[ first ]]; then
    sed -n -e '/pattern_a/,/pattern_b/p' > $filename
  else
    sed -n -e '$linenumber,/pattern_b/p' > $filename
  fi
  linenumber = last_matched_line
  filename = new_filename

Is there a nifty way of doing this using sed? Or would awk be better?

A: How about this:
awk '/pattern_a/{f=1;c+=1;next}/pattern_b/{f=0;next}f{print > "outfile_"c}' input_file

This will create a outfile_x for every range.


text:
Q: Get top 10 most used words in text fields I have an index containing thousands of documents, each one of them having a full text field.
I want to search through all those fields and fetch the 10 most common words that come back most often.
I would also like a way of visualizing it on Kibana if that's possible.

A: The most common way to achieve that is to duplicate your full text field with a keyword datatype. That will get you able to make terms aggregation on that field - doc here. Maybe you could consider to do a significant term aggregation - doc here, thus to avoid the presence of stopwords and common words. In ES 6.x you could use also the significant text aggregation - doc here, without create the keyword field, but i never try it, i don't know how it works. Instead if you need to retrieve the frequency of the words for each document, you should use the termvector - doc here


text:
Q: Get name of function using reflection I'm trying to use Go's reflection system to retrieve the name of a function but I get an empty string when calling the Name method on its type. Is this the expected behavior?
This is a simple example of how I approach the problem:
package main

import "fmt"
import "reflect"

func main() {
    typ := reflect.TypeOf(main)
    name := typ.Name()
    fmt.Println("Name of function" + name)
}

A: import runtime

func funcName() string {
    pc, _, _, _ := runtime.Caller(1)
    nameFull := runtime.FuncForPC(pc).Name()    // main.foo
    nameEnd := filepath.Ext(nameFull)           // .foo
    name := strings.TrimPrefix(nameEnd, ".")    // foo
    return name
}

A: The solution is to use FuncForPc which returns a *Func.
This returns "main.main" :
package main

import "fmt"
import "reflect"
import "runtime"

func main() {
    name := runtime.FuncForPC(reflect.ValueOf(main).Pointer()).Name()
    fmt.Println("Name of function : " + name)
}

If you want "main", just tokenize it.

A: package main

import "fmt"
import "runtime"

func main() {
    pc, _, _, _ := runtime.Caller(0)
    fmt.Println("Name of function: " + runtime.FuncForPC(pc).Name())
    fmt.Println()

    // or, define a function for it
    fmt.Println("Name of function: " + funcName())
    x()
}

func funcName() string {
    pc, _, _, _ := runtime.Caller(1)
    return runtime.FuncForPC(pc).Name()
}

func x() {
    fmt.Println("Name of function: " + funcName())
    y()
}

func y() {
    fmt.Println("Name of function: " + funcName())
    z()
}
func z() {
    fmt.Println("Name of function: " + funcName())
}

Output:

Name of function: main.main
Name of function: main.main
  Name of function: main.x
  Name of function: main.y
  Name of function: main.z

A: This is a tested production ready utility function for returning function name.
Note 1: We are handling the possibility of a nil pointer from FuncForPC
Note 2: optFuncLevel is just a friendly name for stack frame level. This gives us the flexibility of using this within another layer of utility functions.
A direct call from say main would just pass 1 (or nothing since default), but if I am calling FunctionName in a log enriching function, say PrettyLog() that is called from regular code, I would call it as FunctionName(2) in the call from PrettyLog, so the function name returned is the name of the caller of PrettyLog, not PrettyLog itself.
// FunctionName returns the function name of the caller
// optFuncLevel passes the function level to go back up.
// The default is 1, referring to the caller of this function
func FunctionName(optFuncLevel ...int) (funcName string) {
    frameLevel := 1 // default to the caller's frame
    if len(optFuncLevel) > 0 {
        frameLevel = optFuncLevel[0]
    }

    if pc, _, _, ok := runtime.Caller(frameLevel); ok {
        fPtr := runtime.FuncForPC(pc)
        if fPtr == nil {
            return
        }
        // Shorten full function name a bit
        farr := strings.SplitN(fPtr.Name(), "/", 2)
        if len(farr) < 2 {
            return
        }
        return farr[1]
    }

    return
}


text:
Q: Keras Generative LSTM only predicting stop words I have created a model in keras using LSTM for predicting the next word given a sequence of words.Below is my code for the same:
    # Small LSTM Network to Generate Text for Alice in Wonderland
# load ascii text and covert to lowercase
filename = "wonderland.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()
print raw_text
# create mapping of unique words to integers
print raw_text
raw_text = re.sub(r'[^\w\s]','',raw_text)
raw_text = re.sub('[^a-z\ \']+', " ", raw_text)
words_unsorted=list(raw_text.split())
words= sorted(list(set(raw_text.split())))
word_to_int = dict((w, i) for i, w in enumerate(words))
int_to_word = dict((i, w) for i, w in enumerate(words))
#print word_to_int

n_words = len(words_unsorted)
n_vocab = len(words)
print "Total Words: ", n_words
print "Total Vocab: ", n_vocab

# prepare the dataset of input to output pairs encoded as integers
seq_length = 7
dataX = []
dataY = []
for i in range(0, n_words - seq_length, 1):
    seq_in = words_unsorted[i:i + seq_length]
    seq_out = words_unsorted[i + seq_length]
    #print seq_in
    dataX.append([word_to_int[word] for word in seq_in])
    dataY.append(word_to_int[seq_out])

n_patterns = len(dataX)
print "Total Patterns: ", n_patterns

# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (n_patterns, seq_length, 1))
print X[0]
# normalize
X = X / float(n_vocab)
# one hot encode the output variable
y = np_utils.to_categorical(dataY)
# define the LSTM model
model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
print model.summary()
# define the checkpoint
filepath="weights-improvement-{epoch:02d}-{loss:.4f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
# fit the model
model.fit(X, y, epochs=50, batch_size=128, callbacks=callbacks_list)

Issue is when I predict on a test sentence I always end up getting "and" as the next word prediction!Should I remove all stop words or something else?Further,I am training it for 20 epochs.

A: I'm pretty sure, based on the age of the post, you've already solved your problem. But just in case, here is my 2 cents.
You end up predicting the most frequent word. So, if you remove the stopwords, you'll be predicting the next most frequent word. There are two ways, that I know of, to deal with this problem.
First, you can use a loss that emphasizes the less frequent classes, or words in your case. Here is a research paper introducing focal loss, and conveniently, a github implementation of it for keras.
Another approach is to use class_weight in the fit function.
model.fit(X, y, epochs=50, batch_size=128, callbacks=callbacks_list, class_weight=class_weight)

where you can set the weights for words with lower frequencies higher, e.g. inversely proportional to the frequencies.


text:
Q: Read excel cell values containing formulae with pandas I am trying to read an excel with pandas but because it has formulae it will return nan values when reading it instead of the cell values.
df=pd.read_excel('Test.xlsx',sheet_name='Sheet1')

A: @Naga kiran if you want to see the value instead of the formula you can add:
wb = load_workbook('empty_book.xlsx', data_only=True)

But openpyxl never evaluates formula (https://openpyxl.readthedocs.io/en/latest/usage.html#using-formulae)
You need to open the empty_book.xlsx with Excel and save it if you want to see the formula result

A: This question is a quite stale but I didn't find another one that explicitly answer's the OP's question. Assuming you're opening a .xlsx file and not a .xls, you can do:
workbook = openpyxl.load_workbook(filename=excel_path, data_only=True)
data = pd.read_excel(workbook, sheet_name='Sheet1', engine='openpyxl')

Note that pandas reads .xls files with xlrd, and I'm not sure what the best way to achieve the same thing with that library would be.


text:
Q: Understanding ANR logs provided by Android Vitals in the Play Store Console I am getting an instance of a telephonymanager (single or multisim devices) and got several ANRs. I have managed to work through most of them but this one persists:
*Broadcast of Intent { act=android.intent.action.SCREEN_OFF flg=0x50000010 (has extras)
What's the best way to deal with this? Some of these were only reproducible when leaving the app open and the device's screen on for several hours. This makes it difficult to debug ANRs such as these.
There is a part in the report that says that the running is "locked". How do I distinguish if this is a deadlock or when the thread is waiting for the current operation to complete? The callbackDataConnectionStateChanged(), refreshTelephonyState() methods are synchronized
"main" tid=1 Native
"main" prio=5 tid=1 Native
  | group="main" sCount=1 dsCount=0 obj=0x75bf6598 self=0xb87af970
  | sysTid=7874 nice=0 cgrp=default sched=0/0 handle=0xb6f90b4c
  | state=S schedstat=( 54620404003 32316399006 164607 ) utm=3795 stm=1667 core=1 HZ=100
  | stack=0xbe13c000-0xbe13e000 stackSize=8MB
  | held mutexes=

  #00  pc 0000000000016978  /system/lib/libc.so (syscall+28)

  #01  pc 00000000000f5e43  /system/lib/libart.so (_ZN3art17ConditionVariable4WaitEPNS_6ThreadE+82)

  #02  pc 00000000003e4da3  /system/lib/libart.so (_ZN3artL12GoToRunnableEPNS_6ThreadE+502)

  #03  pc 00000000000e541d  /system/lib/libart.so (_ZN3art12JniMethodEndEjPNS_6ThreadE+8)

  #04  pc 0000000000f31ddd  /system/framework/arm/boot.oat (Java_android_os_BinderProxy_transactNative__ILandroid_os_Parcel_2Landroid_os_Parcel_2I+152)

  at android.os.BinderProxy.transactNative (Native method)

  at android.os.BinderProxy.transact (Binder.java:503)

  at com.android.internal.telephony.ISub$Stub$Proxy.getDefaultSubId (ISub.java:893)

  at android.telephony.SubscriptionManager.getDefaultSubId (SubscriptionManager.java:992)

  at android.telephony.TelephonyManager.getDefaultPhone (TelephonyManager.java:3995)

  at android.telephony.TelephonyManager.getSimOperatorName (TelephonyManager.java:2152)

  at com.test.api.tools.testTelephonyManager.getSimOperatorName (testTelephonyManager.java:434)

  at com.test.api.DataCollector.refreshTelephonyState (DataCollector.java:1520)
- **locked** <0x0fdf1bd6> (a com.test.api.DataCollector)

  at com.test.api.DataCollector.callbackDataConnectionStateChanged (DataCollector.java:675)
- **locked** <0x0fdf1bd6> (a com.test.api.DataCollector)

  at com.test.api.DataCollectorSystemListener$MccServicePhoneStateListener.onDataConnectionStateChanged (DataCollectorSystemListener.java:241)
- locked <0x09fe3e57> (a com.test.api.DataCollectorSystemListener$MccServicePhoneStateListener)

  at com.test.api.tools.MultiSimListener.onDataConnectionStateChanged (MultiSimListener.java:70)

  at android.telephony.PhoneStateListener$1.handleMessage (PhoneStateListener.java:326)

  at android.os.Handler.dispatchMessage (Handler.java:102)

  at android.os.Looper.loop (Looper.java:158)

  at android.app.ActivityThread.main (ActivityThread.java:7231)

  at java.lang.reflect.Method.invoke! (Native method)

  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)

  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)


text:
Q: How to connect GAE to Amazon RDS? I have a database instance on Amazon RDS which is configured:
Amazon RDS Instance
My VPC Security group, both Inbound and Outbound are configured like below:
VPC Security Group
My VPC DNS Resolution and DNS Hostnames are activated.
I can connect to this instance and execute queries without problems from MySQLWorkbench.
I'm configuring it in my GAE Eclipse using persistence.xml:
 <persistence-unit name="myworld">
   <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider >

   <!--             MODELS            -->
   ...

   <properties>
       <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
       <property name="javax.persistence.jdbc.url" value="jdbc:mysql://myworld.cy3caqn3kkz0.eu-west-1.rds.amazonaws.com:3306/myworld"/>
       <property name="javax.persistence.jdbc.user" value="myworld"/>
       <property name="javax.persistence.jdbc.password" value="******"/>
       <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
   </properties>

And my appengine_web.xml:
<threadsafe>true</threadsafe>

 <system-properties>
    <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
    <property name="ae-cloudsql.cloudsql-database-url" value="jdbc:mysql://myworld.cy3caqn3kkz0.eu-west-1.rds.amazonaws.com:3306/myworld?user=myworld&password=******" />
    <property name="cloudsql.url" value="jdbc:mysql://myworld.cy3caqn3kkz0.eu-west-1.rds.amazonaws.com:3306/myworld?user=myworld&password=******"/>
 </system-properties>

I'm able to connect and execute queries when I start my GAE project locally and everything works fine but when I deploy it online I receive the following exception:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
Error Code: 0

I have read lots of posts, blogs, questions and answers on stackoverflow but I didn't figured out what I'm doing wrong.
Please, any suggestion, clue, tip will be very appreciate once I'm trying to fix it for the last whole week.
Thanks you guys!

A: I finally could get it working!! It sounds stupid for me but it can be useful for someone who can be experiencing the same problem.
Everything was fine with the projects and their configuration, the only thing I didn't do was activate the billing for my PROJECT.
Yes, you activate you billing account as soon as you create an account on GAE BUT when you create a project you need to LINK YOUR PROJECT BILLING TO THE BILLING ACCOUNT YOU HAVE CREATED.
That's it. I hope it helps someone else.


text:
Q: Why doesn't this jquery (hover) effect get called when the conditions (removeClass) are met? Here is the code link http://codepen.io/anon/pen/kzJvl (full code below)
The code should remove all instances of the class .gigante
$('.gigante').removeClass('gigante');

so therefore the hover effect which works on all the items without .gigante
$civs.hover(function() {
    $(this).addClass("colorise");
}, function() {
    $(this).removeClass("colorise");
});

should be active on all the elements in the code? should it not?
Yet the second div item still appears to have a remnant of that class or something I don't comprehend
Full code of pen:
JavaScript:
var $gigante = $('.gigante');
var $civs = $(".civ-item:not(.gigante)");

// HOVER
$civs.hover(function() {
    $(this).addClass("colorise");
}, function() {
    $(this).removeClass("colorise");
});

// REMOVE CLASS
$civs.bind('click', function() {
    $('.gigante').removeClass('gigante');
});

CSS:
.civ-item{
 float:left;
 background-color: #2D2D2D;
 width: 238px;
 height: 160px;
 border: 1px solid red;
 margin-bottom: 2px;
 }
 .gigante {
    width: 478px;
    height: 600px;
 }
.colorise {
  background-color: blue;
}

HTML:

A:
should be active on all the elements in the code? should it not?

No, because your $civs variable was filled in with the list of elements before you removed the class.
You have at least three options:

*

*Event delegation - You hook the event on a container of the elements in question (ideally something close to them, but you can use document in the worst case), but tell jQuery you only care about the event if it passed through something matching the selector. In your case, you'd hook mouseenter for your entering logic and mouseleave for your exiting logic.
var $gigante = $('.gigante');

// HOVER
$(document)
  .on("mouseenter", ".civ-item:not(.gigante)", function() {
    $(this).addClass("colorise");
  })
  .on("mouseleave", ".civ-item:not(.gigante)", function() {
    $(this).removeClass("colorise");
  })
;

// REMOVE CLASS
$(".civ-item").bind('click', function() {
  $('.gigante').removeClass('gigante');
});

*When you remove the class from the elements, re-query the new set of $civs elements an rebind your handler:
function civsHandler() {
    $('.gigante').removeClass('gigante');
    $civs = $(".civ-item:not(.gigante)"); // Of course, there aren't any anymore,
                                          // but I'm allowing for the case where
                                          // you only remove some or something
    $civs.unbind('click').bind('click', civsHandler);
}
$civs.bind('click', civsHandler);

*Bind to all .civ-item elements:
var $civs = $(".civ-item");

...and check when the hover occurs whether it has the gigante class:
$civs.hover(function() {
  if (!$(this).hasClass("gigante")) {
    $(this).addClass("colorise");
  }
}, function() {
  if (!$(this).hasClass("gigante")) { // You may or may not want this check
    $(this).removeClass("colorise");
  }
});


text:
Q: How this vector spans $\mathbb R^3$? I am having trouble to understand why this given vector spans $ \mathbb R^3$.
$V=\left\{\begin{bmatrix}-4\\-6\\0\end{bmatrix},\begin{bmatrix}2\\-1\\-4\end{bmatrix}\right\}$
I understand that a non-zero determinant shows that the given set spans the space. However, this is not the square matrix. Therefore, I can not use determinant. I searched online and found this thread.
How to tell if a set of vectors spans a space?
According to this thread, we can use row reductions to calculate the rank of the given matrix. If it is equal to space, we can say that it spans this. I tried to row reduce this and end up with
$\begin{bmatrix}1\\0\\0\end{bmatrix},\begin{bmatrix}0\\1\\0\end{bmatrix}$
This shows that the rank is $2$. Therefore, please explain how to arrive at the solution and why it spans $\mathbb R^3$. I know there are lots of questions about spanning sets. I am still kinda confused about calculating spans. I use the following procedure:
$1)$ if the matrix is square, non-zero determinant shows span. If not, rank tells span.
Please guide me is this correct way? or should I use any other procedure?
Thanks. please explain in detail.

A: The set $\{(−4, −6, 0), (2, −1, −4)\}$ does not span $\mathbb R^3$. The set contains only two vectors, so its span is at most $2$-dimensional. In fact, since $(−4, −6, 0)$ and $(2, −1, −4)$ are linearly independent, the span is exactly $2$-dimensional.


text:
Q: Usar Double no método compareTo Estou com uma dúvida.
Tenho varios métodos de comparação, porém, um dos atributos utilizados para fazer a comparação é double.
Aí ocorre um erro:

Cannot invoke compareTo(double) on the primitive type double

Tentei converter o double para String. Porém ele ordena errado.
Ele ordena por ordem "alfabética".
Exemplo, ordena os valores assim:
10, 1000, 1002, 20, 30 , 300, 40.

Quando era pra ordenar assim:
10, 20 ,30 ,40 , 300, 1000 e 1002.

Aqui esta meu código:
<%!
public static class Empreendimento implements Comparable<Empreendimento>{

// ignorar os construtores, métodos e atributos

// Para ordenar por Menor Preco
    public static void ordenaPorMenorPreco(List<Empreendimento> ArrayResultadoBusca) {
        Collections.sort(ArrayResultadoBusca, new Comparator<Empreendimento>() {
            //@Override
            public int compare(Empreendimento emp1, Empreendimento emp2) {
                return emp1.getPrecoMenor().compareTo(emp2.getPrecoMenor());
            }
        });
    }

%>

A: O autoboxing não está de ajudando.
Tenta fazer assim:
return Double.valueOf(emp1.getPrecoMenor()).compareTo(Double.valueOf(emp2.getPrecoMenor()));

Espero que ajude.

A: Como pode-se ver na mensagem de erro:

Cannot invoke compareTo(double) on the primitive type double

Você está tentando acessar um método em um tipo primitivo, mas tipos primitivos não tem métodos, somente os objetos. Você está trabalhando como se estivesse usando o objeto da classe wrapper Double ao invés do tipo primitivo double.
Você tem três formas de resolver isso:

*

*Mudar tanto o retorno do método getPrecoMenor quanto a variável que ela retorna; ou

*Fazer a conversão na hora que for comparar, igual sugerido na outra resposta; ou ainda

*Ao invés de usar o método compareTo() poderia fazer assim:
return emp1.getD() > emp2.getD() ? 1 : emp1.getD() < emp2.getD() ? -1 : 0 ;

Que é basicamente a mesma solução do @Thiago, mas usando dois operadores condicionais ternários. Fica menos legível mas fica mais compacto, deixando a critério do desenvolvedor qual melhor lhe atende.
A terceira opção se dá pois o método compareTo(), de acordo com a documentação, retorna:

the value 0 if anotherDouble is numerically equal to this Double; a value less than 0 if this Double is numerically less than anotherDouble; and a value greater than 0 if this Double is numerically greater than anotherDouble.

Em tradução livre, o método retorna:

o valor 0 se o outro double é numericamente igual ao do objeto que invocou o método; um valor menor que 0 se o valor for menor que o outro double; e um valor maior que 0 se ele for maior que o outro.

A: Tente da seguinte forma:
     Collections.sort(lst, new Comparator<Empreendimento>() {
        @Override
        public int compare(Empreendimento o1, Empreendimento o2) {
            if(o1.getPrecoMenor() > o2.getPrecoMenor()){
                return 1;
            }else if(o1.getPrecoMenor() < o2.getPrecoMenor()){
                return -1;
            }else
                return 0;
        }
    });


text:
Q: Typescript output filename change I'm outputting my typescript project to single js files but want to change the name of the output files to filename.debug.js instead of filename.js. Is this possible.
This *.debug.js files then go through a minimizer and get outputted to *.js
Using TS with VS 2012.
Thanks
Donal

A: You can change this in the in the csproj file. In there you find some TypeScript tags (For example TypeScriptTarget, TypeScriptModuleKind).
Just put the following there:
<TypeScriptOutFile>test.debug.js</TypeScriptOutFile>

Make sure you put it in the right place for debug/release configurations.
For vs2013 users, you can just go to the project properties page and there you find the "TypeScript Build" tab on the left. There you find the option: Combine Javascript output (which adds the above xml)


text:
Q: mvnw: Permission denied on JHipster spring boot application When I try to clone and run jHipster spring boot application using ./mvnw command, it getting an error mvnw: Permission denied. How can I solve it?

A: if you use dockerfile, you should add chmod +x mvnw
RUN chmod +x mvnw


text:
Q: Decoding H264 Stream Fails Eventually After many weeks trying to connect to my home cctv in my c++/Qt project using libav on my raspberry pi (armv7) I am able to correctly display my camera for a good while (at least 20 minutes) with hardly any NAL warnings in the console (but some warnings about invalid NAL unit). However, eventually I will just start to see just a grey screen and lots of NAL warnings in the console and I have to close and reopen the connection to get my camera displaying correctly. I have searched the internet many times to make sure I am understanding av_parser_parse2 correctly and I think I am.
I have pasted my 3 main functions below in the hope that somebody can tell me - is there more to decoding a h264 stream using libav than I understand currently?
Thank you.
void MainWindow::playStreamToScreen(MainWindow* app)
{

avcodec_register_all();

codec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec) {
    qDebug() << "codec not found\n";
    return;
}

c = avcodec_alloc_context3(codec);
/* if(codec->capabilities & CODEC_CAP_TRUNCATED)
    c->flags |= CODEC_FLAG_TRUNCATED;
if(codec->capabilities & CODEC_FLAG2_CHUNKS)
    c->flags |= CODEC_FLAG2_CHUNKS;*//* We may send incomplete frames */
picture = av_frame_alloc();
pFrameRGB=av_frame_alloc();
int  numBytes=avpicture_get_size(pix_fmt_dst, myWidth, myHeight);
buffer= (uint8_t*)malloc(numBytes);
if(avpicture_fill((AVPicture *)pFrameRGB, buffer, pix_fmt_dst,
                  myWidth, myHeight) < 0)
{
    qDebug() << "failed fill picture";
}
if (avcodec_open2(c, codec, NULL) < 0) {
    qDebug() << "could not open codec\n";
    return;
}

frame = 0;

if(parser == NULL)parser = av_parser_init(AV_CODEC_ID_H264);
if(parser == NULL)
{
    qDebug() << "after init parser is null";
    return;
}
parser->flags |= PARSER_FLAG_ONCE;

struct timeval t;
float inv_fps2;// = 4;
int ii = 0;
inv_fps2 = 1e6/9.98;//av_q2d(c->time_base);
qDebug() << "before timebase";
c->time_base = (AVRational){1,10};
c->bit_rate =  251000;
c->width = 352;
c->height = 288;
c->pix_fmt = AV_PIX_FMT_YUV420P;

if(img_convert_ctx == NULL)
{

    img_convert_ctx = sws_getCachedContext ( img_convert_ctx, c->width, c->height,
                                             AV_PIX_FMT_YUV420P, myWidth, myHeight,  AV_PIX_FMT_RGB555,
                                             SWS_LANCZOS | SWS_ACCURATE_RND , NULL, NULL, NULL );
}

running = true;
int retval;
gettimeofday(&t, 0);

}

void MainWindow::display_frame(AVCodecContext* cc, AVFrame *frame, SwsContext* img_convert_ctx, MainWindow* app)
{

sws_scale ( img_convert_ctx, frame->data, frame->linesize, 0,
            288, pFrameRGB->data, pFrameRGB->linesize );

app->currentImage = QImage(pFrameRGB->data[0], app->myWidth, app->myHeight, pFrameRGB->linesize[0], QImage::Format_RGB555) .copy();// - See more at: http://www.mzan.com/article/30784549-best-simplest-way-to-display-ffmpeg-frames-in-qt5-solved.shtml#sthash.RvAFLQsc.dpuf
QImage img2 = app->currentImage.scaled(app->width(), app->height(), Qt::KeepAspectRatio);
QMetaObject::invokeMethod(app->myLabel, "setImage", Qt::QueuedConnection, Q_ARG(QImage, img2));
app->myLabel->setFixedSize(app->width(), app->height());

}

void MainWindow::socketReadyRead()
{
    if(connectingToLive && i  == 0)
    {
    qDebug() << "starting live stream";
    i++;
    this->playStreamToScreen(this);

    }
    else if(connectingToLive && i > 0)
    {
    QByteArray temp;
    int inbuf_start = 0;
    int inbuf_len = 0;

    temp.append(socket->readAll());//reads from network here

    inbuf_len = temp.size();
    inbuf_start = 0;

    int out_size;

    while (inbuf_len)
    {
        av_init_packet(&packet2);
        packet2.data = 0;
        packet2.size = 0;
        len = av_parser_parse2(parser, c, &packet2.data, &packet2.size,
                               (uint8_t*)temp.constData()+ inbuf_start, inbuf_len,
                               AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);

        inbuf_start += len;
        inbuf_len -= len;

        if(packet2.size == 0 && len >= 0)
        {

            break;

        }

        else if(len)
        {

            retval = avcodec_decode_video2(c, picture, &got_picture, &packet2);

            if (got_picture && retval > 0)
            {
                display_frame(c, picture, img_convert_ctx, this);

            }

        }

    }

}

}


text:
Q: multiple selects select the same option In my project, i have a table where various interventions are inserted based on previous selections. In case of more interventions, on the select if I go to select a value on the first intervention, it will also change on the second intervention. How can I make selections independent?

*

*summary.html

      Interventions:
      Surface Type:
      Price:

    <ng-container *ngFor="let element of intervention; index as j">

        {{element.int.code}}

          <select multiple [(ngModel)]="surface_type">
            <option selected disabled [value]="0">Select</option>
            <option [value]="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>
            <option [value]="2" [attr.disabled]="element.pricePlast === 0 ? 'disabled' : null">Plastered Surface</option>
            <option [value]="3" [attr.disabled]="element.priceBoth === 0 ? 'disabled' : null">Both Surface</option>
          </select>

        {{element.priceVis}}€/{{element.unit}}
        {{element.pricePlast}€/{{element.unit}}
        {{element.priceBoth}}€/{{elemento.unit}}

    </ng-container>

*

*summary.ts
intervention: Intervention[] = []
surface_type: number: 0

A: <option [value]="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>

[] as an attribute will be a one way binding of data with the variable that comes inside the ""
so, for your case [value]="1" means you are assigning a variable 1 to the value attribute, and not the value 1 to value attribute.
for that to happen, you have to write as
value="1"

so finally, your code should look like
<option value="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>

You will have to make the similar changes on all the option tags to make this work.
Please check the docs of angular's property binding for more details.
Also
For the variable surface_type is the same for all the loops. so you will either have to change that to an array just like what Erik commented. or you will have to keep a variable surface_type on each of the object inisde intervention array. and replace every insance to
element.surface_type

Your interface Intervention should look something like this
interface Intervention {
   ... your objects ...
   surface_type: number|string

}

A: The <select> elements you generate all store their selected value in the surface_type variable. You could change surface_type into an array by changing the ngModel statement into: [(ngModel)]="surface_type[j]" Where I use the j index from your *ngFor.

A: As noted by Erik, you need to have your ngModel be an array:
<select multiple [(ngModel)]="surface_types[j]">
And secondly - you need to import FormsModule package into your Angular module:
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
         FormsModule
    ]

I've created Sandbox on Stackblitz, you can inspect that:
https://stackblitz.com/edit/angular-qsxgaz?file=src%2Fapp%2Fproduct-list%2Fproduct-list.component.html


text:
Q: Excel Filter Formula/Function - return the first row from the filter formula/function Hi so I have a function as following;
=FILTER(A:M,(B:B=P4) * (C:C=Q4) * (F:F>=R4))

the formula returns an array with all conditions met.
I was wonder if there is a way to return the only first row from the filtered array?
Thanks.

A: Use at @ symbol to return only first value (not full row). If you want to return full row then you need Index function then define row number like 1.
=@FILTER(A:M,(B:B=P4) * (C:C=Q4) * (F:F>=R4))

Use above formula to return only first value. and below will return first row.
=INDEX(FILTER(A:M,(B:B=P4) * (C:C=Q4) * (F:F>=R4)),1)

A: You could just INDEX it.
=INDEX(FILTER(A:M, ((B:B=P4)*(C:C=Q4)*(F:F>=R4))), 1)


text:
Q: Best Practise for custom home page Creating a theme for a site I am working on and would like to know what would be the best solution for my problem.
On the home page I would like a full width slider under the header ( I have the header all built). Under the slider I would like a left column which has the navigation for product categories and the main body to the right of that with Sale and Clearance items product view.
I'm not sure if possible but should I set the home page as a 2 column and add the slider in or make the homepage a one column and do it that way.
If I do do it one of these ways what would be the best way to implement the slider.
I'm using CE lastest version the slider I'm looking at implementing is http://www.jssor.com/demos/simple-fade-slideshow.html
I'm also using the bootstrap framework for the theme as well.
Any input would be great, thanks

A: So the question is actually about page layout and there are 2 ways to achieve it.

*

*Either put your slider into the template/page/html/header.phtml of your theme and then wrap it into the "if" clause which will check if the current page is home or not.

*Modify template/page/2columns-left.phtml of your theme calling a new block between header and main content area. Of course you also have to define a block itself and add it under the cms_index_index layout handle.

A: you can just edit CMS page, or if you want more advanced homepage, you can create new page template.
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/0_-_theming_in_magento/adding_cms_layout_templates


text:
Q: What does the linux "file" command consider "suspicious"? I was playing with the file command (the command-line utility used to identify file types) and I noticed one of the types it could match was "Suspicious"
What does that actually mean, what kind of files match it? Is there some program called "suspicious" that produces data file can identify? Does it match executable data that's in a file with a non-executable extension?

A: The magic numbers definitions used by the file command are stored in these files.
The only occurrence of the description Suspicious points to a certain byte in Flash files. It's actually the only occurrence of the string in the whole project.


text:
Q: Google Maps - can't click on marker in my styled map i've been looking for a way to add a 100% width and specific map, that has some styling on and shows the marker for the address.
i found an example that Google Maps APIs page provides ( https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple ) and applied some styles to it. if i get Google's entire code and save it in it's own html file, it works prefect. however, when i send this code to my complete page, it won't let me click on the marker!
this is the address i'm using for testing now: http://uno.ag/contato5.html
any ideias?
thank you in advance! ;)
function initialize() {
  var myLatlng = new google.maps.LatLng(-23.582423, -46.641885);
  var mapOptions = {
    zoom: 16,
    center: myLatlng,
    styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
  };

  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

  var contentString = '
'+
      '
'+
      '
'+
      '

'+
      '
'+
      'Rua Ambrosina de Macedo, 174
' +
      'CEP 04013-030
 '+
      '(11) 5579 2062 '+
      '
'+
      '
';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      optimized: true,
      clickable: true,
      title: 'UNO+BRAND'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

A: Your wrapper div is on top of it, making it unlickable. You'll notice you can't move the map either, unless you try on the sides. If you F12, and set display:none; on div#wrapper you'll see it works just fine.

A: On inspecting your code, it seems the problem is you #wrapper container.

....

remove it and the marker becomes clickable.
Updates:
I would suggest to remove height: auto !important; in your styles of #wrapper this will fix the problem rather than setting the z-index and always be careful in using !important.


text:
Q: Regular expression to replace match keywords outside html tags AND anchor (a) tag text I am developing an asp.net application. I want to add a keyword linking system.
I want to make the keyword a hyper-link to another page. But, I should not link the keyword if its currently linked (to any page). For example:
it is a linked keyword and it should be a linked keyword.

should convert to:
it is a linked keyword and it should be a linked keyword.

As you can see, the first keyword should be left intact.
Could you help me please to solve this problem?
I've found this link in asp.net forums. But I should tune the answer to exclude currently linked keywords. I've searched everywhere but found nothing.

A: To check if the keywords is "outside", look ahead

*

*(?= if after the keyword there's an opening <tag or the $ end

*[^<>]* any amount of characters, that are NOT > OR <

*followed by (?:<\w|$) where \w is a shorthand to word-charcters [a-zA-Z_0-9]
So the pattern could look like:
String pattern = @"(?i)\bkeyword\b(?=[^<>]*(?:<\w|$))";

String replacement = @"\0";

Put the keyword into word-boundaries \b and used (?i) i modifier for case insensitive.
So this would only replace keyword that is followed by an opening-tag or the end.

UPDATE: To replace keyword also "inside" tags, that don't end up with </a add |<\/[^a]:
String pattern = @"(?i)\bkeyword\b(?=[^<>]*(?:<\w|<\/[^a]|$))";

A: Don't use regular expressions for sophisticated HTML parsing like this. Use a proper HTML parser instead — here's why.


text:
Q: Who was first in precedence inside the House? In Sir Thursday we find:

'I do beg your pardon, ma'am,' said the lieutenant. 'Crosshaw is my name, recruiting officer. I have a draft requisition for one Arthur Penhaligon, only I think there must be a mistake, as it gives this Arthur a precedence within the House of … well … six. I thought perhaps there might be a large number of zeroes missing. Perhaps if there is someone among Mister Monday's staff called Arthur Penhaligon, I might test the draft document?'
'There is no mistake,' said Dame Primus. She indicated Arthur with a lofty wave of her hand. 'The person in question is Lord Arthur Penhaligon, Master of the Lower House, Lord of the Far Reaches, Duke of the Border Sea, sixth in precedence within the House. I am Dame Primus, Parts One, Two, and Three of the Will of the Architect.'

How is Arthur only sixth? There's Sir Thursday, Lady Friday, Superior Saturday and Lord Sunday, leaving Arthur fifth.
If you count the Piper, the Old One and The Mariner he should be lower down in precedence.
So how is Arthur only sixth? And who is the missing one?

A: The Architect.
There's really only one option for someone who would be at the top of the hierarchy, or anywhere else in it. The Piper and the Mariner aren't part of the House hierarchy, since they were a consequence of some of the Architect's experiments with mortality. The Old One almost certainly counts as just another part of the Architect, or perhaps has no rank, being imprisoned. It's also plausible that this refers to Dame Primus, whose name, after all, signifies that she is the first, and who is the largest part of the Architect who's still free.
This, of course,  is an early hint that the Architect is not entirely dead.


text:
Q: How can i replace values in a column using pandas? It's my first time using python and pandas (plz help this old man). I have a column with float and negative numbers and I want to replace them with conditions.
I.e. if the number is between -2 and -1.6 all'replace it with -2 etc.
How can I create the condition (using if else or other) to modify my column. Thanks a lot
mean=[]

for row in df.values["mean"]:
    if row <= -1.5:
        mean.append(-2)
    elif row <= -0.5 and =-1.4:
        mean.append(-1)
    elif row <= 0.5 and =-0.4:
        mean.append(0)
    else:
       mean.append(1)
df = df.assign(mean=mean)

Doesn't work

A: create a function defining your conditions and then apply it to your column (I fixed some of your conditionals based on what I thought they should be):
df = pd.read_table('fun.txt')
# create function to apply for value ranges
def labels(x):
    if x <= -1.5:
        return(-2)
    elif -1.5 < x <= -0.5:
        return(-1)
    elif -0.5 < x < 0.5:
        return(0)
    else:
        return(1)

df['mean'] = df['mean'].apply(lambda x: labels(x)) # apply your function to your table
print(df)

another way to apply your function that returns the same result:
df['mean'] = df['mean'].map(labels)

fun.txt:
mean
0
-1.5
-1
-0.5
0.1
1.1

output from above:
   mean
0     0
1    -2
2    -1
3    -1
4     0
5     1


text:
Q: Stop Do you want to open facebook prompt when i called "logInWithReadPermissions" method in iOS I am using iOS SDK Facebook to login into my app. I have a Facebook login button (my own button, not the one provided) and it shows perfectly either the Facebook App (if is installed) or the Safari, and after that the facebook login page.
ISSUE: When i installed facebook and i click login with facebook button its asking "Do you want to open facebook" with open and cancel button. when i click open button the handler calling automatically.
 [login logInWithReadPermissions:@[@"public_profile",@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
                //Checking for success login
                if (result) {
                    //user login successfully, get user information

                } else {
                    //user login failed
                    NSLog(@"facebook error %@", error);
                }
            }];

When i tried to get user inoformation in success method iam getting error.How can i stop asking prompt Do you want to open facebook when i click on  facebook button first time. And why success block is calling when i press open button.

A: Change the login behavior to:
login.loginBehavior=FBSDKLoginBehaviorWeb;

As default login behavior is via the application or native safari browser.
Changing it will prevent prompt from opening.


text:
Q: segmentation fault in txt parsing C Hi I'm trying to parse a txt file with 2 doubles in every line. At the first line there is an integer that is the total number of lines of the txt file. I have a Nx2 matrix of doubles COORD[NPOIN][2] and i want to put the first double of every txt line into COORD[IPOIN][0] and the second into COORD[IPOIN][1]. The part of the code below should enlighten you :D
COORD = (double**)malloc(NPOIN*sizeof(double*));

for(int i=0; i<NPOIN; i++)
{
  COORD[i] = (double*)malloc(NDIME*sizeof(double));
}

fin = fopen("coord", "r");
fgets(line, 256, fin);
NPOIN = atoi(line);
char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++)
{
   fgets(line, 256, fin);
   token = strtok(line," \t" );
   COORD[IPOIN][0] = atof(token); //line 891
   token = strtok(NULL, " \t");
   COORD[IPOIN][1] = atof(token);

}

I compile the code,everything ok.But when I run it the gdb shows segmentation fault in line 891.Can anyone give some advice?I'm stuck!

A: Here's how you debug with printf:
although you should really learn to step through your code with GDB or another debugger
fin = fopen("coord", "r");
if (fin == NULL)  printf("failed to open\n");

fgets(line, 256, fin);
printf("Got first line as %s\n", line);

NPOIN = atoi(line);
printf("NPOIN is now %d\n", NPOIN);

char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++){
      fgets(line, 256, fin);
      printf("Got a line as %s\n", line);

      token = strtok(line," \t" );
      printf("Got token #1 %s\n", token);

      COORD[IPOIN][0] = atof(token); //line 891
      printf("Found float %f\n", COORD[IPOIN][0]);

      token = strtok(NULL, " \t");
      printf("Got token #2 %s\n", token);
      COORD[IPOIN][1] = atof(token);
      printf("Found float %f\n", COORD[IPOIN][1]);
}


text:
Q: Can I save multiple command arguments for VS2012 debugging Summary: Is there an easy way to save alternate command arguments used by the Visual Studio debugger?
Details:
Visual Studio has an option to set Command Argument that are used by the debugger.  For example in the screenshot shown here I've set them to FOO BAR.  Sometimes when debugging a project I want to switch the arguments to test different input sets.  And often the arguments are much longer than just FOO BAR.  It would be nice if there was a way to save the arguments that I've typed and switch between them quickly.  Ideally it would also be possible to change the working directory at the same time.  But I haven't found a way to do this yet so that's why I'm asking here.  I'm using Visual Studio Professional 2012.

A: You can just create new configuration(s) for this project. I see that your current active configuration is Debug (top left corner of project settings dialog). You can create new configuration(s), which will be based on this one, and name them like Debug-Test1, Debug-Test2, etc. After you will do this you will have a choice to switch between this configurations in VS Debug Toolbar.


text:
Q: Can I power a LED controller (Pixlite 4) with a 5V 30amp power supply I bought a pixlite 4, LEDs(5V) and a 40A-5V PSU.
I have 2 questions:
1- I dont't want to cause any damage to the controller and I'm wondering if I can connect my PSU straight to the controller. (the manual says that the controller is limited to 30amps and my PSU provides 40amps)
2- Can I do the same a Q1 above with my LEDs, 5m of strip needs 9amps without blowing out the LEDS ?
Controler user manual: https://www.advateklights.com/downloads/user-manuals/pixlite-4-mk2
Thanks in advance! :)

A: Don't worry.
If the device is 5V, and the PSU is 5V too, the device will draw from the PSU only the current that the device needs to work; the PSU will feed the device only with the specific current that the device "asks".
40 A is the MAXIMUM current that the PSU is able to supply. But if both the PSU and the device are 5V, the PSU will not "force" more current into the device than the device "asks" for.
It doesn't matter if you connect this 5V PSU to a 5V device that needs 1 A, 0.0001 A, 20A, 30 A, or 40 A.
If you have a 3,000 A @ 5V power supply, you can charge your phone with it, even if the phone needs only 1A.
There will be some problems if the device needs MORE than the 40A that the PSU can supply (the device won't work and/or the PSU will overheat or fail).
And don't connect LEDs directly to a power supply. LEDs always need resistors. Most strips of LEDs have resistors built-in, but you should check it before connecting them to the PSU.


text:
Q: Comunicate to server with different languages I have a server made with nodeJS. And I have created a simple application, that comunícate with the client using socketIO.
I need make possible that the users can connect to this app with other languages (Python, Java...), but I don't know how to make this.
For example, I start the server in xxx.xxx.xxxx:xxx, users can connect to this server with a script, and maintain a communication with him.
Is it possible using SocketIo? What other ways I can follow?
Thanks!

A: So long as all the clients talk with the same protocol it should work. However, you might need to implement the socket.io stuff in each of the target clients if one does not exist yet.

A: All languages have their way of connecting to a server, and they don't care what language the server is written in. The important thing is that you transfer the data over a universal format such as JSON (pretty much every language has a library that can parse JSON)
Hope this helps.

A: https://pypi.python.org/pypi/socketIO-client
https://github.com/socketio/socket.io-client-java
There are socket.io clients in different languages too. You just need to google it.


text:
Q: A good step by step second graduate course textbook for a mathematical statistics textbooks A good step by step math derivation based and self contained second graduate course textbook for a mathematical statistics textbooks?
Note: By saying second mathmatical statistics graduate course, i mean that it is after the first graduate level mathematical statistical course
The second book itself i've been refer to should be the same level as jun shao's mathematical statistics and it should be the focus on general mathematical statistics subjects but not too specific

A: Young and Smith's Essentials of Statistical Inference by Cambridge University Press and Davison's Statistical Models also by Cambridge University Press come into mind for a second book on Mathematical Statistics.
Davison's book has a somewhat more applied feel to it. Both books were proposed to me as the next step from DeGroot and Schervish's  Probability & Statistics.
I have never seen the book from Jun Shao so I am not sure how it compares to them. After a first course students usually begin to hone skills more on  particular areas (e.g. Asymptotics, Applied Stochastic Processes, etc.). Is there such an area that interests you? Maybe you would benefit more from an introductory book to a potential area of interest.

A: Statistical Inference by Casella et al. is often used as a primary textboook.


text:
Q: Using Regular Expression to set the length of a text field I am currently trying to use the RegularExpression attribute to stop users form entering html tags. This does work and the error message appears. I'm now trying to get this RegEx to set a limit on the amount of characters added into the text box. This is the regex:
    [RegularExpression(@"[^<>]{1,10}$*", ErrorMessage = "NOO")]
    public string Name { get; set; }

I am quite new to RegularExpressions and dont really know the layout to how it works. I expected the values within {} would've setted the min and max length but it doesn't work, whereas checking if <> has been entered still works. How do I lay out a regular expression and what is wrong with this RegEx?
I am using ASP.NET MVC 5 C#.
Thank you in advance

A: Looking at your regex [^<>]{1,10}$* the asterisk behind the $ is a bit strange, since it denotes "any number of end of lines".
When matching it against input I would interpret it as "anything that doesn't contain < or > in the last 1 to 10 characters".
If you want to limit the full length of the string you should describe everything between "start of input" and "end of input", so better add a ^ at the start of your regex:
^([^<>]){1,10}$

A: [RegularExpression(@"([^<>]{1,10}$*)[0,30]", ErrorMessage = "NOO")]
public string Name { get; set; }

The [0,30] defines the minimum and maximum number of characters that can be entered.

A: A good place to learn all about regular expressions is here: http://www.regular-expressions.info/tutorial.html
What is weird about your regular expression is that you have the * behind the $ sign. The $ sign indicates that you should have the end of the matching string there and the * is for repetition (0 or more). So checking for zero or more string ends might confuse things.
Beyond that, looking for 1 to 10 characters that are not < or > seems valid. So I think it's the * behind the $ that's throwing you off.

A: try this
 [RegularExpression(@"^.{6,10}$", ErrorMessage = "Name should be of minimum 6 and maximum 10 characters")]
public string Name { get; set; }


text:
Q: Import Error while using new xgboost-distribution I'm using the new xgboost-distribution module
I input the following into my file
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

from xgboost_distribution import XGBDistribution

if __name__ == '__main__':
    data = load_boston()
    X, y = data.data, data.target
    X_train, X_test, y_train, y_test = train_test_split(X, y)

    model = XGBDistribution(
        distribution="normal",
        n_estimators=500
    )
    model.fit(
        X_train, y_train,
        eval_set=[(X_test, y_test)],
        early_stopping_rounds=10
    )

When I run this code, however, it generates an import error within the xgboost/sklearn.py module file:
from xgboost_distribution import XGBDistribution
  File "/Users/timgundersen/opt/anaconda3/lib/python3.8/site-packages/xgboost_distribution/__init__.py", line 18, in <module>
    from xgboost_distribution.model import XGBDistribution  # noqa
  File "/Users/timgundersen/opt/anaconda3/lib/python3.8/site-packages/xgboost_distribution/model.py", line 7, in <module>
    from xgboost.sklearn import XGBModel, _wrap_evaluation_matrices, xgboost_model_doc
ImportError: cannot import name '_wrap_evaluation_matrices' from 'xgboost.sklearn' (/Users/timgundersen/opt/anaconda3/lib/python3.8/site-packages/xgboost/sklearn.py)

I tried updating sklearn, as well as xgboost and other modules that sklearn requires.
Why would this be giving me an import error if my computer is updated with all of the correct versions ?

A: Which python version do you use?
In case of python 3.8, it should work with scikit-learn 0.24.1
pip install scikit-learn==0.24.1


text:
Q: Remove space between rectangles canvas html5 I created an array of rectangles, with each having 100 wide more than the previous.
var pos = new Vector2(0, 0);

for(var i=0;i<numRects;i++) {
    rects[i] = new Rectangle(new Vector2(pos.X, 0), sizeRect, sizeRect);
    pos.X += sizeRect;
}

But the print on the screen there is a small spacing between them.
for(var i=0;i<numRects;i++) {
    Game.drawRect("blue", rects[i].pos, rects[i].width, rects[i].height);
}

Full source code: https://jsfiddle.net/gtspina/cg8t9x1w/5/
What did I do wrong?


text:
Q: Coversion string to array This is my String data
[
   'EDUCATION_LEVEL'   =>'MIDDLE_LEVEL',
   'EDUCATION_PROFESSIONAL'   =>'APPRENTICESHIP',
   'Family_Father'   =>'M.Sharif #03312887233',
   'PROFILE_IMAGE_1'   =>'"file_type" => "image",
   "file_saved_path"   => "public/images/34_php4A2A.tmp.jpg"',
   'COWORKER_REFERENCE_1'   =>'Mr. xyz work place partner #03312887233',
   'COWORKER_REFERENCE_3'   =>'Mr. Abc work place partner #03312887233',
   'BIRTH_CITY'   =>'Rahim Yar Khan',
   'BIRTHPLACE_PROVINCE'   =>'Punjab',
   'BIRTH_DISTRICT'   =>'SadiqAbad',
   'WORKING_PROVINCE'   =>'Sindh',
   'WORKING_PROVINCE_CITY'   =>'Karachi East',
   'WORKING_CITY_AREA'   =>'Gulsan-i-Iqbal',

]◀"

I tried many options which found on net
$data = (array)($chardata);
$data = (object)($chardata);

I want object or array from which i can get vakues like
$data['EDUCATION_LEVEL'];
or
$data->EDUCATION_LEVEL


text:
Q: Removing a vector element of object type using an iterator c++ I am trying to write a function that removes a vector element from listAccounts depending on the account_name of that vector element. I have written this:
void Account::remove_account(string name) {

    auto iter = listAccounts.begin();

    for ( ; iter !=  listAccounts.end(); iter++) {
        if ((*iter).account_name == name) {
            listAccounts.erase(iter);
        }
    }

}

But I am getting a Segmentation fault from the vector removal, from what I understand it means that I tried to access memory that I do not have access to, but i'm not sure how to correctly write this.

A: Once you erase the element pointed to by an iterator, that iterator becomes invalid. (for a std::vector, all other iterators after the erased element becomes invalid too). And incrementing or dereferencing an invalid iterator has undefined behavior.
You could do (assuming only one element is to be removed):
void Account::remove_account(string name) {
    auto iter = std::find_if(listAccounts.begin(), listAccounts.end(),
                 [&](const auto& s){ return s.account_name == name; });
    if(iter != listAccounts.end())
        listAccounts.erase(iter);
}

For multiple elements, that will be:
void Account::remove_account(string name) {
    for(auto iter = listAccounts.begin(); iter != listAccounts.end(); ){
        iter = std::find_if(iter, listAccounts.end(),
                    [&](const auto& s){ return s.account_name == name; });
        if(iter != listAccounts.end())
            iter = listAccounts.erase(iter);
    }
}

A: If container is modified iterator becomes invalid.
There are two good solutions:
void Account::remove_account(const string& name) {
    auto iter = listAccounts.begin();

    while iter !=  listAccounts.end()) {
        if (iter->account_name == name) {
            iter = listAccounts.erase(iter);
        } else {
            ++iter;
        }
    }
}

// or
void Account::remove_account(const string& name) {
    listAccounts.erase(
        std::remove_if(std::begin(listAccounts), std::end(listAccounts),
                       [&name](const auto& item) {
                           return item.account_name == name;
                       }),
        std::end(listAccounts));
}

A: If you are going to remove just one element then you can write
bool Account::remove_account( std::string &name )
{
    auto it = std::find_if( listAccounts.begin(),
                            listAccounts.end(),
                            [&]( const auto &item )
                            {
                                return item.account_name == name;
                            } );

    bool success = it != listAccounts.end();

    if ( success ) listAccounts.erase( it );

    return success;
}

As for your code then after this statement
listAccounts.erase(iter);

the iterator becomes invalid. So you may not increment it.


text:
Q: How do I store a Serializable List in FluentNhibernate If I have the following (cut down for brevity)
public class TempCartMap : ClassMap<TempCart>
{
   Id(x => x.Id).GeneratedBy.Identity();
   Map(x => x.Products); // < This one
}

[Serializable]
public class TempCart {

  public TempCart(){
    Products = new List<int>();
  }

  public virtual IList<int> Products { get; set; }

}

I've looked at (http://www.philliphaydon.com/2012/06/using-nhibernate-with-servicestack/) and (http://www.philliphaydon.com/2012/03/ormlite-blobbing-done-with-nhibernate-and-serialized-json/) but is there a shorter, simpler, faster way of getting NHibernate to Serialize & De-serialize a column as above.
Seems overkill to create a new IUserType class etc etc.

A: You can also store the Products-list as a separate table:
public class TempCartMap : ClassMap<TempCart>
{
    Id(x => x.Id).GeneratedBy.Identity();

    HasMany(x => x.Products)
        .Element("product_number")
        .KeyColumn("temp_cart_id")
        .Table("temp_cart_products")
    ;
}

Just to clarify the question: is there a reason why this is not wanted?


text:
Q: Why weekdays returns the week day in German? I'm on Ubuntu 18.04 and doing the following returns the day of the week in German .. why?
library(lubridate)
ts <- c(1129503178, 850121164, 848329742, 1199772925, 1114229246)
weekdays(as_datetime(ts))
[1] "Sonntag"  "Montag"   "Montag"   "Dienstag" "Samstag"

How can I change it to either English or a number for each week day?
UPDATE doing sessionInfo() yields the following result:
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.3 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=de_CH.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=de_CH.UTF-8
 [6] LC_MESSAGES=en_US.UTF-8    LC_PAPER=de_CH.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=de_CH.UTF-8 LC_IDENTIFICATION=C

A: Ah just doing the following partially solves the issue and now the days of the week show in US English:
Sys.setlocale("LC_TIME", "en_US.UTF-8")
[1] "en_US.UTF-8"

Now the OP outputs:
 > weekdays(as_datetime(ts))
 [1] "Sunday"   "Monday"   "Monday"   "Tuesday"  "Saturday"

However, I'd prefer a numeric output e.g. "Sunday" -> 1, "Monday" -> 2 etc.


text:
Q: Find the arc length using Simpsons rule I'm trying to find the arc length using Simpsons formula for this function:
$\int_{0}^{\pi}\sqrt{1+cos^2(x)}$ where $h=\frac{\pi}{6}$
I've seen online that people solve this type of examples so that they find the values of $f(x_0),f(x_1),...,f(x_n)$ and they just apply the Simpsons formula.
But what about the remainder of the formula ($R$)?
In all examples I needed to find the Simpsons error which is $R_m=\frac{b-a}{180}h^4M_4$, where $M_4=max_{x=[a,b]}|f^{iv}(x)|$ ( 4th derivative of $f(x)$)

A: To clarify, it sounds like you're trying to find the arc length of $f(x) = \sin x$ on the interval $[0,\pi]$.  This will result in needing to evaluate the integral $\displaystyle \int_0^\pi \sqrt{1 + \cos^2 x} \, dx$.
So you'll want to use Simpson's rule with $a = 0, b = \pi, h = \dfrac\pi6$, and $g(x) = \sqrt{1 + \cos^2 x}$.  (I'm using $g(x)$ since the name "$f$" is already taken in my own explanation here: $f(x) = \sin x$ above.)
Before you can use Simpson's rule, you'll need to see how many subintervals of $[0,\pi]$ you have.  In other words, you need to find $n$.  Normally we use $n$ to find $h$, but this time we're given $h$.  It's just as easy to get $n$ from $h$.  We can use the same equation:  $$h = \frac{b-a}n$$
We already know $h$, $b$, and $a$.  So we have:
$$\frac\pi6 = \frac{\pi - 0}n$$
From this it's clear that $n = 6$.  Simpson's rule with $n=6$, applied here, says this:  (Recall that $g(x) = \sqrt{1+\cos^2x}$.)
$$\int_0^\pi g(x) \, dx \approx \frac h3\left[g(x_0) + 4g(x_1) + 2g(x_2) + 4g(x_3) + 2g(x_4) + 4g(x_5) + g(x_6)\right] \tag{*}$$
In the above, $x_0 = 0$, $x_1 = x_0 + h = \dfrac\pi6$, $x_2 = x_1 + h = \dfrac\pi3$, and so on.  I'll leave it to you to find $x_3, x_4, x_5, x_6$ and to evaluate the RHS of equation (*) above.
Regarding the remainder, typically you don't need to find it unless explicitly asked for it.  The way you phrased your question it sounds like you aren't required to find it.  But perhaps there is an understanding in your class that all numerical method answers must include remainder/error terms; I don't know.  The error is, as you said, equal to $\displaystyle \frac {h^4}{180}(b-a) \max_{a \le x \le b} \left|g^{(4)}(x)\right|$.  To find this you'll need to maximize the fourth derivative of $g(x) = \sqrt{1 + \cos^2x}$ on $[0,\pi]$.  To me that sounds nontrivial (or at least extremely tedious) so I'm wondering if you really do have to do that here.


text:
Q: How does one find this matrix $A$? I just took an exam and theres a question that's driving me crazy because I can't seem to figure it out. It said that I was to find a matrix $A$ such that $A\vec x=\vec 0$ and it has the solution $\vec x=\left[\begin{matrix}1\\2\\-3\end{matrix}\right]$ and $A$ isn't all $0$'s. I'm completely stumped and I know I will find out how to do it eventually but it's bugging me. I really want to know. All I could really figure out was that this is what I wanted as my end product of the matrix after it gets row reduced: $$\left[\begin{matrix}1&0&0&1\\ 0&1&0&2\\ 0&0&1&-3\end{matrix}\right]$$ Where the last row is the augmented column.

A: your $x \in null(A)$
one choice of  $A$:
$$A = \begin{pmatrix} 1&1&1\\ 1&1&1\\ 1&1&1 \end{pmatrix}$$

A: You want to choose $A$ so that all its rows are orthogonal to $\vec{x}$. Assuming $A$ is $3\times 3$, then for each row, you can arbitrarily choose the first two elements and then compute the third so that that row is orthogonal to $\vec{x}$. For example, let
$$
A = \left[\begin{array}{ccc}1 & 2 & ? \\ 0 & 1 & ? \\ 1 & 0 & ? \end{array}\right].
$$
Consider each row of $A$ in turn and compute the ? so that the row is orthogonal to $\vec{x}$. In this case, we have
$$
A = \left[\begin{array}{ccc}1 & 2 & 5/3 \\ 0 & 1 & 2/3 \\ 1 & 0 & 1/3 \end{array}\right].
$$


text:
Q: Python-Django Response the text of error How can I response the text of validation error to my template with Ajax?
def create_user(request):
    if request.method == 'POST':
        is_super = True
        if request.POST.get('is_super') in 'false':
            is_super = False
        if request.POST.get('password') == request.POST.get('confirm'):
            user = User.objects.create(first_name=request.POST.get('first_name'),
                                       last_name=request.POST.get('second_name'),
                                       username=request.POST.get('username'),
                                       is_superuser=is_super,
                                       date_joined=datetime.now())
            user.set_password(request.POST.get('password'))
            user.save()
        else:
            raise forms.ValidationError("Passwords doesn't match")
        return HttpResponse('')

A: def create_user(request):
    if request.method == 'POST':
        is_super = True
        if request.POST.get('is_super') in 'false':
            is_super = False
        if request.POST.get('password') == request.POST.get('confirm'):
            user = User.objects.create(first_name=request.POST.get('first_name'),
                                       last_name=request.POST.get('second_name'),
                                       username=request.POST.get('username'),
                                       is_superuser=is_super,
                                       date_joined=datetime.now())
            user.set_password(request.POST.get('password'))
            user.save()

        else:
            return HttpResponse(json.dumps({'error': True, 'message': 'Password and confirm password doesnt match'}))`
        return HttpResponse('')

You need to show the above error message "Password and confirm password doesn't match" in HTML using Jquery.