Q:

Android Calendar like Expedia

I'm on building application,
What am trying to do is building calendar like expedia app.
Here's the screenshot:

Do you guys any idea what component should i use from base and what event should i use when select several box on that.

A:

You can either chose to use the 4.0 calendarView backported to 2.1 (project here), or implement yourself your own calendarView extending a ViewGroup. This is not as hard as you can think :)


Q:

Install phpmyadmin without selection apache2 or lighttpd

I use command Ubuntu: sudo apt-get install phpmyadmin
In process installing I inform about selection type of server: apache2 and lighttpd.
My server is build only on Nginx + php_fpm.
How i can install phpmyadmin without selection apache2 or lighttpd?
Sorry for stupid question

A:

First install php5-fpm and then install phpmyadmin.
sudo apt-get install php5-fpm
sudo apt-get install phpmyadmin

The software, phpMyAdmin, requires a Web server and PHP. If PHP and a Web server have not yet been installed, then the default action is to use Apache. The package, php5-fpm, satisfies the requirements; thus, installing phpmyadmin after php5-fpm results in only the following additional package dependencies.
dbconfig-common javascript-common libjs-codemirror libjs-jquery
libjs-jquery-cookie libjs-jquery-event-drag libjs-jquery-metadata
libjs-jquery-mousewheel libjs-jquery-tablesorter libjs-jquery-ui
libjs-underscore libmcrypt4 php-gettext php5 php5-gd php5-mcrypt php5-mysql

Although PHP-FPM is not a Web server, the package maintainer understood that if php5-fpm has been installed, then the Ubuntu server will utilize some other Web server that uses the FastCGI Process Manager (FPM), and there is no need to know which Web server.


Q:

"Looking for a job" panel placement delay causing click problems

I have an issue with the "Looking for a job" panel that appears on SO pages.
At least in my browser (Chrome on Windows) and via my work's crappy internet connection, there is a slight delay before this panel appears and pushes other content down. This means that sometimes I inadvertently click on the "Looking for a job" panel when I meant to click on something else.
Here's an example of what I see when the page loads:

and what I see after a short delay:

See how the panel has pushed the "Frequented Tags" section down. So the page loads, I go to click on the "c#" tag, and just at that moment the jobs panel appears and I get taken to that page instead.
If there anything that can be done about this?

A:

The "Frequented Tags" section should be shown above the ad.  When the ad loads it will push down the "Hot Network Questions" but the display placement of the Frequented Tags should remain in place.  Let me know if you have further issues.

A:

Sorry, I didn't notice this post, but someone posted the same issue a few days ago.
We've moved the favorite tags section above the ads on the /questions page as well now. Hopefully that solves the annoyance for most people.


Q:

Categorizing a data based on string in each row

I have the following dataframe:
 raw_data = {'name': ['Willard', 'Nan', 'Omar', 'Spencer'],
'Last_Name': ['Smith', 'Nan', 'Sheng', 'Poursafar'],
'favorite_color': ['blue', 'red', 'Nan', "green"],
'Statues': ['Match', 'Mis-Match', 'Match', 'Mis_match']}
df = pd.DataFrame(raw_data, columns = ['name', 'age', 'favorite_color', 'grade'])
df

I wanna do the following tasks:

Separate the rows that contain Match and Mis-match
Make a category that only contains people whose first name and last name are Nan and love a color(any color except for nan).

Can you guys help me?

A:

Use boolean indexing:
df1 = df[df['Statues'] == 'Match']
df2 = df[df['Statues'] =='Mis-Match']

If missing values are not strings use Series.isna and
Series.notna:
df3 = df[df['Name'].isna() & df['Last_NameName'].isna() & df['favorite_color'].notna()]

If Nans are strings compare by Nan:
df3 = df[(df['Name'] == 'Nan') &
         (df['Last_NameName'] == 'Nan') &
         (df['favorite_color'] != 'Nan')]


Q:

Java Generics Cast Error

corresponding to the title, my problem is to get the array-length of an generic array, which is inside an instance of an class, which has been initialized with this generic type.
When i want to get the length of my array (ak.array.length), java throws this error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
    at Testclass.main(Testclass.java:15)
So where is my fault in this code?
Thanks in advance
public class Testclass {

    static class ArrayKeeper<T> {
        protected T[] array;

        public ArrayKeeper() {
            array = (T[])new Object[5];
        }
    }

    public static void main(String[] args) {
        //create a new instance of inner class ArrayKepper (type String)
        Testclass.ArrayKeeper<String> ak = new Testclass.ArrayKeeper<String>();
        System.out.println(ak.array.length); //cast error here.
    }
}

A:

The problem is in this line:
array = (T[]) new Object[5];

That's not the way to create a generic array, you're creating an Object[] and not a String[] as you intended. You can not create an Object[] and then cast it to any type you want, you have to create an array of the correct class. Try this instead:
public ArrayKeeper(Class<T> clazz, int size) {
    array = (T[]) Array.newInstance(clazz, size);
}

And then, when you need to instantiate an ArrayKeeper do this:
Testclass.ArrayKeeper<String> ak =
    new Testclass.ArrayKeeper<String>(String.class, 5);


Q:

Not able to access sqlite database Android

Ive created an app that stores user login information into an sqlite database. However when i try to access it using Root Explorer i get an error.
An error occurred while opening the database. disk i/o error (code 3850):, while compiling: Select * from sqlite_master where type in('table','view') order by name.
The app works fine, and it is storing the log in information as required. However i cant access it on the root explorer?
Any suggestions?

A:

please call this function:
public static void copyDataBase(Context mActivity) throws IOException {
        InputStream myInput = new FileInputStream(new File("/data/data/"
                + mActivity.getPackageName() + "/databases/" + "yourdb.sqlite"));
        File files = new File("/sdcard/files/");
        files.mkdirs();
        String outFileName = "/sdcard/files/your.sqlite";
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int bufferLength;
        while ((bufferLength = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, bufferLength);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

your database is copied  /sdcard/files/your.sqlite this path.


Q:

java : Tracing out the Error line in my case

I am working on a existing Java EE based application .
Somehow the functionality is not working written by them .
When i found out the logs in Linux server i found out this Exception there
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at com.cyber.EasyOptions.view(EasyOptions.java:2054)

What does this mean exactly ??

I guess there is a class named EasyOptions and in that there is a method view and inside it  there is this Exception occuring   ??

This particular class  EasyOptions  is present inside a jar file in our code .
I am using JD-GUI decompiler and when navigated to this particualr jar  ,   and saw  this class EasyOptions , inside view method there is no such line (2054)
    so dont know we can match the line numbers this way or not  ??
I guess we cant match line numbers this way , my questions how can we trace out the exact line of error ??

A:

guess there is a class named EasyOptions and in that there is a method view and inside it there is this Exception occuring ??

That's correct.

I am using JD-GUI decompiler and when navigated to this particualr jar , and saw this class EasyOptions , inside view method there is no such line (2054)

The line number only makes sense in the context of the original source code. The decompiled code isn't identical to the original and will have different line numbering.

how can we trace out the exact line of error

Without the original source code it's going to be tricky. One way to narrow down the possibilities is to look through the decompiled code for EasyOptions.view(), looking for places where an array is being accessed.


Q:

Upload image from android camera to web server

package com.camerafileupload;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    // LogCat tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Camera activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Uri fileUri; // file url to store image/video

    private Button btnCapturePicture, btnRecordVideo;

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

        // Changing action bar background color
        // These two lines are not needed
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

        /**
         * Capture image button click event
         */
        btnCapturePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // capture picture
                captureImage();
            }
        });

        /**
         * Record video button click event
         */
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                recordVideo();
            }
        });

        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
    }

    /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * Launching camera app to capture image
     */
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    /**
     * Launching camera app to record video
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

        // set video quality
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                                                            // name

        // start the video capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // successfully captured the image
                // launching upload activity
                launchUploadActivity(true);

            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }

        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // video successfully recorded
                // launching upload activity
                launchUploadActivity(false);

            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    private void launchUploadActivity(boolean isImage){
        Intent i = new Intent(MainActivity.this, UploadActivity.class);
        i.putExtra("filePath", fileUri.getPath());
        i.putExtra("isImage", isImage);
        startActivity(i);
    }

    /**
     * ------------ Helper Methods ----------------------
     * */

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Config.IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + Config.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}

