text:
Q: How can draw rectangle on camera preview? Hi aim working n android application to  detect page number using camera preview.
After i received frame from OnPreviewFrame i'm doing real time image processing using opencv to find page number position .Now my question is How can i draw rectangle on surface View ?

A: Use this code
PreviewDemo.java
public class PreviewDemo extends Activity implements OnClickListener {

private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
ImageView image;
Bitmap bmp, itembmp;
static Bitmap mutableBitmap;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
File imageFileName = null;
File imageFileFolder = null;
private MediaScannerConnection msConn;
Display d;
int screenhgt, screenwdh;
ProgressDialog dialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.preview);

    image = (ImageView) findViewById(R.id.image);
    preview = (SurfaceView) findViewById(R.id.surface);

    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    previewHolder.setFixedSize(getWindow().getWindowManager()
        .getDefaultDisplay().getWidth(), getWindow().getWindowManager()
        .getDefaultDisplay().getHeight());

}

@Override
public void onResume() {
    super.onResume();
    camera = Camera.open();
}

@Override
public void onPause() {
    if (inPreview) {
        camera.stopPreview();
    }

    camera.release();
    camera = null;
    inPreview = false;
    super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size: parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }
    return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {
            Log.e("PreviewDemo-surfaceCallback",
                "Exception in setPreviewDisplay()", t);
            Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG)
                .show();
        }
    }

    public void surfaceChanged(SurfaceHolder holder,
    int format, int width,
    int height) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height,
        parameters);

        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.startPreview();
            inPreview = true;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
    public void onPictureTaken(final byte[] data, final Camera camera) {
        dialog = ProgressDialog.show(PreviewDemo.this, "", "Saving Photo");
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {}
                onPictureTake(data, camera);
            }
        }.start();
    }
};

public void onPictureTake(byte[] data, Camera camera) {

    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
    savePhoto(mutableBitmap);
    dialog.dismiss();
}

class SavePhotoTask extends AsyncTask < byte[], String, String > {@Override
    protected String doInBackground(byte[]...jpeg) {
        File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
        if (photo.exists()) {
            photo.delete();
        }
        try {
            FileOutputStream fos = new FileOutputStream(photo.getPath());
            fos.write(jpeg[0]);
            fos.close();
        } catch (java.io.IOException e) {
            Log.e("PictureDemo", "Exception in photoCallback", e);
        }
        return (null);
    }
}

public void savePhoto(Bitmap bmp) {
    imageFileFolder = new File(Environment.getExternalStorageDirectory(), "Rotate");
    imageFileFolder.mkdir();
    FileOutputStream out = null;
    Calendar c = Calendar.getInstance();
    String date = fromInt(c.get(Calendar.MONTH)) + fromInt(c.get(Calendar.DAY_OF_MONTH)) + fromInt(c.get(Calendar.YEAR)) + fromInt(c.get(Calendar.HOUR_OF_DAY)) + fromInt(c.get(Calendar.MINUTE)) + fromInt(c.get(Calendar.SECOND));
    imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
    try {
        out = new FileOutputStream(imageFileName);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public String fromInt(int val) {
    return String.valueOf(val);
}

public void scanPhoto(final String imageFileName) {
    msConn = new MediaScannerConnection(PreviewDemo.this, new MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            msConn.scanFile(imageFileName, null);
            Log.i("msClient obj  in Photo Utility", "connection established");
        }
        public void onScanCompleted(String path, Uri uri) {
            msConn.disconnect();
            Log.i("msClient obj in Photo Utility", "scan completed");
        }
    });
    msConn.connect();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
        onBack();
    }
    return super.onKeyDown(keyCode, event);
}

public void onBack() {
    Log.e("onBack :", "yes");
    camera.takePicture(null, null, photoCallback);
    inPreview = false;
}

@Override
public void onClick(View v) {
}
}

Preview.xml
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

 <android.view.SurfaceView
 android:id="@+id/surface"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</RelativeLayout>

Add the Permissions also


text:
Q: Any jQuery plugin that could replace html select tag? It's nothing new - select tag looks damn ugly.
Is there nice jQuery plugin out there that could replace it with ease?

A: maybe this could be usefull to you -> http://www.prismstudio.co.uk/2009/05/jquery-plugin-stylish-select-unobstrusive-select-box-replacement/

A: ASM Select is especially nice if you want to improve the appearance and user experience of selects with multiple enabled.

A: Check out SelectBoxIt.  SelectBoxIt can use both jQuery ThemeRoller and jQueryUI show/hide effects.  It currently does not have support for the multiple HTML property though.

A: This question is similar. You could try jquery.combobox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Wordpress to create a simple web app (SaaS) I want to create a fairly simple web application using Wordpress, making use of the built-in functionalities it offers.
The app would a personal journal. New entries would be posts, user can choose categories, add tags, and fill out custom fields.
Basic flow is this:

*

*User creates an account to access the site

*User can can view, edit, delete, and publish posts on the frontend

*User can view statistics about their own posts (total number, by category, by tag)

*User can edit their account information on the frontend

I want to create the same look/design for everybody, but every user should only have access to their own posts. Other things I mentioned above can be done with various plugins, but I'm not sure how I can "restrict" the website for each user.
In Short: I want to create and style a Wordpress website, but have it function in a way that every user sees it as their "private" profile.
What is the best, simplest way to achieve this?

A: There are 2 ways to achieve your result:

*