I get this code from android hive, I didn't know where the code to upload the image to server. I already build this code into .apk it working when taking photo and video to local storage but not to server.
and this is uploadactivity
     package com.camerafileupload;

    import com.camerafileupload.AndroidMultiPartEntity.ProgressListener;

    import java.io.File;
    import java.io.IOException;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.VideoView;

    public class UploadActivity extends Activity {
        // LogCat tag
        private static final String TAG = MainActivity.class.getSimpleName();

        private ProgressBar progressBar;
        private String filePath = null;
        private TextView txtPercentage;
        private ImageView imgPreview;
        private VideoView vidPreview;
        private Button btnUpload;
        long totalSize = 0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_upload);
            txtPercentage = (TextView) findViewById(R.id.txtPercentage);
            btnUpload = (Button) findViewById(R.id.btnUpload);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            imgPreview = (ImageView) findViewById(R.id.imgPreview);
            vidPreview = (VideoView) findViewById(R.id.videoPreview);

            // Changing action bar background color
            getActionBar().setBackgroundDrawable(
                    new ColorDrawable(Color.parseColor(getResources().getString(
                            R.color.action_bar))));

            // Receiving the data from previous activity
            Intent i = getIntent();

            // image or video path that is captured in previous activity
            filePath = i.getStringExtra("filePath");

            // boolean flag to identify the media type, image or video
            boolean isImage = i.getBooleanExtra("isImage", true);

            if (filePath != null) {
                // Displaying the image or video on the screen
                previewMedia(isImage);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
            }

            btnUpload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // uploading the file to server
                    new UploadFileToServer().execute();
                }
            });

        }

        /**
         * Displaying captured image/video on the screen
         * */

        private void previewMedia(boolean isImage) {
            // Checking whether captured media is image or video
            if (isImage) {
                imgPreview.setVisibility(View.VISIBLE);
                vidPreview.setVisibility(View.GONE);
                // bimatp factory
                BitmapFactory.Options options = new BitmapFactory.Options();

                // down sizing image as it throws OutOfMemory Exception for larger
                // images
                options.inSampleSize = 8;

                final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

                imgPreview.setImageBitmap(bitmap);
            } else {
                imgPreview.setVisibility(View.GONE);
                vidPreview.setVisibility(View.VISIBLE);
                vidPreview.setVideoPath(filePath);
                // start playing
                vidPreview.start();
            }
        }

        /**
         * Uploading the file to server
         * */

        private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
            @Override
            protected void onPreExecute() {
                // setting progress bar to zero
                progressBar.setProgress(0);
                super.onPreExecute();
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                // Making progress bar visible
                progressBar.setVisibility(View.VISIBLE);

                // updating progress bar value
                progressBar.setProgress(progress[0]);

                // updating percentage value
                txtPercentage.setText(String.valueOf(progress[0]) + "%");
            }

            @Override
            protected String doInBackground(Void... params) {
                return uploadFile();
            }

            @SuppressWarnings("deprecation")
            private String uploadFile() {
                String responseString = null;

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

                try {
                    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                            new ProgressListener() {

                                @Override
                                public void transferred(long num) {
                                    publishProgress((int) ((num / (float) totalSize) * 100));
                                }
                            });

                    File sourceFile = new File(filePath);

                    // Adding file data to http body
                    entity.addPart("image", new FileBody(sourceFile));

                    // Extra parameters if you want to pass to server
                    entity.addPart("website",
                            new StringBody("www.fintech-dev.com/cpeco"));
                    entity.addPart("email", new StringBody("i117dr4@gmail.com"));

                    totalSize = entity.getContentLength();
                    httppost.setEntity(entity);

                    // Making server call
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();

                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(r_entity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }

                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
                }

                return responseString;

            }

            @Override
            protected void onPostExecute(String result) {
                Log.e(TAG, "Response from server: " + result);

                // showing the server response in an alert dialog
                showAlert(result);

                super.onPostExecute(result);
            }

        }

        /**
         * Method to show alert dialog
         * */

        private void showAlert(String message) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(message).setTitle("Response from Servers")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // do nothing
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }

    }

and this is androidmultipartentity

package com.camerafileupload;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

@SuppressWarnings("deprecation")
public class AndroidMultiPartEntity extends MultipartEntity

{

    private final ProgressListener listener;

    public AndroidMultiPartEntity(final ProgressListener listener) {
        super();
        this.listener = listener;
    }

    public AndroidMultiPartEntity(final HttpMultipartMode mode,
            final ProgressListener listener) {
        super(mode);
        this.listener = listener;
    }

    public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
            final Charset charset, final ProgressListener listener) {
        super(mode, boundary, charset);
        this.listener = listener;
    }

    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        super.writeTo(new CountingOutputStream(outstream, this.listener));
    }

    public static interface ProgressListener {
        void transferred(long num);
    }

    public static class CountingOutputStream extends FilterOutputStream {

        private final ProgressListener listener;
        private long transferred;

        public CountingOutputStream(final OutputStream out,
                final ProgressListener listener) {
            super(out);
            this.listener = listener;
            this.transferred = 0;
        }

        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.transferred(this.transferred);
        }

        public void write(int b) throws IOException {
            out.write(b);
            this.transferred++;
            this.listener.transferred(this.transferred);
        }
    }
}

This is config
package com.camerafileupload;

public class Config {
     public static final String FILE_UPLOAD_URL = "url.com/android_upload/file_upload.php";

        // Directory name to store captured images and videos
        public static final String IMAGE_DIRECTORY_NAME = "android_upload";

A:

DataHolder.FILE_UPLOAD_URL containing the url to upload.
onclick write
new UploadFileToServer().execute();

private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
            @Override
            protected void onPreExecute() {
                // setting progress bar to zero
                pDialog.setProgress(0);
                super.onPreExecute();
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                // Making progress bar visible

                // updating progress bar value
                pDialog.setProgress(progress[0]);

                // updating percentage value
            //  txtPercentage.setText(String.valueOf(progress[0]) + "%");
            }

            @Override
            protected String doInBackground(Void... params) {
                return uploadFile();
            }

            @SuppressWarnings("deprecation")
            private String uploadFile() {

                String responseString = null;

                    HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(DataHolder.FILE_UPLOAD_URL);

                try {
                    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                            new ProgressListener() {

                                @Override
                                public void transferred(long num) {
                                    publishProgress((int) ((num / (float) totalSize) * 100));
                                }
                            });

                    File sourceFile = new File(filePath);

                    // Adding file data to http body
                    entity.addPart("image", new FileBody(sourceFile));

                    // Extra parameters if you want to pass to server

                    entity.addPart("username", new StringBody("xyz"));

                    totalSize = entity.getContentLength();
                    httppost.setEntity(entity);

                    // Making server call
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();

                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(r_entity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }

                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
                }

                return responseString;

            }

            @Override
            protected void onPostExecute(String result) {
                Log.e(TAG, "Response from server: " + result);

                // showing the server response in an alert dialog
                showAlert(result);

                super.onPostExecute(result);
            }

        }

        /**
         * Method to show alert dialog
         * */
        private void showAlert(String message) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(message).setTitle("Response from Servers")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // do nothing
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }


Q:

Split with regex is not splitting every match

I need to split a string on every match of #ABC3#, #ABC3_3#, or #ABC3_33# tags, so then I built the following regex:
/#([A-Z][A-Z][A-Z])([0-9])#|#([A-Z][A-Z][A-Z])([0-9])_([0-9])#|#([A-Z][A-Z][A-Z])([0-9])_([0-9][0-9])#/

And I want to split the following string:
1234 5647 8512 5648#EMB2#12#EMB3#DEC 12#EMB4#33/03#EMB7_12#02/12#EMB7_13#1999#EMB5#22/19#EMB6#DEC 22#EMB7_1#DEC 22#EMB7_2#14#EMB7_3#11/22#EMB7_14#11/22#EMB7_15#2013#EMB7_4#ASDCFG ASDFWED ODLSKEMT   #EMB7_5#423253 AB ASDCFGER ASDFGH#EMB7_6#4444#EMB7_8#222#EMB7_9##EMB7_16#

The problem is that the following code is not splitting every match of the string.
String[] embTagsToArray = embossingTags.split("/#([A-Z][A-Z][A-Z])([0-9])#|#([A-Z][A-Z][A-Z])([0-9])_([0-9])#|#([A-Z][A-Z][A-Z])([0-9])_([0-9][0-9])#/");

The final array was supposed to have 18 positions but it is being splitted in 9 array positions, like this:
[0] 1234 5647 8512 5648#EMB2#12#EMB3#DEC 12#EMB4#33/03#EMB7_12#02/12#EMB7_13#1999#EMB5#22/19#EMB6#DEC 22
[1] DEC 22
[2] 14
[3] 11/22#EMB7_14#11/22#EMB7_15#2013
[4] ASDCFG ASDFWED ODLSKEMT
[5] 423253 AB ASDCFGER ASDFGH
[6] 4444
[7] 222
[8] #EMB7_16#

Expected Output:
[0] 1234 5647 8512 5648
[1] 12
[2] DEC 12
[3] 33/03
[4] 02/12
[5] 1999
[6] 22/19
[7] DEC 22
[8] DEC 22
[9] 14
[10] 11/22
[11] 11/22
[12] 2013
[13] ASDCFG ASDFWED ODLSKEMT
[14] 423253 AB ASDCFGER ASDFGH
[15] 4444
[16] 222
[17]

I can't find what I'm doing wrong. Anyone?

A:

Just split your input string according to the below regex which uses a non-capturing group.
String s = "1234 5647 8512 5648#EMB2#12#EMB3#DEC 12#EMB4#33/03#EMB7_12#02/12#EMB7_13#1999#EMB5#22/19#EMB6#DEC 22#EMB7_1#DEC 22#EMB7_2#14#EMB7_3#11/22#EMB7_14#11/22#EMB7_15#2013#EMB7_4#ASDCFG ASDFWED ODLSKEMT   #EMB7_5#423253 AB ASDCFGER ASDFGH#EMB7_6#4444#EMB7_8#222#EMB7_9##EMB7_16#";
String[] tok = s.split("#[A-Z]{3}\\d(?:_\\d{1,2})?#");
System.out.println(Arrays.toString(tok));

Output:
[1234 5647 8512 5648, 12, DEC 12, 33/03, 02/12, 1999, 22/19, DEC 22, DEC 22, 14, 11/22, 11/22, 2013, ASDCFG ASDFWED ODLSKEMT   , 423253 AB ASDCFGER ASDFGH, 4444, 222]

DEMO
Regular Expression:
#                        '#'
[A-Z]{3}                 any character of: 'A' to 'Z' (3 times)
\d                       digits (0-9)
(?:                      group, but do not capture (optional):
  _                        '_'
  \d{1,2}                  digits (0-9) (between 1 and 2 times)
)?                       end of grouping
#                        '#'


Q:

When do I need to call watchers.dispatch() in Dart?

I have a small application I am building that is very similar to the example here.
I am using Dart SDK version 0.5.9.0_r22879
The main difference is that I update the results via an AJAX request, and I only make this request when Enter is pressed in my input control.
In my code, the results list does not render unless I explicitly call watchers.dispatch(), as discussed in the 2nd example here.
Why? It is not clear when I would have to explicitly call watchers.dispatch(), and when it would happen automatically, as in the template example.
My HTML:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>My App</title>
    <link rel="stylesheet" href="myapp.css">

My App

      <input type="text" name="search-box" id="search-box" placeholder="Search" bind-value="searchText" />

      <template instantiate="if noMatches">No matches</template>
      <template instantiate="if !noMatches">{{results.length}} entries:</template>

          <template iterate='entry in results'>

{{entry.message}}

          </template>

The important parts of myapp.dart:
import 'dart:html';
import 'dart:json' as JSON;
import 'dart:uri' as uri;
import 'package:web_ui/web_ui.dart';
import 'package:web_ui/watcher.dart' as watchers;

String searchText = '';
List<LogEntry> results = [];

bool get noMatches => results.isEmpty;

void main() {
  query("#search-box").onKeyPress.listen((e) => handleKeyPress(e));
}

void handleKeyPress(KeyboardEvent e) {
  if (!e.ctrlKey && e.keyCode == KeyCode.ENTER) {
    doSearch();
  }
}

void doSearch() {
  if (searchText != '') {
    makeRequest();
  }
}

void makeRequest() {
  HttpRequest.getString( 'http://url.to/rest-api?q=$searchText' )
    .then(processString)
    .catchError(handleError)
    ;
}

processString(String jsonString) {
  List<Map> logs = JSON.parse(jsonString);

  results.clear();
  results.addAll( logs.map((l) => new AppEntry.fromJson(l)) );
  watchers.dispatch();
}

handleError(Error error) {
  print('Request failed');
  print(error);
}

class AppEntry {
  final String message;
  AppEntry.fromJson(Map json) : message = json['message'];
}

A:

You need to call watchers.dispatch() explicitly whenever you need to change the model in a way which is not triggered by events fired by the templates. This means AJAX calls like in your example, timers, etc.
Events installed by templates take care of calling dispatch() for you, so you don't have to do it in that case.
You can find more about this here.
However, at the moment, watchers.dispatch is treated as 'old way', as one of the goals in Web-UI is to make binding more declarative with observables. So the future-proof solution would be to use @observable annotation on your model. This will ensure that observers are updated every time the model changes, without needing you to explicitly update them.


Q:

Download image from Imagelibrary

I have an event receiver that should download images from an imagelibrary, and do some stuff with that copy. There will be several images with the same customid that i want to grab, so I loop over all images and select images with correct id.
How can manage to get the specific item, but how do I grab the file in that item and pass it off as for example a bitmap?
So far I've got this:
//tempid is the value Im looking for in the library
tempid = 1000;
SPListItemCollection Images = pictureLib.Items;
for(int i = 0;i<pictureLib.ItemCount;i++)
{
    //get a specific lookupid,the one im im looking for.
    SPFielLookupValue value = new SPFieldLookupValue(itemid,ObjectId);
    int id = Convert.ToInt32(value);
    if(tempid == id)
    {
        //Here is where i want the bitmap.
        System.Drawing.Bitmap img = Images[i].File;
        ...
     }
 }

So within the "if" I want to get a bitmap from the SPListItemCollection, but how do i get that, is it possible? Is there a method on SPListItemCollection I can use, either "File" or "Attachment", or do I have to convert the file to bitmap first?
Much appreciated any help or ideas here. I'm stumped.

A:

You can use a MemoryStream to create an Image object from the file:
var imageFile = Images[i].File;
var imageStream = imageFile.OpenBinaryStream();
Image image = Image.FromStream(imageStream, true, true);
imageStream.Dispose();

Depending on what you need to do, this can be done from the Image, like resizing
if (originalImage.Width > MAX_WIDTH)// || originalImage.Height > MAX_HEIGHT)
                {
                    var ratioX = (double)MAX_WIDTH / originalImage.Width;
                    //var ratioY = (double)MAX_HEIGHT / originalImage.Height;
                    var ratio = ratioX;// Math.Min(ratioX, ratioY);

                    var newWidth = (int)(originalImage.Width * ratio);
                    var newHeight = (int)(originalImage.Height * ratio);

                    var newImage = new Bitmap(newWidth, newHeight);
                    Graphics.FromImage(newImage).DrawImage(originalImage, 0, 0, newWidth, newHeight);
                    byte[] smallImage = ImageToByteArray(newImage, originalImage.RawFormat);
                }


Q:

How to avoid self-intersection when applying stroke to a curve?

I have several Spline2D objects in my code, each of which has a Position, Velocity, and Acceleration method that returns a vector of the specified quantity at a particular time. I've been using these vectors in order to construct geometry to create gradient strokes for the curves, but I'm having problems with self-intersections at steep curves. As an example, here's one curve where I'm having this occur:
Wireframe: http://twitpic.com/2zplw1/full
Filled: http://twitpic.com/2zpmnt/full
As you can see, on the second bend, the inner portion intersects itself, which causes that ugly artifact. Is there a good algorithm/method to stroke curves without causing that self-intersection?
EDIT: More extreme examples, plus a mock-up of what I'd like to achieve:
Wireframe: http://twitpic.com/2ztwzi/full
Filled: http://twitpic.com/2ztwkt/full
Ideal Outcome (Mock-Up): http://twitpic.com/2ztxa8/full

A:

If you're rendering these with the GPU and any modern 3D api (eg. OpenGL/D3D), it looks to me like you can get rid of this with depth testing. If you assign your outside verts to be z=FAR , and your inside verts to be z=NEAR, the depth testing should prevent the overlap from showing. With OpenGL:

  // don't forget to clear depth buffer to 1.0f at beginning of frame.
  glClearDepth(1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  // enable depth testing.
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
// draw the Spline2D
  for each segment in spline
    for each vert in segment
      if (vert is an outer vert), set vert.z = 1.0, otherwise set vert.z=0.0

Caveat emptor: this won't work if you need translucent strokes.


Q:

listviews dont update subitem (VB.net)

I have a listview in VB.net in which i have two columns (Itemname, Coordinates). the Itemname column is populated with predifined names for each rows (total rows=5) and the coordinates column will be filled with the mouse position coordinates when the user select a row and click anywhere on the screen.
Itemname|Coordinates:
    Item1  (x,y)
    Item2  (x,y)
    Item3  (x,y)
.......
my code works only when i select a row and click anywhere for the first time, but when i select the same row and click again to change the coordinate, it doesn't update to the new coordinates.
here's my code for Item1:
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListView1.SelectedIndexChanged

If ListView1.Items(0).Selected = True Then

Dim mp As Point = MousePosition

Dim lvitem As ListViewItem

ListView1.BeginUpdate()

lvitem = Me.ListView1.Items.Item(0)
lvitem.SubItems.Add(mp.ToString)

ListView1.Update()
ListView1.EndUpdate()

End If

End Sub

the results:
first time selected item1:
    Item1  {X=801,Y=432}
second time selected item1:
    Item1  {X=801,Y=432} ===>doesn't update to second click {X=743,Y=231}
how can i fix this

A:

This is because event you're using.
Handles ListView1.SelectedIndexChanged

This will invoke sub only when selected item in ListView will be changed. On 2nd click you do not change selected index, it stays the same, that's why it does not update.
Changed event to Click or MouseClick:
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListView1.Click


Q:

Colors loops in SCSS

I want to do an array of colours in SCSS
$my-colors: ("green", #008000),("blue",#0000ff), ("orange",#fca644);

And with this array, I would like to colour each column. Imagining that the columns could have the minimum of 4 and the maximum of 10, so the colours defined in the array should repeat.

I thought we have a really good way to do this on SCSS.

A:

You can try the following solution:
$my-colors: ("green", #008000, "blue", #0000ff, "orange", #fca644);

@for $colIndex from 1 through length($my-colors) {
  table td:nth-child(#{length($my-colors)}n + #{$colIndex}) {
    color: unquote(nth($my-colors, $colIndex));
  }
}

By using this solution you only need to change the array of the colors ($my-colors) to change the order and amount of different colored columns.
The result of the above code (CSS output / demo on JSFiddle):

table td:nth-child(6n + 1) {
  color: green;
}
table td:nth-child(6n + 2) {
  color: #008000;
}
table td:nth-child(6n + 3) {
  color: blue;
}
table td:nth-child(6n + 4) {
  color: #0000ff;
}
table td:nth-child(6n + 5) {
  color: orange;
}
table td:nth-child(6n + 6) {
  color: #fca644;
}

    Column 1
    Column 2
    Column 3
    Column 4
    Column 5
    Column 6
    Column 7
    Column 8
    Column 9
    Column 10
    Column 11
    Column 12
    Column 13


Q:

Javascript: How to store a variable in a null variable in a constructor

In the startGame()method, I am trying to store the selected phrase from the getRandomPhrase() method to the null property. It keeps throwing me an error saying

Game.activePhrase is null

What am I doing wrong?
Game.js:
class Game {

  constructor() {
    this.missed = 0;
    //directly put the phrases in the constructor
    this.phrases = [new Phrase("hello world"),
      new Phrase("Wolf on wall street"),
      new Phrase("Despite making"),
      new Phrase("Karen took the kids"),
      new Phrase("alright about to head out")
    ];
    this.activePhrase = null;
  }

  getRandomPhrase() {
    //returns 5 of the random phrases
    return this.phrases[Math.floor(Math.random() * this.phrases.length)];
  }

  startGame() {
    let hid = document.getElementById('overlay');
    hid.style.display = "none";
    let phrs = this.getRandomPhrase();
    phrs.addPhraseToDisplay();
    return this.activePhrase(phrs); //trying to store it by doing this
  }
}

App.js
const game = new Game();
game.startGame();
console.log(`Active Phrase - phrase: ${game.activePhrase.phrase}`);

A:

Assign value to activePhase variable before returning it from startGame method
this.activePhrase = phrs;

Like
  startGame() {
    let hid = document.getElementById('overlay');
    hid.style.display = "none";
    let phrs = this.getRandomPhrase();
    phrs.addPhraseToDisplay();
    this.activePhrase = phrs; //Key to fix your issue
    return this.activePhrase;
  }


Q:

Invertible matrix implies square matrix

Given an $m\times n$ matrix $A$ and an $n\times m$ matrix $B$ such that $AB=I_m$ and $BA=I_n$, I would like to show that, in fact, $m=n$.
(The $m$ and $n$ may be the other way around. They should be such that $A$ and $B$ are inverses, as per the title of the question)
I know this can be done easily by seeing $A$ and $B$ as linear transformations between vector spaces, but I am wondering if anyone is aware of a proof that only involves matrix algebra. That is, a proof that would work even if the entries of $A$ and $B$ were merely from a unital ring rather than a field (although I am not even sure that the statement would be true in that case, but I haven't been able to find a counterexample).

A:

Here is another way: if $A$ and $B$ are any two matrices that can be multiplied from both sides then $tr(AB)=tr(BA)$. You can easily prove it using the definition of matrix multiplication. Hence if $AB=I_m$ and $BA=I_n$ then $m=tr(I_m)=tr(AB)=tr(BA)=tr(I_n)=n$.


Q:

Using Docker-compose, how to access the container database via the same port in container and in host

I'm running a docker-compose container for postgresql.  The postgresql database in the container is running on the standard port 5432, and I am publishing that port out to port 5444 on the host (since the host's postgresql default port is in use).
I am using the same configuration on the host and in the container (a .env file that provides config settings for cli commands and the app as a whole).  Unfortunately, whichever port I choose, one system will lose access.  For example, I cannot run:
[k@host]$ pgsql -p 5444 # Connects

in the host and still have work inside the container:
[k@db-container]$ pgsql -p 5444 # Errors in container

The container's postgresql-server is running on 5432:
[k@db-container]$ pgsql -p 5432 # Connects successfully in container

and the ports are published via the docker-compose.yml via:
- ports:
  - "5444:5432"
So currently I don't know how to configure the same port everywhere simply via the docker-compose.yml! expose command exposes the port but does not allow remapping, ports forwards host<-->container, but does not remap the internal port. I have thought of remapping the postgresql default port inside the postgresql container configuration, but fully reconfiguring postgresql seems non-trivial to do via docker-compose on every docker-compose up.
How can I remap the ports inside the container so that I can use port 5444 everywhere, in the host & container?

A:

The standard PostgreSQL client library supports several environment variables that tell it where the server is.  In the same way that you can configure the host using $PGHOST, you can configure the port using $PGPORT.
In a Docker Compose context, it should be straightforward to set these:
version: '3'
services:
  postgres:
    image: postgres:11
    ports: ['5444:5432']
    volumes: ['./postgres:/var/lib/postgresql/data']
  myapp:
    build: .
    ports: ['8888:8888']
    env:
      PGHOST: postgres
      # default PGPORT=5432 will work fine

Similarly, if you're running the application in a development environment on the host, you can set
PGHOST=localhost PGPORT=5444 ./myapp


Q:

are blue ray disks the cheapest storage medium per Gb?

The question is as simple as that really. Are bluray disks the cheapest storage medium per gb?
I am recording video which is using about 32gb per day.  So a month of that would be almost 1Tb. A year around 12tb.
I want to store at last a years worth with the possibility of more if needed.  To me it seems that cheap bluray disks world be the  cheapest solution.
But I wanted to get this confirmed.

A:

Something to keep in mind:
A quick check of media prices shows BD-R disks for around $1 each--4 cents per GB.
Hard drives are easier to get a good measure of the price as pricewatch tracks them--2tb for $90.  That's 4.5 cents per GB.
The drives are reusable, the disks are not.  In either case you need some sort of redundancy anyway.


Q:

How to find a color in a string that contains part of another color

I am trying to find a color in a string that contains part of another color.
i.e. Some string will contain Rose Gold and others will contain just Gold or
sometimes the string will contain Black and other times Jet Black or Midnight Black.
and when I use the CONTAINS keyword it works randomly.
Galaxy S8 64GB artic Silver                      Just get Silver
Galaxy S7 edge in Black Onyx 32GB (CPO)          Just get Black
Galaxy S7 edge in Silver Titanium 32GB (CPO)     Just gets Silver
Galaxy S7 edge in Blue Coral 32GB                Just gets Blue
Moto Z2 Play - Fine Gold                         Just gets Gold
iPad Mini 4 32GB in Space Gray                   I got Space Gray oddly enough
iPad Pro (9.7) 32GB in Rose Gold                 I got Rose Gold oddly enough
Galaxy Note 8 in Midnight Black                  I got Midnight Black oddly enough

 sProductDescription = Row["ProductDescription"].ToString().Trim().Replace("  ", " ");
 Products pa = db.Products.Single(p => p.ModelNumber == sModelNumber);
 foreach (string x in SharedFunctions.GetColors())
 {
   if (sProductDescription.ToUpper().Contains(x.ToUpper()))
   {
       pa.Color = x;
   }
 }

public static List<string> GetColors()
{
    List<string> lColors = new List<string>();
    lColors.Add("Artic Silver");
    lColors.Add("Black Leather");
    lColors.Add("Black Onyx");
    lColors.Add("Black Sapphire");
    lColors.Add("Black Slate");
    lColors.Add("Black");
    lColors.Add("Blue Coral");
    lColors.Add("Blue");
    lColors.Add("Carbon");
    lColors.Add("Fine Gold");
    lColors.Add("Gold Platinum");
    lColors.Add("Gold");
    lColors.Add("Gray");
    lColors.Add("Green");
    lColors.Add("Grey");
    lColors.Add("Jet Black");
    lColors.Add("Lunar Grey");
    lColors.Add("Midnight Black");
    lColors.Add("Orchid Gray");
    lColors.Add("Pearl");
    lColors.Add("Pink");
    lColors.Add("Platinum");
    lColors.Add("Rose Gold");
    lColors.Add("Silver Titanium");
    lColors.Add("Silver");
    lColors.Add("Slate");
    lColors.Add("Space Gray");
    lColors.Add("Sugar White");
    lColors.Add("Titan");
    lColors.Add("White");
    lColors.Add("Yellow");

    return lColors;
}

A:

I'd make 2 word lists containing the colours; A basic and advanced list. Your first should contain words such as "Rose Gold" and "Titanium White" for example - essentially just all of the colours you intend to use that have 'names'. In your second list, put words that are just plain colours such as "Gold", "Green" or "Silver". Have the program first iterate through your complex colour names, and then your simple one if no match was found in the first one.
var complexList = ColourLists.ComplexList;
var simpleList  = ColourLists.SimpleList;
var productName = "iPad Pro(9.7) 32GB in Rose Gold";
var productColour = string.Empty;

foreach(var colour in complexList)
{
    if(productName.Contains(colour, StringComparison.Ordinal))
    {
        productColour = colour;
        break;
    }
}

if(string.IsNullOrEmpty(productColour))
{
    foreach (var colour in simpleList)
    {
        if (productName.Contains(colour, StringComparison.Ordinal))
        {
            productColour = colour;
            break;
        }
    }
}

This would return your complex colour (in this scenario, Rose Gold would be found in the first foreach loop). If no complex colour was found, then it would return a simple colour (assuming there is one). You can set your productName variable to pull it directly from a model or object instead of being a string like how I've done it.


Q:

What memory Scanners/Editors are available?

Are there memory scanners/editors for Ubuntu (like CheatEngine for Windows)?
I'm aware of scanmem, but I'm thinking about something with a GUI and that lets me visualize the memory segment.

A:

sudo apt-get install gameconqueror
Gameconqueror
Description-en: GUI for scanmem, a game hacking tool
 Scanmem is a simple interactive debugging utility for Linux, used to locate
 the address of a variable in a running process. This can be used for the
 analysis or modification of a hostile process on a compromised machine, for
 reverse engineering, or as a "pokefinder" to cheat at video games.
 .
 GameConqueror is a GUI for scanmem, aims to provide more features than
 scanmem, and CheatEngline-alike user-friendly interface.
Homepage: https://github.com/scanmem/scanmem


Q:

Change the color of an element with dropdown

I wanna change a svg with the help of a dropdown menu with javascript.
My javascript works fine when I wanna change a paragraph element. Then it clears the old class and gives a new based on the text of dropdown option.
But when I use it to change a svg image it works for any times. It gives a new class to the svg element. But the wiping out of the old class does not work and then its broken.

var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')

// When a new <option> is selected
selectElem.addEventListener('change', function() {

  //get value text
  var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;

  pElem.className = '';

  // Add that class to the

  pElem.classList.add(colorValue);
})
.grün {color: green;}
.gelb {color: yellow;}
.blau {color: blue;}
.rot {color: red;}
.pink {color: pink;}

svg {width: 20%;
    height: 20%;}

Element

<select id="select">
  <option selected>grün</option>
  <option>gelb</option>
  <option>blau</option>
  <option>rot</option>
  <option>pink</option>
</select>

Here SVG changing code:

var selectElem = document.getElementById('select')
var pElem = document.getElementById('one')

// When a new <option> is selected
selectElem.addEventListener('change', function() {

  //get value text
  var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;

  pElem.className = '';

  // Add that class to the

  pElem.classList.add(colorValue);
})
.weiss {fill: white;}
.grün {fill: green;}
.gelb {fill: yellow;}
.blau {fill: blue;}
.rot {fill: red;}
.pink {fill: pink;}
<svg id="one" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" />
</svg>

Element

<select id="select">
  <option selected>grün</option>
  <option>gelb</option>
  <option>blau</option>
  <option>rot</option>
  <option>pink</option>
</select>

A:

You need to change pElem.className = '' to pElem.classList = ''.

var selectElem = document.getElementById('select')
var pElem = document.getElementById('one')

// When a new <option> is selected
selectElem.addEventListener('change', function() {

  //get value text
  var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;

  pElem.classList = '';

  // Add that class to the

  pElem.classList.add(colorValue);
})
.weiss {fill: white;}
.grün {fill: green;}
.gelb {fill: yellow;}
.blau {fill: blue;}
.rot {fill: red;}
.pink {fill: pink;}
<svg id="one" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" />
</svg>

Element

<select id="select">
  <option selected>grün</option>
  <option>gelb</option>
  <option>blau</option>
  <option>rot</option>
  <option>pink</option>
</select>

This should fix your problem.
Links: className docs, classList docs
Related tags: css, html, classname


Q:

Wirecloud geojson in a map

Hello i'm trylling to show an entity with geojson data in a map inside of Wirecloud. The data comes from my own instance of Orion. Here you have some screenshots where you can see the data from Orion and the configuration.
General configuration
Entity to POI configuration
Dashboard, Json editor is just to show the data
If i change the lat and long and i put it in a normal attribute with name, it works but in the geojson array it doesn't work.
Can someone tell me what i'm doing wrong.
Thanks

A:

After some days of working, I saw that the version in the repo of the component "NGSI Entity 2 PoI operator" is hightest than the one that it's in the Wirecloud's marketplace, in the last commits i saw that geojson support was added so i tried it but it didn't work so I forked the repo and i fixed it.
Here it is my fixed version.
https://github.com/xXcoronaXx/ngsi-entity2poi-operator


Q:

How to insert and display new node in a JTree of the file system contents

I have successfully created a small program that will display the file system contents in a JTree. It shows only folders and plain text files by design. I would now like to add a folder to the tree when it is created. The example program will display the tree and create a folder, but it will not insert a new node for the folder that was just created. How can I insert a node into the tree when a folder is created and have the tree display the new folder?
Many thanks!
This class creates and displays the tree.
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class TreeFrame extends JFrame{

    private JTree fileTree = null;
    private String USER_HOME = System.getProperty("user.home");

    public TreeFrame(){
        super("File Tree");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //Create tree
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new File(USER_HOME));
        fileTree = new JTree(new FileTreeModelTest(rootNode));
        fileTree.setCellRenderer(new TreeCellRendererTest());
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                //Commented out the next part because it causes a null pointer exception.
                //I believe it is caused by the tree not inserting a node.
                //JTree tree = (JTree)e.getSource();
                //DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                //Object obj = node.getUserObject();//Causes a null pointer exception
                //if(obj instanceof File){
                //    File f = (File)node.getUserObject();
                //    System.out.println(f.getAbsolutePath());
                //}
            }
        });

        JPanel panel = new JPanel();
        JLabel folderLabel = new JLabel("Name:");
        panel.add(folderLabel, BorderLayout.WEST);
        final JTextField textField = new JTextField(25);
        textField.setPreferredSize(new Dimension(100, 28));
        panel.add(textField, BorderLayout.CENTER);
        JButton button = new JButton("Create Foder");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                //Add a folder when the menu item is clicked
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)fileTree.getLastSelectedPathComponent();
                File f = (File)node.getUserObject();
                if(f.isDirectory()){
                    File dir = new File(f.getAbsolutePath()+"/"+textField.getText().trim());

                    if(dir.mkdirs()){
                        System.out.println("ADDED: " + dir.getAbsolutePath());

                        //Insert node into tree model -- this is the part that does not seem to work.
                        FileTreeModelTest model = (FileTreeModelTest)fileTree.getModel();
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(dir);
                        model.insertNodeInto(child, node, node.getChildCount());
                        model.reload(node);
                        TreeNode[] nodes = model.getPathToRoot(child);
                        TreePath path = new TreePath(nodes);
                        fileTree.scrollPathToVisible(path);
                        fileTree.setSelectionPath(path);

                    }

                }
            }
        });
        panel.add(button, BorderLayout.EAST);
        getContentPane().add(panel, BorderLayout.NORTH);

        JScrollPane scrollPane = new JScrollPane(fileTree);
        scrollPane.setPreferredSize(new Dimension(200, 400));

        getContentPane().add(scrollPane, BorderLayout.CENTER);
        pack();

    }

    public static void main(String[] args){
        TreeFrame frame = new TreeFrame();
        frame.setVisible(true);
    }

}