*Use wordpress`s rest api functionality and some frontend js framework (Angular or React or other at your choice)

*Code custom theme for this purpose - maybe something with authorization and custom userpages

A: Use the Multisite option of WordPress, so each user has his own site, install a theme that its a SaaS, install a plugin to restrict the site to logged only or just use is_user_logged_in() (not sure if you need this, with multisite each user will only be able to access his own site).
As you stated you can install plugins for the statistic part.
Another option would be to create the Theme yourself, and show only content related to the current logged user, you will have to modify the default widgets.


text:
Q: Uploading picture from xamarin form to a php server Please I have been trying to upload pictures from a xamarin form application to a php server but seems not to be working. The server receives an empty $_FILES request. This is the c# code.
    public async Task<bool> Upload(MediaFile mediaFile, string filename)
    {
        byte[] bitmapData;
        var stream = new MemoryStream();
        mediaFile.GetStream().CopyTo(stream);
        bitmapData = stream.ToArray();
        var fileContent = new ByteArrayContent(bitmapData);

        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "fileUpload",
            FileName = filename
        };

        string boundary = "---8393774hhy37373773";
        MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
        multipartContent.Add(fileContent);

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent);
        response.EnsureSuccessStatusCode();

        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();

            return true;
        }
        return false;
     }

Below is the php file to receive the uploaded image. I tried to save the content of the posted image to file but the file only has an empty array and always return "failure". Please what am i missing wrong? I have searched the web but cant seem to understand the problem.
  $uploads_dir = 'uploads/';
  $req_dump = print_r( $_FILES, true );
  $fp = file_put_contents( 'data.txt', $req_dump );
  if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))
  {
    $tmp_name = $_FILES["fileUpload"]["tmp_name"];
    $name = $_FILES["fileUpload"]["name"];
    $Result = move_uploaded_file($tmp_name, "$uploads_dir/$name");
    echo "Success";
  }
  else
  {
    echo "Failure";
  }

A: The AND operator is really not a good choice for you. (On line 4).
Sometimes it shows some really unexpected behaviour. (I can refer you to 'AND' vs '&&' as operator for more info).
If you want a logical AND use the && operator instead.
The line would be
if (isset($_FILES["fileUpload"]["tmp_name"]) && is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))

A: I know this is an old post but this is how I upload an image from Xamarin Forms to PHP
http://gjhdigital.com/xamarin/xamarin-forms-upload-image-to-php/
Xamarin c# code
using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace UploadPicToServer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

private async void btnUpload_Clicked(object sender, EventArgs e)
{

if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

});

if (file == null)
return;

string fileName = file.Path;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});

//UploadImage1(file.AlbumPath);
UploadImage(file.GetStream(), fileName);
}
private async void UploadImage(Stream mfile, string fileName)
{
int authorID = 2;
string username = "yourusername";

var url = "https://yourwebsite.com/ba-add-profile-pic.php";
url += "?id="+ authorID +"&username="+ username; //any parameters you want to send to the php page.

try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://yourwebsite.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
//HttpContent content = new StringContent("fileToUpload");
//form.Add(content, "fileToUpload");

var stream = mfile;
StreamContent content = new StreamContent(stream);

//get file's ext
string fileExt = fileName.Substring(fileName.Length - 4);
string fName = "User-Name-Here-123" + fileExt.ToLower();

content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = fName
};
form.Add(content);
var response = await client.PostAsync(url, form);
var result = response.Content.ReadAsStringAsync().Result;

}
catch (Exception e)
{
//debug
Debug.WriteLine("Exception Caught: " + e.ToString());

return;
}
}

public static byte[] ToArray(Stream s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (!s.CanRead)
throw new ArgumentException("Stream cannot be read");

MemoryStream ms = s as MemoryStream;
if (ms != null)
return ms.ToArray();

long pos = s.CanSeek ? s.Position : 0L;
if (pos != 0L)
s.Seek(0, SeekOrigin.Begin);

byte[] result = new byte[s.Length];
s.Read(result, 0, result.Length);
if (s.CanSeek)
s.Seek(pos, SeekOrigin.Begin);
return result;
}
}
}

PHP code
//parameters send in via querystring
if (!isset($_REQUEST['author']) || !isset($_REQUEST['username']) ) {
die('{"status" : "Bad", "reason" : "Invalid Access"}');
}

$userID = $_REQUEST['author'];
$isGood = false;
try{

$uploaddir = '../someFolderToStoreTheImage/';
$fileName = basename($_FILES['fileToUpload']['name']);
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);

//CHECK IF ITS AN IMAGE OR NOT
$allowed_types = array ('image/jpeg', 'image/png', 'image/bmp', 'image/gif' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['fileToUpload']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( '{"status" : "Bad", "reason" : "Not a valid image"}' );
}
//

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
//echo "File is valid, and was successfully uploaded.\n";
echo '{"status" : "Success", "reason" "'. $fileName .'"}';
$isGood = true;
} else {
//echo "Possible file upload attack!\n";
echo '{"status" : "Bad", "reason" : "Unable to Upload Profile Image"}';
}

}
catch(Exception $e) {
echo '{"status" : "Bad", "reason" : "'.$e->getMessage().'"}';
}


text:
Q: How to detect Daylight saving of EST timing? I have developed a clock which shows IST & EST timings. I am from India, so my system clock setting uses IST settings. I want to display EST daylight timings in the clock. How can I display daylight saving timing of EST?

A: you can use the FindSystemTimeZoneById method like this:
    Dim istNow = System.TimeZoneInfo.ConvertTime(Now, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"))
    Dim estNow = System.TimeZoneInfo.ConvertTime(Now, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
    Debug.WriteLine(istNow.ToString)
    Debug.WriteLine(estNow.ToString)


text:
Q: new to swiftUI. Is there a way to show a blank TextField with the grayed out prompt for a numeric entry I am trying to get numeric input via the TextField. See related code below. The display does not show the TextField with the grayed out 'item1:'. It shows the initialized value of 0 instead. deleting the 0 does show the TextField prompt. Trying to find out if there is a way show the prompt.
@State var item1 = 0

TextField(" item1:", value: $item1, formatter: numberFormatter )

private let numberFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    // formatter.timeStyle = .medium
    return formatter
   }()

A: Make your item1 an optional int, since SwiftUI doesn't know if the value 0 was already provided by the user or not, thus, it assumes a placeholder is not needed, add a check to unwrap the optional safely.
struct TestNumber: View {
    @State private var myNumber: Int?

    var body: some View {
        TextField("Enter a Number", value: $myNumber, formatter: numberFormatter)

    }

    private let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()
}


text:
Q: JSF - Validation error in 1 component, leads all others in the form to fail Hey to all in the forum
I use JSF Mojarra implementation, version JSF 2.2
I need desperately a help on this.

*

*I have a snippet of my page.

*I have a custom component "example_result.xhtml" used in the page.

*I have my BackingBean.java
Be aware please that this code is not the real code I made. If you run it, it will be very ugly maybe because I deleted all the css classes and I kept only the hot stuff I need to show you my problem.

Everything is inside 1 form.
The 5 "h:selectManyCheckbox" (in my code I have 8 or 9)
In the form I have 5 "h:selectManyCheckbox" which are using values in the "value" attribute for different cases (javaFrameworks2Values, javaFrameworks3Values,...), and the "f:selectItems" use arrays of "SelectItem" (javaFrameworksSelectItems2, javaFrameworksSelectItems3...) created for these different  cases, just to make some examples for me to understand how all the selectOne and selectMany components work.
The ideas for this, about different cases were taken from these links:
"https://stackoverflow.com/tags/selectonemenu/info" and
"https://mkyong.com/jsf2/jsf-2-checkboxes-example".
After I have 2 commandButtons
1 for submit, and 1 for reset the values.
Display the values
After I display the results of the values of the "h:selectManyCheckbox" via the "example_result.xhtml".
You can see the 4th "h:selectManyCheckbox" that is the only one different, because it has the attribute "required" with the attribute "requiredMessage". With it there is a "h:message" to display the validation error.
In the BackingBean (which is Spring Bean, but it works perfectly good - sorry I don't want ejbs 3.x),
I have initialized:

*

*The values of the SelectItems and

*The values of the "value" attribute, where the values of the "h:selectManyCheckbox" will be stored to be displayed later.
[The code is completely castrated, to make it readable snippet].

When the page is rendered, I select checkBoxes (e.g. the 2 last, because the 2 first are initials) from all the "h:selectManyCheckbox".
When I say that select from all, I mean it. And from the 4th with the "required" attribute. I try in the buttons (see in the code) the "Effort 1", or "Effort 2", or "Effort 3"  (in the "f:ajax" in the buttons) and the result outputs in the last part are displayed  and updated like a candy. Without any problem. To achive this with the composite component I googled and tried a lot. But I made it.
Then it comes the time to try the 4th to see the validation error of the "required" attribute.
I select again from all as before, but not from all. NOT from the 4th "h:selectManyCheckbox" this time. I select nothing from the 4th "h:selectManyCheckbox" to ckeck the validator error message ("requiredMessage").
The result is:
It displays the message of error (GOOD until now), BUT this time it does not update anything from the others "h:selectManyCheckbox" to the output results at the end, and it does not reset the values as  well as it was doing before (when I selected from all and from the 4th as well).
I understand that it says: as long as in the form the 4th failed with validation error, all the other "h:selectManyCheckbox" will not update the output results (something like wanting to fail all the others too).
But what really happes here?

*

*It does not give the values to the "h:selectManyCheckbox", to be updated to the output?

*It gives the vales to the "h:selectManyCheckbox" normally, BUT it just not updates the output?

The other efforts in the "f:ajax" in the buttons, are just efforts maybe to solve the problem but  in these cases they don't even display the error message in the 4th case and of cource they don't update the other output results as well (again). But no message error as well.
I don't know if the problem is clear to you. I can explain in the discussion better so I can clarify the situation better.
[To be honnet it took me 1 and half hour to write all this thing]
Thanks a lot in advance
========== Snippet from my page ==========
<h:form>
    <h:panelGrid id="smcb" columns="1">

        <h:selectManyCheckbox id="smcb1" value="#{myBackingBean.javaFrameworksHardCodedValues}">
            <f:selectItem itemLabel="Java Label" itemValue="Java Value"/>
            <f:selectItem itemLabel="Spring Framework Label" itemValue="Spring Framework Value"/>
            <f:selectItem itemLabel="Hibernate Label" itemValue="Hibernate Value"/>
            <f:selectItem itemLabel="JSF Framework Label" itemValue="JSF Framework Value"/>
        </h:selectManyCheckbox>

        <h:selectManyCheckbox id="smcb2" value="#{myBackingBean.javaFrameworks2Values}">
            <f:selectItems value="#{myBackingBean.javaFrameworksSelectItems2}"/>
        </h:selectManyCheckbox>

        <h:selectManyCheckbox id="smcb3" value="#{myBackingBean.javaFrameworks3Values}">
            <f:selectItems value="#{myBackingBean.javaFrameworksSelectItems3}"/>
        </h:selectManyCheckbox>

<h:message for="smcb4" styleClass="error_messages"/>

        <h:selectManyCheckbox id="smcb4" value="#{myBackingBean.javaFrameworks4Values}"
                            required="true"
                            requiredMessage="The 'h:selectManyCheckbox' must have a value. Please select an item from the list!">
            <f:selectItems value="#{myBackingBean.javaFrameworksSelectItems4}"/>
        </h:selectManyCheckbox>

        <h:selectManyCheckbox id="smcb5" value="#{myBackingBean.javaFrameworks5Values}">
            <f:selectItems value="#{myBackingBean.javaFrameworksSelectItems5}"/>
        </h:selectManyCheckbox>

    </h:panelGrid>

    <h:commandButton value="Display Java Frameworks values">

        <f:ajax execute="@form"
                render="outputId1 outputId2 outputId3 outputId4 outputId5 smcb1 smcb2 smcb3 smcb4 smcb5"/>
                Other combinations with the @form and the ids...
        -->
    </h:commandButton>
    <h:commandButton value="Reset Java Frameworks values" action="#{myBackingBean.resetValues}">

    </h:commandButton>

    <h:panelGrid columns="1" id="outputId">
        <mc:example_result id="outputId1"
                           example_label="1. Java Frameworks hardcoded with 'f:selectItem': "
                           example_result="#{myBackingBean.displayItemValues()}"/>

        <mc:example_result id="outputId2"
                           example_label="2. Java Frameworks 2: "
                           example_result="#{myBackingBean.displayItemValues()}"/>

        <mc:example_result id="outputId3"
                           example_label="3. Java Frameworks 3: "
                           example_result="#{myBackingBean.displayItemValues()}"/>

        <mc:example_result id="outputId4"
                           example_label="4. Java Frameworks 4: "
                           example_result="#{myBackingBean.displayItemValues()}"/>

        <mc:example_result id="outputId5"
                           example_label="5. Java Frameworks 5: "
                           example_result="#{myBackingBean.displayItemValues()}"/>
    </h:panelGrid>
</h:form>

========== My Component: "example_result.xhtml" ==========
<ui:composition ...
    xmlns:mc="http://xmlns.jcp.org/jsf/composite/mc_components">

    <cc:interface>
        <cc:attribute name="example_label" type="java.lang.String" required="true"/>
        <cc:attribute name="example_result" type="java.lang.String" required="true"/>
    </cc:interface>

    <cc:implementation>

            <h:outputText value="#{cc.attrs.example_label}" .../>
            <h:outputText value="#{cc.attrs.example_result}" .../>

    </cc:implementation>
</ui:composition>

========== My BackingBean: "MyBackingBean.java" ==========
@org.springframework.stereotype.Component(value = "myBackingBean")
public class MyBackingBean implements Serializable {

    // Variables used in the "value" attribute of "HtmlSelectMany" components
    private String[] javaFrameworks2Values; // + Getters-Setters
    // All the others: javaFrameworks3Values, ...

    // The "HtmlSelects" components' "SelectItems" are generated by an array of "SelectItem"
    private SelectItem[] javaFrameworksSelectItems2; // +Getters
    // All the others: javaFrameworksSelectItems3, ...

    @PostConstruct
    protected void initLabelValueMapAndLabelValueArray() {

        // Pre-selected values of "HtmlSelectMany" components
        javaFrameworks2Values = new String[]{"Java Value", "Spring Framework Value"};

        // Initialization of the array of "SelectItem"
        javaFrameworksSelectItems2 = new SelectItem[4];
        javaFrameworksSelectItems2[0] = new SelectItem("Java Value", "Java Label");
        javaFrameworksSelectItems2[1] = new SelectItem("Spring Framework Value", "Spring Framework Label");
        javaFrameworksSelectItems2[2] = new SelectItem("Hibernate Value", "Hibernate Label");
        javaFrameworksSelectItems2[3] = new SelectItem("JSF Framework Value", "JSF Framework Label");

        // Initialization of all the others: javaFrameworks3Values, ..., javaFrameworksSelectItems3, ...
    }

    public String displayItemValues() {
        // return array of the result values;
    }

    public void resetValues() {
        // Reset the values to the initials
    }
}

A: After a lot of discussing with the only person who wanted to help to my issue here (and I thank him @WoAiNii for this a lot), I decided to post my solution:
I will make 5 different forms with 5 set of buttons (submit/reset), to make escalate this problem, for 5 so much related components in the form.
But my question is open:
Why this is happening, what rule in JSF in this case is taking place and makes this situation.
Anyone, who comes with an explanation, like:

*

*this is a rule in JSF, or

*is a JSF bug, or

*this happens in these cases, or... whatever...,

I will be glad to read it here so I will learn better, and others to will learn from these ideas of yours.
Thanks a lot


text:
Q: Convert string id of column to int autoincrement I have table Cars
Id nvarchar(25) PK
Name nvarchar(max)

And there is some records.
Id      Name
CodeXYZ Namezxc
CodeQAZ Nameasd
CodeEDC Nameqwe

I want to convert Id column to int autoincrement:
Id      Name
1 Namezxc
2 Nameasd
3 Nameqwe

but I have no idea how to make it :/
Could you help me ?

A: Create a new table (TBLB) that matches the table structure of the first table (TBLA) except create the second table with an int identity insert column for your ID column.
Then
INSERT INTO TBLB
(Name)
SELECT Name FROM TBLA
Make sure that you map the columns so that you aren't selecting or inserting the Id column.
Then you can drop the original table and rename the new table.
It's a bit painful but should get you what you want. You can even add a column to TBLB to keep the original id in a new column.

A: In SQL Server Management Studio, you can right click on the table, and modify it.
Once in there, select the column you want to auto increment.  You should be able to change it to an INT.
Then look at the column properties; one of them is IDENTITY, which is a unique and auto-incrementing field.  By turning that property on, and saving the changes, you get what you want.
If you have duplicates in that field though, or values that can't be cast to an INT, it will fail.  You would need to run an UPDATE on the table to get rid of any problems or duplicates first.
EDIT:
You made a comment "all the records are strings".  If the string values don't cast to an INT, you can't have waht you're asking for.  A field looking like "AAABC" can't be auto-incremented.

A: I don't know if it is possible with SQL Server but with MySQL you can use :
SET @tempVariable := 0;
UPDATE block SET id = (@tempVariable:=@tempVariable+1);

The idea is to initiate a variable that is incremented every time with the UPDATE.


text:
Q: Gambler's ruin: Probability heads exceed tails by $X$ or more as $N$ increases. I have a question similar to, but different from, the martingale problem.
Assume you are a gambler willing to bet, say, $10\%$ of whatever amount you start with on a fair coin toss.  Then, if at any time the number of tails (losses) exceeds the number of heads (wins) by $10$, you are out of the game.
It seems intuitive to me that as $N$ increases, the probability approaches $1.0$.
However, I don't know how to calculate the probability for any given $N$, say $10$ or $100$ or $1000$.  If, in addition to a formula, someone also knows how to build a Monte Carlo simulation in Excel, that would be excellent!  Thanks in advance for your insights and expertise.


text:
Q: Poor sample measurement and the Central Limit Theorem I have a fairly basic question about the Central Limit Theorem. I understand it in principle, but I like to know specifically what happens when there is poor measurement on the samples.
Say for example I have a large population which I sample in order to determine the population mean. In sampling I make a measurement on each sample which will have one of 3 outcomes. However, my measurement mechanism is very poor, and I only have a 40% chance of making a good measurement - the rest of the the time I have a random chance of incorrectly getting one of the other values.
Can the Central Limit Theorem be applied in this case? Any pointers to further reading on this situation would be appreciated.

A: You may want to look into the literature on randomized response. In this approach to asking confidential and sensitive survey questions, the interviewer asks the respondent to toss a coin and answer a sensitive question (e.g., "Do you use illicit drugs?") if heads come up, and an innocuous question (e.g., "Does your mother's birthday fall on an even-numbered day of the month?") if tails come up. That way, if the respondent says "Yes", the interviewer does not know whether they answered the mother question or the drug question, so it won't be as embarrassing or scary for the respondents to say "Yes". By working out the probabilities in a way similar to that in Dirk Horsten's answer, you can deduce the incidence of the sensitive behavior.
While there's a school of researchers following up and developing that technique, randomized response is rarely used in practice in large scale surveys, as both interviewers and respondents find it rather confusing, and lower literacy/numeracy respondents still don't understand how it protects their answers, and hence continue to underreport the sensitive behaviors.

A: Assuming the values you're getting are numeric, so that it makes sense to talk about averages, and if the resulting contaminated distribution still satisfies the conditions for some version of the CLT, that CLT should still apply -- in that appropriately standardized sample means will still go to a standard normal (in the limit as $n\to\infty$).
However beware -- the distribution that you use to standardize it will be the contaminated one, not the 'good' one; in some cases that may not be useful.

A: CLT relates your mean on a sample to the parameters of your observed variable. In this case that observed variable is your biassed measurement, not your underlying actual variable.
Name the three possible outcomes x1, x2 and x3.
Let r be your chance of correct measurement (in your case 0.4), so that both other outcomes have a chance of (1-r)/2
To estimate the distribution of your actual variable A, using your measured variable M, consider
P(M = xi) = sum over j (P(M = xi | A = xj) * P(A = xj))
= r * P(A = xi) + (1-r)/2 * sum for j not i P(A = xj)
= r * P(A = xi) + (1-r)/2 * (1 - P(A = xi))
= (1-r)/2 + (3r-1)/2 * P(A = xi)

In your case
P(M = xi) = 0.3 + 0.1 * P(A = xi)
E(M) = 0.3 * mean(x1, x2, x3) + 0.1 * E(A)

As the standard deviation of M is less than ´max(x1, x2, x3) - min(x1, x2, x3)´ , the average of n samples will converge to have the above average and a standard deviation of less than
(max(x1, x2, x3) - min(x1, x2, x3)) / sqrt(n)

From the above we also know
P(A = xi) = 2/(3r-1) * (P(M = xi) + (r-1)/2)
= 2/(3r-1) * P(M = xi) + (r-1) / (3r-1)

in your case
P(A = xi) = 10 * P(M = xi) - 3

So if 40% of your measurements give a certain outcome, the actual variable will have a probability of 100% to have that value and if 30% of your measurements  give a certain outcome, the actual variable will have a probability of 0% to have that value.


text:
Q: C, Do structs with multiple dynamically allocated arrays need to be resized for every allocation? Below I have a struct with multiple dynamically allocated char arrays.
It compiles, Valgrind indicates no issues and it functions as anticipated.
Earlier, someone tried to explain to me I may encounter memory issues down the road. Their reasoning was that one of the variables may exceed the contagious memory allocated for the foo instance.
Should I be performing a malloc on foo every time I allocate memory for its variables?
Live Demo
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct foo_t{
    char *strA;
    char *strB;
    char *strC;
    int x;
} foo;

int main() {

    char *str1 = "Hello World";
    char *str2 = "foo";
    char *str3 = "Kolmongorov complexity";

    foo *point = malloc(sizeof(foo));
    point->x = 100000;

    point->strA = calloc(strlen(str1)+1, sizeof(char));
    point->strB = calloc(strlen(str2)+1, sizeof(char));
    point->strC = calloc(strlen(str3)+1, sizeof(char));

    strcpy(point->strA, str1);
    strcpy(point->strB, str2);
    strcpy(point->strC, str3);

    free(point->strA);
    free(point->strB);
    free(point->strC);

    free(point);

    return 0;
}

A: In your example, the foo struct doesn't really contains the arrays : it contains pointers to arrays.
When arrays are resized, the size of pointers remains the same, so there's no need to reallocate the foo struct.
Just be aware that resizing an array with realloc may change its memory address, so pointers in foo struct will have to be reassigned according to that.

A:
Their reasoning was that one of the variables may exceed the contagious memory allocated for the foo instance.

That's nonsense, whoever told you as much didn't understand how allocation works. The struct only allocates the pointers, not what they point at. It will have the very same size, always. The pointers may point at memory allocated anywhere, not necessarily even on the heap.

Should I be performing a malloc on foo every time I allocate memory for its variables?

You need to allocate memory for it once, before accessing the pointer members. But in case the data pointed at by the pointer members are changed, then that doesn't affect the struct and it need not get reallocated.

A: I think memory management is one of the most important topic in C, but it's far more confusing than you may thought at first. This question can be a great entrypoint to illustrate it, so I will try my best to explain it in detail.
First consider the following three C struct definitions:
#define STR_SIZE 16

struct foo_A {
    char str1[STR_SIZE];
    char str2[STR_SIZE];
};

struct foo_B {
    char *str1;
    char *str2;
};

struct foo_C {
    char str1[STR_SIZE];
    char str2[];
};

Note that foo_C is legal, not a typo. What' their difference?
Well, let's consider foo_A and foo_B first. It looks like both of them try to describe and manage two strings. So for memory management, the first question you have to think is where the memory comes from.
In general there are two ways to get the memory, one is "I will allocate it by myself" and the other is "Someone else will allocate it, I just take it and manage". As you might guess, the former in-place style is foo_A, while the latter is foo_B.
More specifically, in C, you will use them in different styles(headers are omitted):
char str1[] = "I'm string A";
char str2[] = "I'm string B";

int main() {

    struct foo_A foo_A;
    struct foo_B foo_B;

    memset(&foo_A, 0, sizeof(struct foo_A));
    memset(&foo_B, 0, sizeof(struct foo_B));

    foo_B.str1 = (char *)malloc(sizeof(str1));
    foo_B.str2 = (char *)malloc(sizeof(str2));

    strcpy(foo_A.str1, str1);
    strcpy(foo_A.str2, str2);
    strcpy(foo_B.str1, str1);
    strcpy(foo_B.str2, str2);

    /*
        safely manipulate foo_B strings
        ...
    */

    free(foo_B.str1);
    free(foo_B.str2);
}

As you see, compared to foo_A's out-of-box usage, we have to deal with memory allocation before access foo_B's strings. If you omit these steps, the program just crashes.
What causes such difference, more formally, lies that foo_A itself contains the resource it is to manage, while foo_B doesn't. foo_B just contains a handle to the resource it is to manage, and before you use foo_B, you have to first do have a resource, and attach it to the handle. Of course the allocation/release of such resource is not the job of foo_B.
Before jump back to your reallocation confusion, another problem remains to deal with: management of management struct itself.
As you see, the code above doesn't allocate/free struct foo_A or struct foo_B besides some memset erasing. This is not always the case, while I choose this way to make the code clear and avoid introducing this problem too early.
Now consider the following two alternatives:
/*
    alternative_1.c

    str1, str2 remain the same
*/

struct foo_A foo_A;
struct foo_B foo_B;

int main() {

    foo_B.str1 = (char *)malloc(sizeof(str1));
    foo_B.str2 = (char *)malloc(sizeof(str2));

    strcpy(foo_A.str1, str1);
    strcpy(foo_A.str2, str2);
    strcpy(foo_B.str1, str1);
    strcpy(foo_B.str2, str2);

    /*
        safely manipulate foo_B strings
        ...
    */

    free(foo_B.str1);
    free(foo_B.str2);
}

/*
    alternative_2.c

    str1, str2 remain the same
*/
int main() {

    struct foo_A *foo_A = (struct foo_A *)malloc(sizeof(struct foo_A));
    struct foo_B *foo_B = (struct foo_B *)malloc(sizeof(struct foo_B));

    memset(foo_A, 0, sizeof(struct foo_A));
    memset(foo_B, 0, sizeof(struct foo_B));

    foo_B->str1 = (char *)malloc(sizeof(str1));
    foo_B->str2 = (char *)malloc(sizeof(str2));

    strcpy(foo_A->str1, str1);
    strcpy(foo_A->str2, str2);
    strcpy(foo_B->str1, str1);
    strcpy(foo_B->str2, str2);

    /*
        safely manipulate foo_B strings
        ...
    */

    /* free managed string */
    free(foo_B->str1);
    free(foo_B->str2);

    /* free management struct itself */
    free(foo_A)
    free(foo_B)
}

As you see, the way we get foo_A and foo_B varies. In the very first example, we define them within function body, which means they are automatically allocated on stack(case 1). In alternative_1.c, we define them as static variable whose space is allocated at compile time(case 2), while in alternative_2.c they are allocated on heap by malloc(case 3).
No matter how you get foo_A and foo_B, the key point is the same as before:  you have to first do get a it. And manage them. You can free them manually(case 3), or relying on automatic varialbe reclaim(case 1), or at process exiting(case 2).
After all these discussions, you may find that the management of resource(e.g. string) and the management of management resource(e.g. foo_A or foo_B) are independent. So if your resouce changed like, just as you say, the string is resized by reallocation, you don't have to reallocate your management resource(i.e. foo_X). That' s it.
Remember there is still a struct foo_C? Before talking about it I want to first discuss why you may choose struct foo_A or struct foo_B.
It turns out that foo_A cannot manage variable-length strings, but just fix-length strings(in our example < 15). If you know the strings foo_A will manage never exceed a fixed small size, you may choose such style, otherwise you choose style like foo_B.
foo_C can be regarded as a mixture of both, variable-length but in-place allocation. It can be used as following:
/*
    foo_C.c

    str1, str2 remain the same
*/
#define BUF_SIZE 1024

int main() {

    struct foo_C *foo_C = (struct foo_C *)malloc(BUF_SIZE);

    memset(foo_C, 0, BUF_SIZE);

    strcpy(foo_C->str1, str1);
    strcpy(foo_C->str2, str2);

    /*
        safely manipulate foo_C strings
        ...
    */

    free(foo_C);
}

You get foo_C from malloc rather than define it on stack or as static variable, so as to make foo_C of variable size. You access strings of foo_C directly without first allocating space for them. A key difference between foo_C and foo_A is that, str2 of the former can be of variable length, while that of the latter is fixed. As for variable-length, foo_C is also differnt from foo_B. For foo_C, the variable string space is always allocated with foo_C, while for foo_B, it can be allocated anywhere on heap and you must attach it manually.
Note if you just define foo_C on stack or as static variable, then str2 of it looks like non-existent. That is, sizeof(struct foo_C) equals STR_SIZE. You should never access str2, which may behaves like array out-of-bound.
As far as I know, only kernel code which manages slab allocator makes use of such hack.


text:
Q: Setting Memory Breakpoints in Eclipse How do you set memory breakpoints in Eclipse?  That is, I would like to set a conditional breakpoint that triggers when the data at a given memory location changes.
This question has been asked before, but the only provided answer doesn't address the question and is essentially the same information that can be found in the Eclipse Online help.
What I am looking for is more detailed information (or an example would be good) for setting a conditional breakpoint in Eclipse that will trigger when the data at a specific memory address changes.

A: Solution that works:
 1/ Select the variable representing the pointer you want to break on in a given context in the "Variables" tab
 2/ Right click, then select "Add Watchpoint (C/C++)
 3/ In the field "Expression to watch", just replace the name of the variable by the memory address to break on.

A: You need to use a watchpoint. From the page:

*

*Highlight the variable in the editor, or select it in the Outline
view.

*Click Run > Toggle Watchpoint.

*Do any of the following:

*

*To stop execution when the watch expression is read, select the Read check box.

*To stop execution when the watch expression is written to, select the Write check box.

*The watchpoint appears in the Breakpoints view list.

A: Using a Watchpoint in Eclipse Oxygen:

*

*In the Expressions view (Window > Show View > Expressions), add an Expression such as:  *(uint8_t*)0x231cc528.  The cast tells Eclipse the memory location size.

*Right-click the added expression and select "Add Watchpoint".

*The resulting Watchpoint may be edited and controlled in the "Breakpoints" view.

*It may be important to edit the Watchpoint.  If you want to e.g. detect changes done by other threads:  right-click the Watchpoint in the "Breakpoints" view, select Breakpoint Properties... > Filter, UN-check "Restrict to Selected Processes and Threads"


text:
Q: I get a NON Error when I get the date from hidden input but when I input the date manually I get the time working, what could be the problem I get a NON Error when I get the date from hidden input but when I input the date manually I get the time working, what could be the problem:
<input type="hidden" name="counter_value" id="counter_value" value="2019/9/10">


text:
Q: MongoDB returning null value for keys in uppercase I am trying to fetch response from MongoDB collection in java spring boot.
Below is the sample record:-
{
        "_id" : ObjectId("5c86193efa093d1b8d9ca3fe"),
        "name" : "name",
        "UPPERCASENAME" : "NAMEINUPPERCASE"
}

Below is the model class:-
public class modelClass {
    private String name;
    private String UPPERCASENAME;

    public String getName() {
        return name;
    }

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

    public String getUPPERCASENAME() {
        return UPPERCASENAME;
    }

    public void setUPPERCASENAME(String UPPERCASENAME) {
        this.UPPERCASENAME = UPPERCASENAME;
    }
}

And below is the query:-
public List<modelClass> getResponse(){
  return collection.find().into(new ArrayList<>());
}

Below is the response on making an api call to the database:-
[
    {
        "name": "name",
        "uppercasename": null
    }
]

When I logged the document response I was able to fetch all the records correctly from DB
{"timestamp":"2021-03-10T21:03:29,483Z","level":"INFO","thread":"boundedElastic-1","message":":::Document Document{{_id=5c87868efa093d1b8d9ca415, UPPERCASENAME= NAMEINUPPERCASE, name=name}}"}

It seems that query is returning correct values, and somehow the data is not getting mapped correctly with the model object because of case sensitive issue.
So as you can see from the api response I was able to fetch the value for key 'name' since it was in lowercase, but was not able to fetch value for key 'UPPERCASENAME' which is in uppercase. Also in the response magically 'UPPERCASENAME' has changed to 'uppercasename'.
Can someone please help me to understand the root cause of the issue, and also a possible solution for the same?
Any help will be appreciated.
PS:- I am new to mongoDB, so please understand my situation if I am missing something basic.

A: Change the variable name to camel case.
so change:
private String UPPERCASENAME;

to:
private String uppercaseName;

Then it should get parsed correctly


text:
Q: C# Multiple conditions To put it simply I would like to know if there is a way I can have multiple conditions to trigger a if statement.
To add to that the program I am working on will be for toner cartridge inventory management, and I want it to send an e-mail if our reserves of a particular colour is low. The code to send a e-mail is quite long to I want to avoid doing it in 4 different statements, such as:
if (k toner is low)
{
send mail
}

else if (C toner is low)
{
send mail
}

else if (M toner is low)
{
send mail
}

else if (Y toner is low)
{
send mail
}

so what I basically want is:
if (K or C or Y or M toner is low)
{
Send mail
}

Any ideas on the best way to do this?

A: Yup, you're just looking for the || (conditional-OR) operator:
if (kTonerIsLow || cTonerIsLow || ...)
{
    SendEmail();
}

Note that the operator is short-circuiting - so if kTonerIsLow is true, it won't evaluate cTonerIsLow, etc. If you use | instead, it will still work - but it will evaluate both operands unconditionally.
Additionally, this comment struck me:

The code to send a e-mail is quite long to I want to avoid doing it in 4 different statements

That suggests you should probably pull it out into a separate method anyway.

A: @Habib, @Jon
|| Operator change business logic here. Lets assume that You want to send email when more than one toner is low, using || You will only send email with information than only one of the toners is low whether other toners are in same the same condition.
To solve this problem You can send information about all toners in one email
-or-
Create array of toners and then iterate through them checking if one of them is low:
foreach(toner in Toners)
{
  if (toner.IsLow)
     SendEmail(toner);
}

A: Building on dzaba's idea of an list of Printers:
 var printers = new Printer[] {...};
 if (printers.Any(p=>p.Toner.IsLow))
      sendEmail();

A: Use the following format to solve your problem:
if (K is low || C is low || Y is low || M is low)
{
    Send mail
}


text:
Q: property_exists doesn't work on class property which is generated dynamically I have the following PHP class, which its properties is generated dynamically during running time.
<?php

class ParamEx
{
    private $params = array();

    public function __get($name) {
        return $this->params[$name];
    }

    public function __set($name, $value) {
        $this->params[$name] = $value;
    }
};

$paramEx = new ParamEx();
$property = "dummy_property";
$paramEx->$property = "123";

// "123" printed
echo $paramEx->$property . "\n";

// Nothing printed
echo property_exists($paramEx, $property) . "\n";

I realize property_exists doesn't work for such case.
Is there any way I can make it work?

A: If I were you, I'd add a public method to this class like this:
public function propertyExists($property) { return property_exists($this, $property) || isset($this->params[$property]); }

If you have a lot of classes like this (and you're using php 5.4 or better), you might want to consider doing this function as a Trait which you can use in all of those classes.

A: You could overload __isset and use isset($paramEx->$property) since you're already overloading __get and __set:
class ParamEx
{
    private $params = array();

    public function __get($name) {
        return $this->params[$name];
    }

    public function __set($name, $value) {
        $this->params[$name] = $value;
    }

    public function __isset($name) {
        return isset($this->params[$name]);
    }
};

Then use:
echo isset($paramEx->$property) . "\n";

instead of:
// Nothing printed
echo property_exists($paramEx, $property) . "\n";


text:
Q: Is there a way to get all elements in a JList? I was wondering if there is a way to retrieve a list of all the elements that have been added to a JList. For example I would like JList to return an array or list of Strings or JLabels from a custom cell renderer.

A: Yes of course. You getElementAt() with a loop.
Example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class Jlist {
    JFrame frame;
    JList<String> list;
    JButton button;

    public Jlist(){
        init();
    }

    public void init(){
        frame = new JFrame("Sample");
        frame.setSize(300, 300);
        frame.setLayout(new  BorderLayout(30, 30));

        DefaultListModel<String> model = new DefaultListModel<>();
        model.addElement("A");
        model.addElement("B");
        model.addElement("C");
        model.addElement("D");
        model.addElement("E");

        list = new JList<>();

        list.setModel(model);
        JScrollPane pane = new JScrollPane(list);
        pane.setViewportView(list);

        button = new JButton("Get");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                buttonActionPerformed();
            }
        });

        frame.add(pane, BorderLayout.NORTH);
        frame.add(button, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public void buttonActionPerformed(){
        for(int i = 0; i< list.getModel().getSize();i++){
            System.out.println(list.getModel().getElementAt(i));
        }
    }
    public static void main(String[] args) {
        new Jlist();
    }
}

A: You can use getModel method to get ListModel. And then use getElementAt and getSize method to build array or list or whatever you want.

A: try this...
 String[] myArray = new String[50];
    for (int i = 0; i < jList1.getModel().getSize(); i++) {
             myArray[i] = String.valueOf(jList1.getModel().getElementAt(i));
        }

A: I haven't seen anyone use the most concise way to do it. Assuming you're using Java 8+:
IntStream.range(0,listModel.size()).mapToObj(listModel::get).collect(Collectors.toList());

I personally prefer it to any of the loop methods.

A: Also we can get elements from JList (named ) myL using Message dialog,  so you can use folowing method to make action perform to JButton object.
String item = myL.getSelectedValue();
if( item == null ){
    JOptionPane.showMessageDialog(null,  "Not selected yet");
}else{
    JOptionPane.showMessageDialog(null, item);
}


text:
Q: Raw resource file type How do you detect what kind of file the resource is? In my case there could be videos and images.
So in case it's a video, I use a VideoView; and in the case of an image, I use an ImageView?
I'm getting the resource id like this:
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resourceID);

A: the only thing I have in mind is that you can check the file names using constants like this:
 final String type = getApplicationContext().getResources().getResourceTypeName(resID);
 if(type.equals("drawable")){
   // handle it like an image
 }else if(.....) //do some research for other constants

A: I think it's impossible without reading/ analyzing the binary data of files (like TrID). The easiest way is to prefix file names with predefined strings. For example:

*

*video_file_00, video_file_01…

*image_file_00, image_file_01…

Then you can use getResourceName(int) to parse the file names.


text:
Q: run powershell script before entrypoint This is the parent dockerfile im working with: https://github.com/Microsoft/aspnet-docker/blob/master/4.7.1-windowsservercore-1709/runtime/Dockerfile
When the container is started with "docker run" I need to run a PS script before the entrypoint executes, how is this possible?
the entrypoint in the parent dockerfile is: ENTRYPOINT ["C:\\ServiceMonitor.exe", "w3svc"]

I want that to behave as usually just execute a ps script first.
I have overwritten the entrypoint with a PS script:
ENTRYPOINT ["powershell", "C:/myscript.ps1"]
myscript.ps1
.... does some stuff ....
# executes the command to start up like the parent container did
C:/ServiceMonitor.exe w3svc

Running this script seems to work fine, but are there any gotchas? How can I pass arguments to the entrypoint now?


text:
Q: How can I prevent foreign changes to my Windows 10 "Group Policies" by firewall rules? Specifically, I would like to use the Windows 10 firewall to block changes to Group Policy from sources other than me.
My computer is not for corporate use, not for use on corporate networks. I do not want to see another ActiveSync Policy Broker popup.
If I want to make changes to my computer's security and related policies, I'll do it myself. I don't want others participating in administrating my machine.
I want to be able to continue to use (personal) Office365.

*

*The Group Policy Client service cannot be disabled as far as I can see.

*I have renamed C:\Windows\System32\gpupdate as some have suggested, and it hasn't stopped the popups.

I've seen lots of discussion on this subject, but no concrete facts about how to remove or disable it. Period.

A: I have a partial answer to (1) part is there a firewall formula... ?
UNTESTED
I found several docs on the web that purport to provide port usage information for ActiveSync. I can't vouch for their accuracy or completeness at this time.
I also went out and bought a managed switch for IGMP snooping so I can monitor traffic to determine the effectiveness of filters based on this information.
Here is a digest of what I've found:
Microsoft ActiveSync uses the following applications for the communication:
* Wcesmgr.exe
* Wcescomm.exe
* Rapimgr.exe
Microsoft ActiveSync uses the following ports for the communication:
1. Inbound TCP:
    * 990
    * 999
    * 5678
    * 5721
    * 26675
2. Inbound UDP:
    * 2883
3. Outbound UDP:
    * 5679


text:
Q: Very strange GRANT permission issue I am having a very strange issue here with a web app that I have seen working fine in the past.
The server is a simple LAMP stack running MySQL 5.6.30.
SQLSTATE[HY000] [1045] Access denied for user 'my_user'@'localhost' (using password: YES)
The reason why this issue is causing me problems is because the user my_user has all privileges.
Here is the output of the SHOW GRANTS query on my MySQL server:
mysql> SHOW GRANTS FOR 'my_user'@'localhost';
+---------------------------------------------------------------
| Grants for my_user@localhost
+---------------------------------------------------------------
| GRANT USAGE ON *.* TO 'my_user'@'localhost' IDENTIFIED BY PASSWORD '******'
| GRANT ALL PRIVILEGES ON `db1`.* TO 'my_user'@'localhost'
| GRANT ALL PRIVILEGES ON `db2`.* TO 'my_user'@'localhost'
| GRANT ALL PRIVILEGES ON `db3`.* TO 'my_user'@'localhost'
| GRANT ALL PRIVILEGES ON `db4`.* TO 'my_user'@'localhost'
| GRANT ALL PRIVILEGES ON `my_db`.* TO 'my_user'@'localhost'
+---------------------------------------------------------------
6 rows in set (0.00 sec)

The database called my_db is the Database in question for this web app.
Does anyone have any suggestions on how I should go about diagnosing this issue?
I have confirmed that I am indeed looking at the right server with the correct user and what should be the correct password.
I am also unable to log in to MySQL CLI with this user.

A: SOLUTION:
Somehow the password for that user got modified/blasted. By resetting the password I have regained access.

A: It seems the combination of host, user name and password is not allowed to connect to the server, please verify the permission tables (reload grants if required) on the server. You may also restart MySQL service once.


text:
Q: Save editable div-tag content into an object? I have an editable div-tag where i dynamically create paragraphs. I want to save that div-tags content on button click. Is that possible?

A: I would use jquery for that
$('.btnClick').on('click', function(){
    var content = $('#RiskScoreTextArea').html();
});

If you wanted the text of the div you can use .text() but html will return the full contents of the div.  Hopefully this will work for you.


text:
Q: Types in a sum of a matrix's elements in C I wrote a little program to do the sum of a matrix's elements and I noticed it works when most types are int and it doesn't when most types are unsigned char, but I don't get why.
By "working" I mean "gives the correct result", actually they both compile with no errors and no warnings (even with the -Wall command), but the "not working" code just gives a different random number as a result everytime I run it (in the unsigned char range).
This is the code that works:
#include <stdio.h>

typedef unsigned char uchar;

int matrix_sum ();

int main (void)
{

  printf ("\nSum of a matrix's elements in a function out of the main function\n\n");

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

  int sum = matrix_sum (2, 3, mat);

  printf ("Sum of matrix is: %d\n\n", sum);

  return 0;

}

int matrix_sum (int row, int col, int mat [row] [col])
{

  int sum = 0;

  for (uchar i = 0; i < row; ++i)
    for (uchar j = 0; j < col; ++j)
      sum += mat [i] [j];

  return sum;

}

This is the code that doesn't work:
#include <stdio.h>

typedef unsigned char uchar;

uchar matrix_sum ();

int main (void)
{

  printf ("\nSum of a matrix's elements in a function out of the main function\n\n");

  uchar mat [2] [3] = { {4, 5, 0} , {1, 2, 3} };

  uchar sum = matrix_sum (2, 3, mat);

  printf ("Sum of matrix is: %d\n\n", sum);

  return 0;

}

uchar matrix_sum (int row, int col, int mat [row] [col])
{

  uchar sum = 0;

  for (uchar i = 0; i < row; ++i)
    for (uchar j = 0; j < col; ++j)
      sum += mat [i] [j];

  return sum;

}

What rule on types did I miss?

A: The passed array is uchar[2][3], but the array in the argument is int[2][3]. Here you passed different things, so it worked incorrectly.
You have two choice and should do just one of that:

*

*Change the array to pass uchar mat [2] [3] to int mat [2] [3] to match the function argument.

*Change the function argument int mat [row] [col] to uchar mat [row] [col] to match the passed thing.

A: In your second code that doesn't work
#include <stdio.h>

typedef unsigned char uchar;

uchar matrix_sum ();

int main (void)
{

  printf ("\nSum of a matrix's elements in a function out of the main function\n\n");

  //data type is uchar
  uchar mat [2] [3] = { {4, 5, 0} , {1, 2, 3} };

  //data type is uchar
  uchar sum = matrix_sum (2, 3, mat);

  printf ("Sum of matrix is: %d\n\n", sum);

  return 0;

}

//data type is uchar                data type is int
uchar matrix_sum (int row, int col, int mat [row] [col])
//here is the reason of mismatch of the data type
{

  uchar sum = 0;

  for (uchar i = 0; i < row; ++i)
    for (uchar j = 0; j < col; ++j)
      sum += mat [i] [j];

  return sum;

}

Thus you just need to go to the uchar matrix_sum() function and change the data type of matrix from int to uchar.


text:
Q: Draw youtube in html5 canvas It's a follow-up question to Detect play event in youtube wrapped via MediaElement.js. I tried to detect play or click event in the question but can't do it because of cross-origin issue (maybe). I also found that you draw the youtube clip directly to canvas, it will not be copied (will be blank), like this:
<!DOCTYPE html>
<html>
<head>
  <title>video in canvas</title>
  <link rel="stylesheet" href="mediaelementplayer.css" />

  <script src="jquery.js"></script>
  <script src="mediaelement-and-player.min.js"></script>

  <script>
  $(document).ready( function() {
    $('#v').mediaelementplayer();

    var v = $('#v')[0];
    var canvas = $('#c')[0];
    var context = canvas.getContext('2d');

    console.log('play event entered');
    draw(v, context, 640, 360);
  });

  function draw(v, c, w, h) {
    // if(v.paused || v.ended)  return false;
    console.log("draw event entered");
    c.drawImage(v, 0, 0, w, h);
    setTimeout(draw, 20, v, c, w, h);
  }
  </script>
</head>

<body>
  <video width="640" height="360" id="v" preload="none">
    <source type="video/youtube" src="http://www.youtube.com/watch?v=nOEw9iiopwI"/>
  </video>
  <canvas id="c" width="640" height="360"></canvas>
</body>
</html>

Anybody knows other more promising approach to draw youtube stream in canvas? Thanks.

A: You cannot use canvas drawImage to draw <video> or <img> coming from a different domain.
Maybe you could proxy Youtube streams through your server, but that probably goes against Youtube TOS


text:
Q: Unable to locate the specified class: Model.php codeigniter phpstorm I am trying to add phpstorm autocomplete for codeigniter as seen in different quesiton.
The link provided: https://github.com/topdown/phpStorm-CC-Helpers
I commented out the specified files and added
* @property Test_model      $test_model

to my_models.php
When I try to load Test_model.php from my controller using:
$this->load->model('Test_model');

I get:

'Unable to locate the specified class: Model.php'

If I remove the load row and try:
$this->Test_model->insert_entry()

I get:

Message: Undefined property: Test::$Test_model

Test.php:
class Test extends CI_Controller {
  public function __construct(){
        parent::__construct();
  }
  public function modelTutorial(){
    $this->Test_model->insert_entry();
 }

Test_model.php
class Test_model extends CI_Model{

  public function __construct(){
      parent::__construct();
  }

  public function insert_entry(){
      die('asdasd');
  }
}

A: When creating models, you need to place the file in application/models/ and name the file in all lowercase - like yourfile_model.php
Change your file name from Test_model to test_model.php and call it on controller constructor
public function __construct(){
        parent::__construct();
        $this->load->model('test_model');
  }

Read manual Models


text:
Q: My python module does not see other modules I have a folder with 2 files.
import_test.py
main.py.

Here is content of import_test.py:
def some_function():
        df = pd.DataFrame({'col_1': [1,2,3],
                       'col_2': [1,2,3]})
        return df

Here is content of main.py:
import import_test
import pandas as pd
import importlib
importlib.reload(import_test)

import_test.some_function()

When I execute import_test.some_function(), I get back the following error:
NameError: name 'pd' is not defined

I guess I can solve this problem by adding import pandas as pd in my import_test.py file, but this seems redundant to me, since main.py already has the import statement for pandas. Is there way to avoid the redundancy?

A: You have to import modules where they are being used. When you use the import keyword, whatever you import is being bound to the current module's global namespace.
So it's not really a matter of your modules being unable to see each other, more that you've imported pandas in the wrong location. You can remove the pandas import from your main module if you import it where it's being used.
For what it's worth, C.Nivs is correct in saying that the module loader will only load pandas once even if you import it multiple times, so redundancy isn't much of an issue in that regard.

A: You can try passing pd into the function, and then supply pd to the function when calling it.
import_test.py:
def some_function(pd):
        df = pd.DataFrame({'col_1': [1,2,3],
                       'col_2': [1,2,3]})
        return df

main.py
import import_test
import pandas as pd
import importlib
importlib.reload(import_test)

import_test.some_function(pd)


text:
Q: css - How to prevent to "splitting" div on PDF generating I'm generating PDF with dynamic fields, e.g. textarea.
At this moment I'm using:
    .div__break {
        page-break-inside: avoid;
    }

To prevent splitting this DIV but it's not working and I still see this (content is hiding under header-html):

I'm using WKHTMLTOPDF with Laravel. What can I do to fix this?

A: Perhaps you have an other element with page-break-inside: avoid.
Probably you can use
page-break-inside: avoid !important;

instead of
page-break-inside: avoid


text:
Q: $\sup_{x,y}\frac{|f(x)-f(y)|}{|x-y|} = \sup_x \|D_f(x)\|$ Let $B \subset \mathbb R^n$ be an open ball, $f:B \to \mathbb R^n$ differentiable.
Show that $\sup_{x,y \in B, x\neq y}\frac{|f(x)-f(y)|}{|x-y|} = \sup_{x \in B}\|D_f(x)\|$
What I did:
$\sup_{x \in B}\|D_f(x)\| = \sup_{x \in B} \sup_{|v| = 1}|D_f(x)v| = \sup_{x \in B, |v| = 1}|D_f(x)v| = \sup_{x \in B, |v|=1} |\lim_{t \to 0} \frac{f(x+tv)-f(x)}{t}| = \sup_{x \in B, |v|=1} \lim_{t \to 0} \frac{|f(x+tv)-f(x)|}{|t|}$
And here I am stuck.
If we could somehow magically get rid of the limit, we would be left with something that looks a lot like what we want to show, but how do we do that?

A: The inequality
$$
\sup\limits_{x, y \in B,\ x \ne y} \frac{\lvert f(x) - f(y) \lvert}{\lvert x - y\rvert} \le \sup\limits_{x \in B}\, \lVert D_f(x) \rVert
$$
follows from (indeed, is almost the precise statement) of Theorem 11 on p. 277 of:  C. C. Pugh, Real Mathematical Analysis, Springer, 2002 (the proof rests on an application of the one-dimensional MVT to the function $g(t) = \langle u, f(y + t (x - y) \rangle$, where $u \in \mathbb{R}^n$ is any unit vector).
The second inequality is straightforward.


text:
Q: FB.login pop up is blocked when page on load I'm facing an issue when calling FB.login when page on load, the FB.login pop up is block by the browser. Currently I know I've to call FB.login after a user click event but I've to do it this way due to the business logic from client.
FB.api('/me/permissions', function(response2) {
    var permsArray = response2.data[0];
    var permsNeeded = ["user_events"];

    var permsToPrompt = [];
    for (var i in permsNeeded) {
       if (permsArray[permsNeeded[i]] == null) {
        permsToPrompt.push(permsNeeded[i]);
      }
    }

    if (permsToPrompt.length > 0) {
      promptForPerms(permsToPrompt);
    }
});

var promptForPerms = function(perms) {
    FB.login(function(response) {
    }, {scope: perms.join(',')});
};

Is there any solution to call FB.login() without user click event? Or is there any tweak for this? Appreciate for the help.

A: You're not going to be able to code your way around the popup blocker, unfortunately.
The way to solve this is by redirecting the user to the Facebook permissions dialog when the page loads as described in the docs for manually building a login flow.
You first need to detect if the user is authenticated / connected with your application already and only redirect if they are not connected. This is best done in the window.fbAsyncInit function like this:
window.fbAsyncInit = function() {

    var myAppID = 'YOUR APPLICATION ID';

    FB.init({ appId: myAppID });

    FB.getLoginStatus(function(response) {
        if ('connected' != response.status) {
            window.location.href = 'https://www.facebook.com/dialog/oauth' +
                '?client_id=' + myAppID +
                '&scope=user_events' +
                '&redirect_uri=' + encodeURIComponent(document.URL);
        } else {
            alert('welcome to my app');
        }
    });

};

The other option is to adjust your user journey slightly; perhaps if the user is not connected then you could display an overlay with a message asking them to authenticate and a button which when clicked calls FB.login.


text:
Q: Regex for parsing Wikipedia templates I'm developing a tool for Wikipedia, and I'm at a point in which I need to extract the parameter names and values out of the wikitext of templates, such as the following:
|param1=value1 |param2=value2 |param3=value3

This would be easy enough, but there are two complications. First, there may be spaces and line breaks:
|param1=value1
| param2 = value 2
|   param3  =  value  3

And second, there may be pipes | inside the parameter values! Like so:
|param1=value1
|param2 = [[value2|val2]]
|param3  =  [[ value3 | val3 ]]

The expected result would be an array mapping keys to values, like so:
$result = [
    'param1' => 'value1',
    'param2' => '[[value2|val2]]',
    'param3' => '[[ value3 | val3 ]]',
];

I'm afraid this level of regex mastery is beyond my current skill. Can anyone see the solution? Thanks!

A: You can use already existing libraries like mwclient (https://github.com/mwclient/mwclient) and mwparserfromhell (https://github.com/earwig/mwparserfromhell) to achieve this.
For example code below will extract templates & their parameters from https://en.wikipedia.org/wiki/Test page:
import mwclient
import mwparserfromhell

wiki = mwclient.Site(('https','en.wikipedia.org'), '/w/')
page = wiki.Pages['Test']
text = page.text()
wikicode = mwparserfromhell.parse(text)
templates = wikicode.filter_templates()
for template in templates:
  print "Found template %s" % template.name
  for param in template.params:
     print "\tFound param %s with value %s" % (param.name, param.value)

You will see something like:
Found template SampleTemplate
  Found param1 with value value1
  Found param2 with value value2
  Found param3 with value value3
...

A: input = `|param1=value1
|param2 = [[value2|val2]]
|param3  =  [[ value3 | val3 ]]`

var output = input.replace(/[\s\n]*/g,'').match(/\w+=(\[\[.+?\]\]|\w+)/g).map(item => {
    var pairs = item.split('=');
    pairs[1] = pairs[1].match(/\w+/g);
    return {
        key: pairs[0],
        values: pairs[1]
    }
});
/* output:

    [
      {
        "key": "param1",
        "values": [
          "value1"
        ]
      },
      {
        "key": "param2",
        "values": [
          "value2",
          "val2"
        ]
      },
      {
        "key": "param3",
        "values": [
          "value3",
          "val3"
        ]
      }
    ]
*/

A: from what i understood, the solution would be this. It will work only if the parameters name or values do not contain = character.
      var str = "|param1=value1
                |param2 = [[value2|val2]]
                |param3  =  [[ value3 | val3 ]]";
      //Delete line break and spaces
      var splited = str.split(/\=/), len = splited.length, result = [];
      var for(var i = 0; i < len; i++){
         result.push({param:splited[1], value:splited[i+1]});
       }

       //result = [{param:param1, value:value1}, {param:param2, value:value2} ...]


text:
Q: How to add an object to a NSMutableArray that is stored in a CoreData iOS database? I have an NSManagedObject subclass where absences is an NSMutableArray
@interface Record : NSManagedObject
@property (nonatomic, retain) id absences;
@end

I want to be able to add items to the absences array; however, if I do [myRecord.absences addObject:SomeObj the record does not save properly.  It almost appears that the NSManagedObject does not know that I updated the absences array.
Nevertheless, if I add SomeObj to some localAray, then set myRecord.absences = localArray, the NSManagedObject saves correctly.
Can someone explain this behaviour and how I might avoid it...thanks

A: You're exactly right, in the first case you're changing an object outside of NSManagedObject field of view. To solve this, Apple doc says the following

For mutable values, you should either transfer ownership of the value to Core Data, or implement custom accessor methods to always perform a copy.

So declaring your property with (copy) should suffice.


text:
Q: ffmpeg hangs when using -fflags +genpts I'm trying to remux a .vob file (which I got using vobcopy) into a mp4 container (mkv would do it as well) using ffmpeg 4.2.4-ubuntu0.1.
Initially the remuxing finished, but I got these errors:
[mp4 @ 0x560f9a37e5c0] Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly

and several thousand times
[mp4 @ 0x560f9a37e5c0] pts has no value

So I tried fixing it using -fflags +genpts:
ffmpeg -fflags +genpts -i 'video.vob' -c copy 'video.mp4'

After processing around 90000 frames ffmpeg gets somehow stuck (but the CPU keeps running on 100%) and can only terminated using kill combined with Ctrl+C.
I tried it with an other .vob file and ffmpeg hanged this time at an other point.

When creating the full debug log I noticed that after the program was aborted the output always shows the same last edited frame (92775). Here you can view it: https://paste.ubuntu.com/p/tbhMmpQwff/

A: I fixed the problem by adding the +igndts flag:
ffmpeg -fflags +genpts+igndts -i 'video.vob' -c copy 'video.mp4'

It resulted in some error messages at the point where ffmpeg hung up earlier, but the created video file was fine.
[mp4 @ 0x56482f355a00] Invalid DTS: 333993600 PTS: 0 in output stream 0:0, replacing by guess
[mp4 @ 0x56482f355a00] Non-monotonous DTS in output stream 0:0; previous: 334018800, current: 334018800; changing to 334018801. This may result in incorrect timestamps in the output file.

I'm not sure what caused the problem and what +igndts does to fix it, but I'm happy that it works.


text:
Q: How to extract all the column name from the required table by Excel(or maybe python) Now I have table1 as below:

A
B
C

First
Second
Second

Second
Third
Forth

I now want to output a list(The first column has already known):

First
A

Second
A
B
C

Thrid
B

Forth
C

How can I output this using Excel(or maybe python, if much easier)?

A: This can be done with Python and the openpyxl package. The code below reads an existing spreadsheet table1.xlsx, and creates a new spreadsheet table1_columns.xlsx listing the unique values and the columns they were found in. With your input, the code produces your output.
import os
from collections import defaultdict
import openpyxl

input_filename = r"table1.xlsx"
output_filename = r"table1_columns.xlsx"

# Read the input spreadsheet file
wb = openpyxl.load_workbook(input_filename)

# Use the first spreadsheet in the workbook
ws = wb.worksheets[0]

# Iterate over every cell in each column, and read the values into a dict
# which has a default value of an empty set.
# The keys are the cell values, e.g. "First"
# The values are sets of column letters the cell value was found in, e.g. {"A"}
values = defaultdict(set)
for cells in ws.iter_cols():
    for cell in cells:
        values[cell.value].add(cell.column_letter)

# Create a new spreadsheet
wb = openpyxl.Workbook()
ws = wb.active

# Iterate over the dict, writing each value and its column letters to a new row
for row_num, (value, column_letters) in enumerate(values.items(), start=1):
    # The first column is always the value, e.g. "First"
    ws.cell(row=row_num, column=1).value = value

    # As sets are an unordered data type, it first needs to be sorted. If not,
    # the second row could be "Second B A C" instead of "Second A B C"
    column_letters = sorted(column_letters)
    for column_num, column_letter in enumerate(column_letters, start=2):
        ws.cell(row=row_num, column=column_num).value = column_letter

# Save the spreadsheet to disk
wb.save(output_filename)

# Launch the new spreadsheet
os.startfile(output_filename)

A: While I prefer GordonAitchJay's answer as it uses an existing library, most (if not all) spreadsheet editors can export sheets in .csv format (comma-separated values). From there you could read the first line containing the column names, and split on commas.
Off the top of my head it should look something like this:
columnNames = None
with open(filePath, "r", encoding="utf-8") as contents:
    columnNames = contents.getlines()[0].split(",")    # Or maybe "readlines()"

# Do your magic.


text:
Q: Каким образом необходимо внедрить Hibernate Session Factory в Spring MVC? Необходимо реализовать CRUD операции с БД MySQL. Использую Repository для доступа у данным.
 private SessionFactory sessionFactory;

public void setSessionFactory(final SessionFactory sf) {
    sessionFactory = sf;
}

@Override
public void insert(final ClientEntity object) {
    Session session = sessionFactory.getCurrentSession();
    session.persist(object);
    clientLog.info("Insert " + object);
}

@Override
public void update(final ClientEntity object) {
    Session session = sessionFactory.getCurrentSession();
    session.update(object);
    clientLog.info("Update " + object);
}

@Override
public void remove(final long id) {
    Session session = sessionFactory.getCurrentSession();
    ClientEntity client = session.load(ClientEntity.class, id);
    if (client != null) {
        session.delete(client);
    }
    clientLog.info("Delete " + client);
}

@SuppressWarnings("unchecked")
@Override
public List<ClientEntity> readAll() {
    final String query = "select p from"
            + ClientEntity.class.getSimpleName() + "p";
    Session session = sessionFactory.getCurrentSession();
    List<ClientEntity> clientList = session.createQuery(query).list();
    for (ClientEntity c : clientList) {
        clientLog.info("Item:", c);

    }
    return clientList;
}

@Override
public ClientEntity getObjectId(final long id) {
    Session session = sessionFactory.getCurrentSession();
    ClientEntity client = session.load(ClientEntity.class, id);
    clientLog.info("Client" + client);
    return client;
}

При обращении к базе данных выпадает исключение NullPointerException. Я предполагаю потому что SessionFactory не инициализирован. Пробовал использовать @Autowared но возникает ошибка указывающая что SessionFactory нет в списке бинов для внедрения. Возможно я ошибся в конфигурации.
private Properties hibernateProperties() {
    Properties htProperties = new Properties();
    htProperties.put("hibernate.dialect",
            env.getProperty("hibernate.dialect"));
    htProperties.put("hibernate.show_sql",
            env.getRequiredProperty("hibernate.show_sql"));
    htProperties.put("hibernate.hbm2ddl.auto",
            env.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return htProperties;
}

@Bean
public PlatformTransactionManager transactionManager() {
    JpaTransactionManager transactionManager =
            new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(
            entityManagerFactory().getObject());
    return transactionManager;
}

Пробовал исправить на:
@Bean
public LocalSessionFactoryBean transactionManager() {
    LocalSessionFactoryBean factoryBean =
            new LocalSessionFactoryBean();
    factoryBean.setDataSource(dataSource());
    return factoryBean;
}

Но выпадает стек с ошибкой 500:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

В чем может быть проблема?

A: Вот тут есть настройки Hibernate'а https://github.com/bytestree/spring4-hibernate5-example
статья от этого репозитория ТУТ


text:
Q: Events shows wrong time in Google Calendar through api I've created an event and also passed the EST timezone. But in my Google Calendar, it displays as time offset 3 hours later.
For example, I pass the values as
"start": {
    "dateTime": "2017-10-27T15:00:00-04:00",
    "timeZone": "EST"
},
"end": {
    "dateTime": "2017-10-27T19:00:00-04:00",
    "timeZone": "EST"
}

But the values shown in the calendar is:
"start": {
    "dateTime": "2017-10-27T18:00:00-04:00",
    "timeZone": "EST"
},
"end": {
    "dateTime": "2017-10-27T22:00:00-04:00",
    "timeZone": "EST"
}

This is serious issue. Can anyone please help me, thank you.

A: A few things:

*

*Don't pass EST.  Use the full Area/Locality format of the tz identifier.

*

*While EST is a valid identifier, it is fixed to UTC-5.  It's really only there for certain backwards compatibility scenarios.

*The date you gave is during daylight saving time, and is UTC-4.

*Assuming you meant the US Eastern time zone, you should pass America/New_York as the time zone id.

*Even with the above taken into consideration, your output shouldn't actually be as shown above.

*

*Perhaps you are just looking at the calendar and not taking the calender's time zone setting into account?

*See the timeZone calendar settings in the API docs


text:
Q: Remember Toggle state with jQuery after refresh? I got a small script which toggles my nav. But I'm using the nav in more pages. I want jQuery to remember the toggle(show/hide) state so I can use it when navigating.
$(document).ready(function(){
$('ul.second').show();
$('ul.third').hide();
$('ul.first').show();
$('ul.first li.first a').click(function(){
    //$('ul.second').slideToggle("");
    $('ul.third').slideToggle("");
    });
});

A: You could use either use cookie management or localStorage to store this info across your session. LocalStorage only works with html5 though.
Here's a good article on a plugin that features both, so you don't need to detect yourself if the browser is capable of localStorage or not:
http://upstatement.com/blog/2012/01/jquery-local-storage-done-right-and-easy/

A: You can also add a hash to the url and detect the hash after page refresh.
More details on hash here
http://benalman.com/projects/jquery-hashchange-plugin/
https://developer.mozilla.org/en/DOM/window.onhashchange

A: you can  do it with slide function of jquery
just design the panel and flip element to your liking with css like this

Click to slide the panel down or up

Hello world!


text:
Q: Android: Many Views that require frequent redraw. Threading approach? In my application I have a number of Views that represent graphical gauges. At the moment the gauges directly represent a set of input data, with postInvalidate() being called on a particular gauge View when the data it is observing changes.
What I want to introduce next is a dampened pointer motion to simulate real gauges, plus possibly some other fancy animation features as well. Performing the calculations for the dampened motion and so forth is of course trivial. What requires some thought is the fact that, after a given View has been initially had invalidate() called on it following a change in the data model, that View needs to needs to be 'ticked' (that is, invalidated) periodically to allow it to onDraw() several times following the initial data change in order to perform the dampened pointer animation, until the point where the pointer stops completely and the View no longer requires the tick.
I can see two main ways of doing this:

*

*Each gauge View has its own Thread to periodically call postInvalidate(). This thread will eventually self-stop when the pointer movement sequence has come to an end. The result of this is that if you have a screen with a bunch of gauges shown on it, all responding to different data inputs, then at any time any of those Views could be running its own motion Thread. If the screen is showing ten gauges, then at any time you could have anything from zero to ten individual Threads running in those Views.

*Second approach is to completely remote away this 'tick' from the Views themselves, and perform the invalidate() calls all from a single Thread. This single Thread might be placed in the Activity, or defined in some GaugeTick class, or something. It would work by having individuals register themselves with it when they need to start performing some animation after the initial data model change, and can unregister themselves when done. Each time the 'tick' Thread wakes up (let's say it goes to sleep every 100ms for example, so does a very roughly 10Hz tick) it would run through and call postInvalidate() on all Views in its observer ArrayList.
I personally like option 1 because, if I'm to think in an MVC pattern sort of way, the dampened motion is an attribute of the View itself, and it's a mechanism that should be an implementation detail inside that View. From a programming point of view, it feels a lot more elegant to just run an individual Thread inside the View. Furthermore, a View's individual Thread can have a specific sleep interval to suit whatever form or speed of animation it is doing.
On the other hand, would an individual Thread in each View potentially clobber the system in terms of performance, even though they're all going to be short-lived and spend most of their time sleeping? Could I be asking for trouble potentially having so many Threads running, which would all require stopping when the Activity is paused / destroyed, or on orientation change? Going for option 2 feels a lot less of a headache in terms of Thread etiquette.
Thanks,
Trev

A: I don't think you need to multi-thread at all. If I understand correctly, you want to redraw a View (the gauges) in response to some user input (touch events). Both drawing and user input are handled by the system UI thread. Just add an invalidate() to the method in your gauge View that responds to the user input (probably onTouchEvent() in your case). The message queue will receive a message shortly thereafter to redraw the gauge.
onTouchEvent() should handle ACTION_MOVE events if you want real-time responsiveness or ACTION_UP if you want it to respond when the user is done.
Barry


text:
Q: mongodb java aggregation operation movies: {
    _id: "1"
    name: "comedy"
    userratings: [{
        user_id: "11",
        count: 4
    }, {
        user_id: "22",
        count: 2
    }]
}
movies: {
    _id: "2"
    name: "funny"
    userratings: [{
        user_id: "22",
        count: 8
    }]
}

users: {
    _id: "11",
    name: "jhon",
    userFriends: [{
        user_id: "22"
    }, {
        user_id: "12"
    }]
}
users: {
    _id: "22",
    name: "tom",
    userFriends: [{
        user_id: "11"
    }]
}

I have two collections: users and movies.
The users collection consists of users info and his friends list.
The movies collection consists of movies info and the rating of users to the movie.
My question is:
how I can find the movies that are rated by a user's friends but not the user,and order them by the sum of friends'ratings count, limit 5 records.
I am using java with mongodb

A: You need to implement this operation at your application level, i.e. using Java code. MongoDB is a document store, so it doesn't support relations between collections and what you want to do involves a relation like movies -> user_id -> users -> friends. You need to retrieve separately users and movies using Java and implement the join in your Java code. You won't be able to do this with one single MongoDB query.
Assuming that a user cannot be friends with him/herself, I would do it like this:
1) Get all userFriends from users with _id = (your_user_id):
users.find({_id : (your_user_id)}, {userFriends.user_id : 1})

2) Get all documents from movies having one userratings.user_id = (one of the userFriends from step 1). + group by userratings.count + limit 5. Something like this:
movies.aggregate(
    [
        {$match : {userratings : {user_id : { $in (userFriends)}}},
        {$group : {_id : _id, count : {$sum : userratings.count}}},
        {$sort : {count : 1}},
        {$limit : 5}
    ]
)


text:
Q: how to create chart in java web application I am new to Java Web. I am using netbeans 7.0.1 and glassfish 3 to develop a web application. I am almost through with all data input and Now I want to create reports & graph. Requirement is to create charts (pie/bar/line based on user selection) with dynamic data (from database / datatable user can apply filters on data). I tried using Primefaces but it gives below error with simple example given in primeface show case:

javax.faces.event.AbortProcessingException:
  /pages/analyst/analyse.xhtml @65,151
  actionListener="#{analysis.bar()}": java.lang.NoClassDefFoundError:
  org/primefaces/component/chart/series/ChartSeries

I have a jsf page that holds datatable backed by managedbean of viewscope. below is my code:
page
<html   xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"
        xmlns:f="http://java.sun.com/jsf/core">

    <body>
        <ui:composition template="./../../WEB-INF/Templates/VUTemplate.xhtml">
            <ui:define name="menu">
                <h:form id="home">
                    <p:menu>
                        <p:menuitem value="Home Page" url="../home.xhtml" />
                    </p:menu>
                </h:form>
            </ui:define>
            <ui:define name="content">
                <h:form id="form" prependId="false">
                    <p:growl id="growl" showDetail="true"/>

                    <p:barChart id="basic" value="#{analysis.categoryModel}" legendPosition="ne"
                                title="Basic Bar Chart" min="0" max="200" style="height:300px"/>

                    <p:dataTable id="table" var="var" widgetVar="wbTable"
                                 value="#{analysis.list}"
                                 paginator="true" rows="10"
                                 paginatorPosition="bottom"
                                 emptyMessage="No data found with given criteria"
                                 >

                        <f:facet name="header">
                            World Bank Open Data Analysis
                        </f:facet>

                        <p:column filterBy="#{var.regionFullName}" sortBy="#{var.regionFullName}"
                                  headerText="Region" footerText="Enter starting characters" >
                            <h:outputText   value="#{var.regionFullName}" />
                        </p:column>

                        <p:column filterBy="#{var.countryFullName}" sortBy ="#{var.countryFullName}"
                                  headerText="Country" footerText="Enter starting characters" >
                            <h:outputText   value="#{var.countryFullName}" />
                        </p:column>

                        <p:column  filterBy="#{var.indcatorTypeName}" sortBy ="#{var.indcatorTypeName}"
                                   headerText="Indicator Type" footerText="Enter starting characters" >
                            <h:outputText   value="#{var.indcatorTypeName}" />
                        </p:column>

                        <p:column  filterBy="#{var.indicatorName}" sortBy ="#{var.indicatorName}"
                                   headerText="Indicator" footerText="contains" filterMatchMode="contains">
                            <h:outputText   value="#{var.indicatorName}" />
                        </p:column>

                        <p:column  filterBy="#{var.year}" sortBy ="#{var.year}"
                                   headerText="Year" footerText="starts with">
                            <h:outputText value="#{var.year}" />
                        </p:column>

                        <p:column  filterBy="#{var.dataValue}" sortBy ="#{var.dataValue}"
                                   headerText="Data Value" footerText="starts with" >
                            <h:outputText value="#{var.dataValue}" />
                        </p:column>
                    </p:dataTable>

                    <h:panelGrid id="command" columns="6"  cellpadding="4" >
                        <p:commandButton id="line" value="Line" actionListener="#{analysis.line()}"  process="@this :form:table"  update="result  table" >
                        </p:commandButton>
                        <p:commandButton id="bar" value="Bar" actionListener="#{analysis.bar()}" process="@this :form:table"  update="result  table" >
                        </p:commandButton>
                    </h:panelGrid>
                    <p:messages id="result" showDetail="true" autoUpdate="true"/>

                </h:form>
            </ui:define>
        </ui:composition>
    </body>
</html>

backbean
import ejb.VwdataFacade;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import model.Vwdata;
import org.primefaces.component.chart.series.ChartSeries;
import org.primefaces.model.chart.CartesianChartModel;

@ManagedBean
@ViewScoped
public class Analysis implements Serializable{
    private List<Vwdata> list;

    private @EJB VwdataFacade wsvc;  //entity services
    private CartesianChartModel categoryModel;

    public Analysis() {
    }

    public CartesianChartModel getCategoryModel() {
        return categoryModel;
    }

    @PostConstruct
    public void init() {
        list = wsvc.findAll();
     }

    public List<Vwdata> getList() {
//        list = wsvc.findAll();
        return list;
    }
    public void line(){

    }

    public void bar(){
        createCategoryModel();
    }

    private void createCategoryModel() {
        categoryModel = new CartesianChartModel();
        ChartSeries yaxis = new ChartSeries();
        yaxis.setLabel("Label");
        yaxis.set("2004",120);
        yaxis.set("2005",130);
        yaxis.set("2006",140);
        yaxis.set("2007",110);
        categoryModel.addSeries(yaxis);
    }

}

If I place call createCategoryModel in the constructor or init method, I cant even view the page which otherwise was working perfectly without chart code. Any help will be highly appreciated. Thanks

A:
java.lang.NoClassDefFoundError: org/primefaces/component/chart/series/ChartSeries

The mentioned class was introduced in PrimeFaces 3.0 and was thus not available in PrimeFaces 2.x and older.
Given the fact that the PrimeFaces 3.0 specific XML namespace http://primefaces.org/ui and all the <p:xxx> tags in your code did apparently not result in a Facelets compile error, that can only mean that you've both PrimeFaces 2.x and 3.x libraries in your webapp's runtime classpath wherein the 2.x one got precedence in classloading.
Get rid of the offending old PrimeFaces 2.x library from your webapp's runtime classpath and this problem should then disappear.


text:
Q: Using Greasemonkey, is it possible to make some parts of the script apply to certain sites and other parts apply to different sites? The reason I want to do this is that I'm writing a script for meebo.com that involves changing the background and replacing some pictures with css.  I'd like to add links to it from other sites (namely Gmail, Google Calendar, etc.)  Is it possible to accomplish this with one Greasemonkey script? (I think this is a general enough question to exclude my actual code but if it would help, just leave a comment saying so.)

A: Well, I think the conventional method would be to write two scripts, one that only @include's meebo.com (and changes the background image) and another that @include's http://* or whatever set of other URLs (and adds a link to meebo).
But if you're set on writing only a single script, you could use a series of if statements to accomplish the same effect.  That would look something like this:
// @include        http://*
// ==/UserScript==
if (window.location.hostname.match(/meebo\.com/) {
    //change background images and do other meebo.com specific actions
} else if (window.location.hostname.match(/google\.com/) {
    //add a link to the DOM (or some other Google specific action)
}