This class is the tree model.
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;

public class FileTreeModelTest extends DefaultTreeModel {

    public FileTreeModelTest(DefaultMutableTreeNode root){
            super(root);
        }

        private File[] getFiles(File parent){
            File[] f = parent.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    if(file==null)
                        return false;
                    if(file.isDirectory())
                        return true;
                    if(file.getName().toLowerCase().endsWith("txt")){
                        return true;
                    }
                    return false;
                }
            });
            return f;
        }

        @Override
        public Object getChild(Object parent, int index){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)parent;
            File p = (File)node.getUserObject();
            File[] pFile = getFiles(p);
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(pFile[index]);
            return child;
        }

        @Override
        public int getChildCount(Object parent){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)parent;
            File f = (File)node.getUserObject();
            if(!f.isDirectory()){
                return 0;
            }else{
                //Is a directory, return number of folders and text files
                File[] children = getFiles(f);
                if(children==null) return 0;
                return children.length;
            }
        }

        @Override
        public int getIndexOfChild(Object parent, Object child){
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent;
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)child;
            File p = (File)parentNode.getUserObject();
            File c = (File)childNode.getUserObject();

            File[] pFile = getFiles(p);
            return Arrays.asList(pFile).indexOf(c);
        }

        @Override
        public Object getRoot(){
            return root;
        }

        @Override
        public boolean isLeaf(Object parent){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)parent;
            File f = (File)node.getUserObject();
            if(f.isDirectory()){
                File[] children = getFiles(f);
                if(children==null) return true;
                //F is a directory. If it has no files, then it is a leaf.
                return children.length==0;
            }else{
                //F is a file. It is a leaf.
                return true;
            }
        }

}

This last class is the tree cell renderer.
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.io.File;

public class TreeCellRendererTest extends DefaultTreeCellRenderer {

    private FileSystemView fsv = FileSystemView.getFileSystemView();

    public TreeCellRendererTest(){

    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

            if(value instanceof DefaultMutableTreeNode){
                Object obj = ((DefaultMutableTreeNode) value).getUserObject();

                if(obj instanceof File){
                    File f = (File)obj;
                    if(row==0){
                        setIcon(fsv.getSystemIcon(f));
                        setText(f.getPath());
                    }else
                    if(f.isFile()){
                        setIcon(fsv.getSystemIcon(f));
                        setText(f.getName());
                    }else{
                        setIcon(fsv.getSystemIcon(f));
                        setText(f.getName());
                    }
                }
            }

            return this;
        }

}

A:

There seems to be a basic mismatch of approaches.  You are using DefaultMutableTreeNodes, which cache there child nodes, but are managing the actual nodes directly via the model, this is causing confusion at multiple different levels...
If you want to continue monitoring the disk contents directly (or proxying it), I would create a custom TreeNode whose sole responsibility was to monitor a single directory.
I would then create a custom TreeModel (probably from the DefaultTreeModel), which provided a makeDirectory method, which you would pass the currently selected TreeNode and the name of the directory.
This method would then be responsible for the physical creation of the directory and notification of the  structural changes to the JTree (via the nodesWereInserted method).  I'd probably have this node return an instance a TreeNode which represented the child...
There are a lot of problems with this approach, namly with the referencing of objects.  In your current approach, you are creating a new DefaultMutableTreeNode whenever getChild is called, this could cause issues if parts of the API are relying on those references remaining constant for the given position/data, this would require you to maintain some kind of internal cache, linking the File with the TreeNode...which kind of defeats the purpose...
A better approach might be to utilising the existing "mutable tree node" API, each node would still be responsible for a single File, but it would also cache the results.  The problem here is managing when a node should be populated (as you don't want to populate directory nodes that are not expanded).
I you are planning on utilising the "Watch Service" API, then I would go for the "mutable tree node" API and cache the child files within it (as you need to), it will simply the issues...


Q:

Undecorated JDialog / JFrame bigger than a decorated one

I found out that when placing 2 similar JFrames
in the same location :
import java.awt.Color;
import java.awt.Point;
import javax.swing.JFrame;

public class Test{

  public static void main(String[] args) throws InterruptedException {

        JFrame jFrame = new JFrame();
        jFrame.setSize(400,200);
        jFrame.setUndecorated(true);
        jFrame.setLocation(new Point(200,200));
        jFrame.getContentPane().setBackground(Color.RED);
        jFrame.setVisible( true );

        JFrame jFrame2 = new JFrame();
        jFrame2.setSize(400,200);
        jFrame2.setUndecorated(false);
        jFrame2.setLocation(new Point(200,200));
        jFrame2.getContentPane().setBackground(Color.GREEN);
        jFrame2.setVisible( true );
  }
}

Where one JFrame is decorated and the other isn't, yields a decorated frame (in green) which is smaller than the undecorated one (in red):

The bounds of the two frames are the same, as expected:

JFrame 1 bounds java.awt.Rectangle[x=200,y=200,width=400,height=200]
  JFrame 2 bounds java.awt.Rectangle[x=200,y=200,width=400,height=200]

I did not find what's causing it.

A:

I found out what is causing decorated and undecorated JFrame or JDialog to have different display size.
It is due to the insets. The size of the insets (which can be checked using jFrame.getInsets() ) of an undecorated window is 0, while the size of it for a decorated window is > 0.


Q:

Eliminate < > as accepted characters in a wordpress password?

Is it possible to eliminate these characters from a wordpress password? I have heard that it can open up scripts this way, that hackers can use to get in.   Thank you.

A:

Simple answer:
Your friend has misinformed you. Restricting these characters in a wordpress password is not something you need to worry about. But as they say "There is no smoke without fire".
More background information:
In your own web-application code, you should always be especially careful whenever you take any data from a user (Whether from a form, a cookie,or a URL) or another external computer system or application. The reason for this is that you want to avoid the values being interpreted as code and not just used as data.
The issue that has led your friend to worry about the <> characters is called Cross-Site Scripting and is a kind of attack that malicious users can perform to "inject" html or javascript content into your pages. If you accept information from the user that contains these html mark-up characters and re-display it on the same, or another page, then you can cause their html or javascript content to become part of your page. Any javascript content will run with access to the same data as the user that views the page.
Whenever outside data is read, it sould always be

validated : i.e. checked that it looks like the kind of thing you are expecting, and rejected if it doe not.
and encoded: i.e. When this data is displayed to back to the user or sent to another part of the system, it is converted to be safe. The type of conversion always depends on how and where the data is being used.

Please note that the angle-bracket characters are not the only thing to worry about. Please also note that it is well proven that disallowing certain characters (also called "blacklisting") is never the best way to secure code. It is always safer to state what is allowed (also called "whitelisting").


Q:

How to programmatically update the selected resource for link-with-editor functionality?

My Eclipse plugin provides an editor which contains a list of files (as result of a dependency search). When the user selects a file in the list, this file/resource should be highlighted in package/resource explorer.
This could be done easily using the link-with-editor functionality of the explorer view if there was a call like: updateSelectedResource(IResource) that I could call from within my editor to explicity set the active file. What is the actual call?

A:

Your editor must become a ISelectionProvider. In the Eclipse FAQ you get a complete example, where the important line for registering your selection provider is getSite().setSelectionProvider(viewer);. Afterwards the selected file in your list is automatically told to all selection listeners, including the package explorer.
If you want to get the big picture about the selection service (which is responsible for making those views react on selections in other views), there is an Eclipse article describing it in detail.
And if find yourself wanting to interact with even more existing views, you may also want to have a look at IAdaptable, as described here, but this is not necessary for the package explorer linking.


Q:

Embed .Net dll into Microsoft Access Database

1) Is it possible to embed a .net dll into a Microsoft Access database? Ideally I want the dll actually embedded into the access database, so it can't go missing. I need to access a few APIs from within my access database.
2) If it is possible, what are the limitations? I'm assuming the access database would have to be used on a machine that had .net installed. Are there any other issues that I should consider?

A:

This actually seems to be 2 slightly different questions than the ones asked, if I'm reading it correctly: (1) Can you embed a binary in an JET/ACE database? and (2) Can you call methods from a .NET DLL from MS-Access?

Yes, you can embed a binary file in an JET/ACE database.  My preferred way of doing this is by reading the file as binary and encoding as base64 in a Memo field.

First, you need to read in the binary file into a byte array.  This can be done using Open, or by using an ADODB.Stream object.  Then, you encode the byte array as a Base64 string, and finally, you write that string to a table.  To export the binary, you do the opposite.
Here are functions to convert a byte array to Base 64 (Source):
'Requires reference to Microsoft XML v3.0
Private Function EncodeBase64(ByRef arrData() As Byte) As String

    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement

    ' help from MSXML
    Set objXML = New MSXML2.DOMDocument

    ' byte array to base64
    Set objNode = objXML.createElement("b64")
    objNode.dataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.Text

    ' thanks, bye
    Set objNode = Nothing
    Set objXML = Nothing

End Function

Private Function DecodeBase64(ByVal strData As String) As Byte()

    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement

    ' help from MSXML
    Set objXML = New MSXML2.DOMDocument
    Set objNode = objXML.createElement("b64")
    objNode.dataType = "bin.base64"
    objNode.Text = strData
    DecodeBase64 = objNode.nodeTypedValue

    ' thanks, bye
    Set objNode = Nothing
    Set objXML = Nothing

End Function

And, here are examples of how to use those Base64 functions to import and export a binary file into a Memo field using an ADODB.Stream object:
Function ImportBinary()
    'Requires a reference to ActiveX Data Objects 2.8 or higher
    Dim InputStream As ADODB.stream
    Dim FileBytes() As Byte

    Set InputStream = New ADODB.stream
    InputStream.Type = adTypeBinary
    InputStream.Open
    InputStream.LoadFromFile ("A:\Binary\File\To\Import.dll")
    FileBytes = InputStream.Read()

    With CurrentDb().TableDefs("TableWithMemoField").OpenRecordset
        .AddNew
        !MemoField.Value = EncodeBase64(FileBytes)
        .Update
        .Close
    End With

    InputStream.Close
End Function

Function ExportBinary()
    Dim OutputStream As ADODB.stream

    Set OutputStream = New ADODB.stream
    OutputStream.Type = adTypeBinary
    OutputStream.Open

    With CurrentDb().TableDefs("TableWithMemoField").OpenRecordset
        OutputStream.Write DecodeBase64(!MemoField.Value)
        .Close
    End With

    OutputStream.SaveToFile "A:\Binary\File\To\Export.dll"

    OutputStream.Close
End Function

Alternatively, you could also embed the file(s) into OLE fields, or, recent versions of Access also have an "Attachment" field. I believe it is possible to use this.

Yes, it's possible to call methods from a .NET DLL - see here.  What you are essentially doing is hosting the .NET runtime in Access.

The limitation is that you can only host the .NET 2.0 or 3.5 runtime -- despite the fact that the linked page says you can use 4.0.  As far as I know, there is no easy way to host the .NET 4.0+ runtime in VBA.  If you try to call a 4.0+ DLL, you will get an error to the effect of "the assembly is newer than the runtime".
Yes, you'd also need to use it on a machine that had the 2.0 and/or 3.5 runtimes installed on it.
Also, it won't load a DLL directly from a network share.  This is a limitation of the .NET framework which it is possible to overcome (link), but I'm not sure if that can be done when hosting the DLL in Access.
In order to use the "embedded" DLL, you need to export it from the database before you use it; a good place would be the user's temp folder.
EDIT: Regarding point (2)-- I had previously written that you do not need to expose your C# class as COM, however, after testing this I realized this was incorrect. You do need to declare your class with a [COMVisible(true)] attribute (or implement an IDispatch interface) in order for VBA to correctly instantiate your class-- otherwise CreateInstanceFrom will return Nothing.


Q:

Why am I getting a type mismatch error with a type I cannot see anywhere in my solution?

I am getting the following error in an editor template of mine, ApplicantAddressMode:

error CS0019: Operator '!=' cannot be applied to operands of type
  'Comair.RI.ViewModels.ApplicantAddressType' and
  'Comair.RI.Models.ApplicantTypesOfAddress'"}

The type Comair.RI.ViewModels.ApplicantAddressType is nowhere to be found. A global solution search of all files for just the ApplicantAddressType returns no results. I changed the name of the enum in Comair.RI.Models from ApplicantAddressType to ApplicantTypesOfAddress to try and avoid an unintentional match, and cleaned out both 32 bit and 64 bit Temporary ASP Internet Files, and yet the error still persists on this line of the editor template:
@using Comair.RI.Models
@model Comair.RI.ViewModels.ApplicantAddressModel
@Html.ValidationSummary(true)
<fieldset>
    <legend>@Model.AddressTypeDescription</legend>
    <ul class="form-column">
        @if (Model.AddressType != ApplicantTypesOfAddress.Residential)
        {

Model.AddressType is declared as:
[ScaffoldColumn(false)]
public ApplicantTypesOfAddress AddressType { get; set; }

I am at my wits end about to start throwing flaming, pointed flags around, like IsResidentialStreetNumber and IsPostalSuburb. I don't think the ambulances will arrive long after that and take me away to peace.
The enum declaration is like this:
namespace Comair.RI.Models
{
    public enum ApplicantTypesOfAddress
    {
        Residential,
        Postal
    }
}

A:

The tpe that was suspected missing was declared in a file not included in the project. When you tell VS to build view at compile time, which in normally only does just before rendering them, not when it builds the application assembly, it builds all views, and uses any files they refer to whether they are included in the project or not.
Jim Lamb has a good post on how to do this called Turn on Compile-time View Checking for ASP.NET MVC Projects in TFS Build 2010
I don't know about the TFS Build part though. I don't use that, in my case simply adding the following element to my .csproj file did the trick. Note, if the MvcBuildViews element already exists, it's text value must be true.
<PropertyGroup>
    <MvcBuildViews>true</MvcBuildViews>
</PropertyGroup>

Caveat Emptor.


Q:

How to delete dynamic component in Nuxt.js

I used Nuxt.js with Vue.js. I added dynamic component like this.
// pages/index.vue
<template>

    <component v-for="item in buttons" :is="item" :key="item.id" :buttons="buttons" />
    ADD

</template>

and in the component
// components/productFilter.vue
<template>
..........
  del
..
..
..
</template>

like this.
when I click add button, then appear component per click.
and when I click del button, then delete last component...
I want to delete the component that corresponds to the button I clicked.
Why didn't work indexOf? I watch console.log(this.buttons.indexOf(item));, it did work! When I click second button, then appear index 1. But Why didn't work at component?

A:

I think you do not have access to this.buttons in components/productFilter.vue because this.buttons is scoped to its component instance and it's not a good practice to provide it in props and to expect reactivity in its parent. I would suggest you to pass the index of this dynamic component in it via props item-id and then to emit an event in delQuerysToStore() and after that to remove the component in the parent pages/index.vue. Example:
// components/productFilter.vue

 props: {
   itemId: {
     type: Number,
     default: 0
   }
},
 methods: {
  delQuerysToStore(item) {
      this.$emit('delete', this.itemId)
    }
  }
}

// pages/index.vue

<template>

    <component v-for="(item, index) in buttons" :is="item" :key="item.id" :buttons="buttons" @delete="deleteComponent" :item-id="index"/>
    ADD

</template>

In general this is the standard and good practice: Data down -> actions up. You provide data down to lower level components, but the lower level components emit events to their parent and thus the communication work between components.


Q:

Custom Tableview cell with multiline UILabel needs dynamic height

I created a custom TableView cell with Interface Builder. This is what it looks like:

For the Description Label, I need that to word wrap so I set it as such:

In my SettingsPageViewController, I have the following Table View methods overridden:
@implementation SBSettingsViewController
{
    NSArray *settingHeaders;
    NSArray *settingDescriptions;
}
- (void)viewDidLoad {
[super viewDidLoad];

[self setupLeftMenuButton];
// Do any additional setup after loading the view from its nib.
settingHeaders = [NSArray arrayWithObjects:@"Label Header 1",@"Label Header 2",nil];
settingDescriptions = [NSArray arrayWithObjects:@"Two line description Two line description Two line description ",@"One Line Description",nil];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [settingHeaders count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"SettingsTableCell";

SettingsTableViewCell *cell = (SettingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SettingsTableCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

cell.settingsHeaderLabel.text = [settingHeaders objectAtIndex:indexPath.row];
cell.settingsDescriptionLabel.text = [settingDescriptions objectAtIndex:indexPath.row];

cell.settingsDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.settingsDescriptionLabel.numberOfLines = 0;
CGRect appFrame=[[UIScreen mainScreen] bounds];
cell.settingsDescriptionLabel.preferredMaxLayoutWidth = appFrame.size.width - 15;

[cell.settingsDescriptionLabel sizeToFit];
[cell.settingsDescriptionLabel setNeedsDisplay];
[cell layoutIfNeeded];

return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [tableView setLayoutMargins:UIEdgeInsetsZero];
}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsZero];
}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 85;
}

Here is what the resulting page looks like:

As you can see, the description label for the 1st tableview cell does NOT word wrap. It just cuts off. How do I make it wrap?
Also, I'd like for the Tableview cell height to be dynamically adjusted. I tried to change the heightForRowAtIndexPath: to be UITableViewAutomaticDimension but that just made it look super weird as such:

How do I get the tableview height adjusted for the row with the 1 line description label is slightly shorter?
Thanks you for your help!

A:

give constraint of header label top, leading, trailing to super view and bottom (vertical ) to description Label.
same for description label >  leading, trailing  and bottom margin to super view.
now set Header label height Fix and description label make multiline ( Lines = 0)
for table view set in viewDidLoad
_tableView.estimatedRowHeight = 100.0;
_tableView.rowHeight = UITableViewAutomaticDimension;

Let me know if this works...


Q:

aurelia-forms bundling issue aurelia-cli

I am attempting to use the Aurelia-Form plugin in a Aurelia\Aspnetcore\Typescript project.
Unfortunately I get an issue when using the aurelia-cli build process where the aurelia-form components are not correctly bundled.
Bundling progress
On the left is how it should (Project taken from here https://github.com/SpoonX/swan-example-client).
I am thinking that there might be a error in my aurelia.json but I can't see anything suspicious.

{
  "name": "AuFormsEx",
  "type": "project:application",
  "platform": {
    "id": "aspnetcore",
    "displayName": "ASP.NET Core",
    "output": "wwwroot\\scripts",
    "baseUrl": "scripts"
  },
  "transpiler": {
    "id": "typescript",
    "displayName": "TypeScript",
    "fileExtension": ".ts",
    "dtsSource": [
      "./typings/**/*.d.ts",
      "./custom_typings/**/*.d.ts"
    ],
    "source": "src\\**\\*.ts"
  },
  "markupProcessor": {
    "id": "none",
    "displayName": "None",
    "fileExtension": ".html",
    "source": "src\\**\\*.html"
  },
  "cssProcessor": {
    "id": "none",
    "displayName": "None",
    "fileExtension": ".css",
    "source": "src\\**\\*.css"
  },
  "editor": {
    "id": "visualstudio",
    "displayName": "Visual Studio"
  },
  "unitTestRunner": {
    "id": "none",
    "displayName": "None"
  },
  "paths": {
    "root": "src",
    "resources": "src\\resources",
    "elements": "src\\resources\\elements",
    "attributes": "src\\resources\\attributes",
    "valueConverters": "src\\resources\\value-converters",
    "bindingBehaviors": "src\\resources\\binding-behaviors"
  },
  "build": {
    "targets": [
      {
        "id": "aspnetcore",
        "displayName": "ASP.NET Core",
        "output": "wwwroot\\scripts",
        "baseUrl": "scripts"
      }
    ],
    "loader": {
      "type": "require",
      "configTarget": "vendor-bundle.js",
      "includeBundleMetadataInConfig": "auto",
      "plugins": [
        {
          "name": "text",
          "extensions": [
            ".html",
            ".css"
          ],
          "stub": true
        }
      ]
    },
    "options": {
      "minify": "stage & prod",
      "sourcemaps": "dev & stage"
    },
    "bundles": [
      {
        "name": "app-bundle.js",
        "source": [
          "[**/*.js]",
          "**/*.{css,html}"
        ]
      },
      {
        "name": "vendor-bundle.js",
        "prepend": [
          "node_modules/bluebird/js/browser/bluebird.core.js",
          "wwwroot\\scripts/require.js"
        ],
        "dependencies": [
          "aurelia-binding",
          "aurelia-bootstrapper",
          "aurelia-dependency-injection",
          "aurelia-event-aggregator",
          "aurelia-framework",
          "aurelia-history",
          "aurelia-history-browser",
          "aurelia-loader",
          "aurelia-loader-default",
          "aurelia-logging",
          "aurelia-logging-console",
          "aurelia-metadata",
          "aurelia-pal",
          "aurelia-pal-browser",
          "aurelia-path",
          "aurelia-polyfills",
          "aurelia-route-recognizer",
          "aurelia-router",
          "aurelia-task-queue",
          "aurelia-templating",
          "aurelia-templating-binding",
          "aurelia-fetch-client",
          "extend",
          "aurelia-view-manager",
          {
            "name": "aurelia-validation",
            "path": "../node_modules/aurelia-validation/dist/amd",
            "main": "index"
          },
          {
            "name": "validate.js",
            "path": "../node_modules/validate.js",
            "main": "validate"
          },
          {
            "name": "aurelia-validatejs",
            "path": "../node_modules/aurelia-validatejs/dist/amd",
            "main": "aurelia-validatejs"
          },
          {
            "name": "aurelia-form",
            "path": "../node_modules/aurelia-form/dist/amd",
            "main": "aurelia-form",
            "resources": [
              "component/**/*.html"
            ]
          },
          "jquery",
          {
            "name": "bootstrap",
            "path": "../node_modules/bootstrap/dist",
            "main": "js/bootstrap.min",
            "deps": [ "jquery" ],
            "exports": "$",
            "resources": [
              "css/bootstrap.css"
            ]
          },
          {
            "name": "text",
            "path": "../wwwroot\\scripts/text"
          },
          {
            "name": "aurelia-templating-resources",
            "path": "../node_modules/aurelia-templating-resources/dist/amd",
            "main": "aurelia-templating-resources"
          },
          {
            "name": "aurelia-templating-router",
            "path": "../node_modules/aurelia-templating-router/dist/amd",
            "main": "aurelia-templating-router"
          },
          {
            "name": "aurelia-testing",
            "path": "../node_modules/aurelia-testing/dist/amd",
            "main": "aurelia-testing",
            "env": "dev"
          }
        ]
      }
    ]
  }
}

Any ideas?

A:

In case you are still looking for an answer, I would recommend you leave config.json the way the Aurelia-CLI creates it, and then publish to the wwwroot from Visual studio. Take a look at this one I have just generated.
{
  "name": "AuFormsEx",
  "type": "project:application",
  "platform": {
    "id": "aspnetcore",
    "displayName": "ASP.NET Core",
    "output": "scripts",
    "index": "index.html",
    "baseUrl": "scripts"
  },
  "transpiler": {
    "id": "typescript",
    "displayName": "TypeScript",
    "fileExtension": ".ts",
    "dtsSource": [
      "./typings/**/*.d.ts",
      "./custom_typings/**/*.d.ts"
    ],
    "source": "src/**/*.ts"
  },
  "markupProcessor": {
    "id": "none",
    "displayName": "None",
    "fileExtension": ".html",
    "source": "src/**/*.html"
  },
  "cssProcessor": {
    "id": "none",
    "displayName": "None",
    "fileExtension": ".css",
    "source": "src/**/*.css"
  },
  "editor": {
    "id": "visualstudio",
    "displayName": "Visual Studio"
  },
  "unitTestRunner": {
    "id": "none",
    "displayName": "None"
  },
  "paths": {
    "root": "src",
    "resources": "src/resources",
    "elements": "src/resources/elements",
    "attributes": "src/resources/attributes",
    "valueConverters": "src/resources/value-converters",
    "bindingBehaviors": "src/resources/binding-behaviors"
  },
  "build": {
    "targets": [
      {
        "id": "aspnetcore",
        "displayName": "ASP.NET Core",
        "output": "scripts",
        "index": "index.html",
        "baseUrl": "scripts"
      }
    ],
    "loader": {
      "type": "require",
      "configTarget": "vendor-bundle.js",
      "includeBundleMetadataInConfig": "auto",
      "plugins": [
        {
          "name": "text",
          "extensions": [
            ".html",
            ".css"
          ],
          "stub": true
        }
      ]
    },
    "options": {
      "minify": "stage & prod",
      "sourcemaps": "dev & stage"
    },
    "bundles": [
      {
        "name": "app-bundle.js",
        "source": [
          "[**/*.js]",
          "**/*.{css,html}"
        ]
      },
      {
        "name": "vendor-bundle.js",
        "prepend": [
          "node_modules/bluebird/js/browser/bluebird.core.js",
          "node_modules/requirejs/require.js"
        ],
        "dependencies": [
          "aurelia-binding",
          "aurelia-bootstrapper",
          "aurelia-dependency-injection",
          "aurelia-event-aggregator",
          "aurelia-framework",
          "aurelia-history",
          "aurelia-history-browser",
          "aurelia-loader",
          "aurelia-loader-default",
          "aurelia-logging",
          "aurelia-logging-console",
          "aurelia-metadata",
          "aurelia-pal",
          "aurelia-pal-browser",
          "aurelia-path",
          "aurelia-polyfills",
          "aurelia-route-recognizer",
          "aurelia-router",
          "aurelia-task-queue",
          "aurelia-templating",
          "aurelia-templating-binding",
          "text",
          {
            "name": "aurelia-templating-resources",
            "path": "../node_modules/aurelia-templating-resources/dist/amd",
            "main": "aurelia-templating-resources"
          },
          {
            "name": "aurelia-templating-router",
            "path": "../node_modules/aurelia-templating-router/dist/amd",
            "main": "aurelia-templating-router"
          },
          {
            "name": "aurelia-testing",
            "path": "../node_modules/aurelia-testing/dist/amd",
            "main": "aurelia-testing",
            "env": "dev"
          }
        ]
      }
    ]
  }
}

You are also mixing \\ and / path separators and that is not necessary.
I hope this helps.


Q:

Flexible array error with gcc 6 but not with gcc 4

I'm trying to compile a piece of code written by a colleague. On my machine with gcc 6.1.1 I get this error:
In file included from src/TYAGlobalLibs.cc:1:0:
./include/TYAGlobalLibs.hh:112:17: error: flexible array member ‘TYA::TMultiHist::fh’ not at end of ‘class TYA::TMultiHist’
 TH1F    *fh[];
             ^
./include/TYAGlobalLibs.hh:102:9: note: in the definition of ‘class TYA::TMultiHist’
class TMultiHist{
      ^~~~~~~~~~

It seems that this is a forbidden code path and as such it triggers a compiler error; however, using gcc 4.5.2 the same file compiles without error. I use these compiler options for g++:
-O2 -Wall -fPIC -pthread -m32 -std=c++98

for both 6.1.1 and for 4.5.2. In case it matters, gcc 6 runs on a 64 bit machine while gcc 4 on a 32 bit one. Here's a minimal code snippet to reproduce the issue:
struct test{
        int a;
        float b[];
        double c;
};

int main(){
}

Does anybody know why this happens and eventually if there are compiler options to make gcc 6 compile without errors (I have no chance of changing the code, it's not under my control)?

A:

In C (C99 and later), a flexible array member can be defined with [], and must be the last member of a structure.  C++ doesn't support flexible array members, but g++ permits them as a language extension.
Older versions of g++ do not require a flexible array member to be the last member of a class or struct.  This is a bug, which has been corrected in newer versions of g++.
Here's a small test program, based on yours that illustrates the problem:
#include <iostream>
#include <cstddef>

static int mem[100];

struct test{
        int a;
        int b[];
        int c;
};

int main(){
    test *ptr = (test*)&mem;
    ptr->a = 10;
    ptr->b[0] = 20;
    ptr->b[1] = 30;
    ptr->c = 40;

    std::cout << "ptr->a    = " << ptr->a << "\n";
    std::cout << "ptr->b[0] = " << ptr->b[0] << "\n";
    std::cout << "ptr->b[1] = " << ptr->b[1] << "\n";
    std::cout << "ptr->c    = " << ptr->c << "\n";
}

And here's the output when I compile it with g++ 4.1.2:
ptr->a    = 10
ptr->b[0] = 40
ptr->b[1] = 30
ptr->c    = 40

As you can see, the member c is allocated at the same offset as b[0].
(Strictly speaking, using an int[] array to hold a test object isn't 100% safe due to possible alignment problems, but that's unlikely to be an issue in practice.)
It's very likely that your code has undiscovered bugs because of this.
Your problem is not that the newer g++ rejects your code; it's that the older one doesn't.
Reordering the member declarations so the flexible array member appears last is the simplest fix -- though you (or someone else) will need to carefully examine how the type is used.  A far better solution is probably to replace the flexible array member with some C++ container class, perhaps a std::vector.

(I have no chance of changing the code, it's not under my control)

Somebody is able to change the code, and presumably you're able to submit a bug report.


Q:

How to retrieve time in XML

In this XML :
<CD>
<title>Essential Collection </title>
<artist>Lee Dorsey</artist>
<tracks>
<track>Ya Ya</track>
<track>Do Re Mi</track>
<track>Ride Your Pony</track>
<track>Work Work Work</track>
<track>Can You Hear Me</track>
<track>Get Out Of My Life Woman</track>
<track>Working In A Coalmine</track>
<track>Holy Cow</track>
<track>Operation Heartache</track>
<track>Gotta Find A Job</track>
</tracks>
</CD>

CD is Compact Disc. It has different song tracks. I want to calculate total playing time of CD. How I will represent time in XML, in two ways?

A:

How about something like this:
<tracks>
    <track>
        <name>Ya Ya</name>
        <duration>207</duration>
    </track>
    <track>
        <name>Do Re Mi</name>
        <duration>118</duration>
    </track>
    .
    .
    .
</tracks>