text:
Q: Browse Button required? Hii i am working on an application in which i require to select files using browse button..
How can i implement a browse button in android?

A: You need to do:

*

*Create a button which runs a separate activity(startActivityForResult).

*This file choosing activity should list all the files and folders from a particular location. If you click on a folder, then activity is reinitialized for this folder(list the files from this).

*If a file clicked, then activity should set the result, passing the filename in extras, and finish.

A: Below is the whole code from my sample application. I used a button which will pick files from any directory of your phone.
layouts
file_picker_empty_view.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No files or directories"
android:background="@android:drawable/toast_frame"
android:textSize="28sp"
android:gravity="center_vertical|center_horizontal"/>

file_picker_list_item.xml
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal" >
  <ImageView
      android:id="@+id/file_picker_image"
      android:layout_width="40dip"
      android:layout_height="40dip"
      android:layout_marginTop="5dip"
      android:layout_marginBottom="5dip"
      android:layout_marginLeft="5dip"
      android:src="@drawable/file"
      android:scaleType="centerCrop"/>
  <TextView
      android:id="@+id/file_picker_text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:layout_gravity="left|center_vertical"
      android:textSize="28sp"
      android:layout_marginLeft="10dip"
      android:singleLine="true"
      android:text="filename"/>
</LinearLayout>

file_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_width="fill_parent">
    <TextView android:text="@+id/TextView01"
    android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:textStyle="bold"
    android:layout_marginTop="5dip"
    android:layout_marginLeft="5dip"></TextView>
    <TextView android:text="@+id/TextView02"
    android:id="@+id/TextView02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dip"></TextView>
</LinearLayout>

main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical">
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start_file_picker_button"
        android:text="Browse" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Selected file"
        android:textStyle="bold"
        android:textColor="#fff"
        android:textSize="24sp" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/file_path_text_view"
        android:text="No file has been selected"
        android:textSize="18sp" />
</LinearLayout>

Activities are
FilePickerActivity
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 *
 * @author pankaj
 *
 */
public class FilePickerActivity extends ListActivity {

    public final static String EXTRA_FILE_PATH = "file_path";
    public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
    public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
    private final static String DEFAULT_INITIAL_DIRECTORY = "/";

    protected File mDirectory;
    protected ArrayList<File> mFiles;
    protected FilePickerListAdapter mAdapter;
    protected boolean mShowHiddenFiles = false;
    protected String[] acceptedFileExtensions;

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

        // Set the view to be shown if the list is empty
        LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View emptyView = inflator.inflate(R.layout.file_picker_empty_view, null);
        ((ViewGroup)getListView().getParent()).addView(emptyView);
        getListView().setEmptyView(emptyView);

        // Set initial directory
        mDirectory = new File(DEFAULT_INITIAL_DIRECTORY);

        // Initialize the ArrayList
        mFiles = new ArrayList<File>();

        // Set the ListAdapter
        mAdapter = new FilePickerListAdapter(this, mFiles);
        setListAdapter(mAdapter);

        // Initialize the extensions array to allow any file extensions
        acceptedFileExtensions = new String[] {};

        // Get intent extras
        if(getIntent().hasExtra(EXTRA_FILE_PATH)) {
            mDirectory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
        }
        if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) {
            mShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
        }
        if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
            ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
            acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]);
        }
    }

    @Override
    protected void onResume() {
        refreshFilesList();
        super.onResume();
    }

    /**
     * Updates the list view to the current directory
     */
    protected void refreshFilesList() {
        // Clear the files ArrayList
        mFiles.clear();

        // Set the extension file filter
        ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions);

        // Get the files in the directory
        File[] files = mDirectory.listFiles(filter);
        if(files != null && files.length > 0) {
            for(File f : files) {
                if(f.isHidden() && !mShowHiddenFiles) {
                    // Don't add the file
                    continue;
                }

                // Add the file the ArrayAdapter
                mFiles.add(f);
            }

            Collections.sort(mFiles, new FileComparator());
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if(mDirectory.getParentFile() != null) {
            // Go to parent directory
            mDirectory = mDirectory.getParentFile();
            refreshFilesList();
            return;
        }

        super.onBackPressed();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        File newFile = (File)l.getItemAtPosition(position);

        if(newFile.isFile()) {
            // Set result
            Intent extra = new Intent();
            extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
            setResult(RESULT_OK, extra);
            // Finish the activity
            finish();
        } else {
            mDirectory = newFile;
            // Update the files list
            refreshFilesList();
        }

        super.onListItemClick(l, v, position, id);
    }

    private class FilePickerListAdapter extends ArrayAdapter<File> {

        private List<File> mObjects;

        public FilePickerListAdapter(Context context, List<File> objects) {
            super(context, R.layout.file_picker_list_item, android.R.id.text1, objects);
            mObjects = objects;
        }

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

            View row = null;

            if(convertView == null) {
                LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.file_picker_list_item, parent, false);
            } else {
                row = convertView;
            }

            File object = mObjects.get(position);

            ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
            TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
            // Set single line
            textView.setSingleLine(true);

            textView.setText(object.getName());
            if(object.isFile()) {
                // Show the file icon
                imageView.setImageResource(R.drawable.file);
            } else {
                // Show the folder icon
                imageView.setImageResource(R.drawable.folder);
            }

            return row;
        }

    }

    private class FileComparator implements Comparator<File> {
        public int compare(File f1, File f2) {
            if(f1 == f2) {
                return 0;
            }
            if(f1.isDirectory() && f2.isFile()) {
                // Show directories above files
                return -1;
            }
            if(f1.isFile() && f2.isDirectory()) {
                // Show files below directories
                return 1;
            }
            // Sort the directories alphabetically
            return f1.getName().compareToIgnoreCase(f2.getName());
        }
    }

    private class ExtensionFilenameFilter implements FilenameFilter {
        private String[] mExtensions;

        public ExtensionFilenameFilter(String[] extensions) {
            super();
            mExtensions = extensions;
        }

        public boolean accept(File dir, String filename) {
            if(new File(dir, filename).isDirectory()) {
                // Accept all directory names
                return true;
            }
            if(mExtensions != null && mExtensions.length > 0) {
                for(int i = 0; i < mExtensions.length; i++) {
                    if(filename.endsWith(mExtensions[i])) {
                        // The filename ends with the extension
                        return true;
                    }
                }
                // The filename did not match any of the extensions
                return false;
            }
            // No extensions has been set. Accept all file extensions.
            return true;
        }
    }
}

MainActivity // This must be your default Activity, as MAIN in manifest
public class MainActivity extends Activity implements OnClickListener {

    private static final int REQUEST_PICK_FILE = 1;

    private TextView mFilePathTextView;
    private Button mStartActivityButton;
    private File selectedFile;

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

        // Set the views
        mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
        mStartActivityButton = (Button)findViewById(R.id.start_file_picker_button);
        mStartActivityButton.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.start_file_picker_button:
            // Create a new Intent for the file picker activity
            Intent intent = new Intent(this, FilePickerActivity.class);

            // Set the initial directory to be the sdcard
            //intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory());

            // Show hidden files
            //intent.putExtra(FilePickerActivity.EXTRA_SHOW_HIDDEN_FILES, true);

            // Only make .png files visible
            //ArrayList<String> extensions = new ArrayList<String>();
            //extensions.add(".png");
            //intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);

            // Start the activity
            startActivityForResult(intent, REQUEST_PICK_FILE);
            break;

        case R.id.You_can_handle_more_onclick_events_from_here:
            //Do something
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK) {
            switch(requestCode) {
            case REQUEST_PICK_FILE:
                if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
                    // Get the file path
                    selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
                    // Set the file path text view
                    mFilePathTextView.setText(selectedFile.getPath());
                    //Now you have your selected file, You can do your additional requirement with file.
                }
            }
        }
    }
}

Now Iam uploading images, You can use your own images.
Image Name: file

Image Name: folder

and finally
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.myContactAdder.adder"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-permission android:name="android.permission.READ_CONTACTS" />
      <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FilePickerActivity"
                  android:label="@string/app_name">
        </activity>
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />

</manifest>

Original references (now unavailable): Android file picker Activity and Creating simple file chooser.

Edited after above ref not available.
https://github.com/AndersKaloer/Android-File-Picker-Activity


text:
Q: How come the image is not displayed? I'm learning php and mysqli.  I wrote a program that allows users to upload name and image to a database.  They can click on a name in the database and clicking on a name, they'll see a picture of that person.
Below are my PHP file.  Everything works except that the image doesn't display.  When I click on a name, all I see is a blue box with a question mark.  Can someone take a look at my code and give me some hints on how to solve this?  Thanks!
main.php
    <?php

    //Turn on error reporting
    ini_set('display_errors', 'On');
    //Connects to the database
    $mysqli = new mysqli("abc", "abc","abc", "abc");
    if($mysqli->connect_errno){
        echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>Homework</title>
        <meta charset="UTF-8">

Homework

            <form method="post" action="index.php" enctype="multipart/form-data">
                Celebrity Name: <input type="text" name="c_name">
                Celebrity Photo: <input type="file" name="c_picture">
                <input type="submit" name="add" value="Upload">
            </form>

            See below for a list of celebrities in our database

        <?php
            //Display names in the celebrity database
            if(!($stmt = $mysqli->prepare("SELECT c_id, c_name FROM celebrity"))){
                echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
            }

            if(!$stmt->execute()){
                echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            if(!$stmt->bind_result($c_id, $c_name)){
                echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            while($stmt->fetch()){
                echo "
" . $c_name . "
";
                //echo "
\n\n" . $c_name . "\n	\n
";

            }

            $stmt->close();
        ?>

img.php
    <?php

    //Turn on error reporting
    ini_set('display_errors', 'On');
    //Connects to the database
    $mysqli = new mysqli("blah", "blah","blah", "blah");
    if($mysqli->connect_errno){
        echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    $c_id=1;
    //retrieve the blob
    if(!($stmt = $mysqli->prepare("SELECT c_picture FROM celebrity where c_name = ?"))){
        echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
    }

    //if(!($stmt->bind_param("i",$_GET['c_id']))){
    if(!($stmt->bind_param("i",$c_id))){
        echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
    }

    if(!$stmt->execute()){
        echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
    }

    $stmt->store_result();

    if(!$stmt->bind_result($c_picture)){
        echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
    }

    $stmt->fetch();
    header("Content-Type: image/jpeg");
    echo $c_picture;

    $stmt->close();
?>

index.php
    <?php

    //Turn on error reporting
    ini_set('display_errors', 'On');
    //Connects to the database
    $mysqli = new mysqli("blah", "blah","blah", "blah");
    if($mysqli->connect_errno){
        echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $errorinfo = $_FILES['c_picture']['error'];
        $img = $_FILES['c_picture']['name'];
        $imgTmp = $_FILES['c_picture']['tmp_name'];
        $imgSize = $_FILES['c_picture']['size'];
        $imgType = $_FILES['c_picture']['type'];
    }

    //Check image type and size
    if (($imgType == 'image/jpeg' || $imgType == 'image/gif' || $imgType == 'image/png') && $imgSize < 1048576)
    {
        //Insert name and image file into celebrity database (c_name, c_picture) values (?, ?)
        if(!($stmt = $mysqli->prepare("INSERT INTO celebrity(c_name, c_picture) VALUES (?, ?)")))
        {
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }

        if(!($stmt->bind_param("sb",$_POST['c_name'], $img)))
        {
            echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
        }

        if(!$stmt->execute())
        {
            echo "Execute failed: "  . $stmt->errno . " " . $stmt->error;
        }
        else
        {
            echo "Added " . $stmt->affected_rows . " celebrity to database.";
        }

    }
    else
    {
        echo "Only jpegs, gifs, and pngs under 1MB can be uploaded";
    }
?>

A: You are not saving the image data when inserting, if you print:
$img = $_FILES['c_picture']['name'];
echo $img;

It is only the image's original name, instead you need to save the file data. If you wanted to just output the image directly:
header("Content-Type: image/jpeg");
echo file_get_contents($_FILES['c_picture']['tmp_name']);

What you need to do is take the image data from $_FILES['c_picture']['tmp_name'] and store it as BLOB or LONGBLOB in your database. I see you are already using BLOB, so you only need to change:
$img = $_FILES['c_picture']['name'];

instead, use:
$img = file_get_contents($_FILES['c_picture']['tmp_name']);

Also, your header should output the right image type, maybe you can save it to the database too.
In a real world application you shouldn't store the image's binary in a database, a better approach would be to store the image in a folder and just save the address in the database.

A: The link to the page that displays picture in your main.php is img.php:

Yet the Name of the file you posted here that display picture is viewfile.php, so just change your link to point to viewfile.php:

A: just check something, if you entered the full image tag in the db then there is a problem, but if you just entered the name of the image to the db, to view it, you should do something like this

instead of just $c_name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting MasterDetail Relationship to lookup and Its impacts on Reports We are working on urgent requiremnt where i am looking for the best approach to to achieve this.
What impact would be on report, i have read many articles that warns doing this as this might impact reports and dashboards.
I was wondering will this changes really impacts reports and dashboards.
Any Suggestions are welcome

A: Converting a relationship from master detail to lookup can cause existing custom reports to become unusable due to the different standard report types available for each type of relationship.
Its better to test your custom reports immediately after converting the relationship type. If you revert your relationship back to the original type, the reports are restored and become usable again.
Master-Detail Standard Report Types
Master object by itself ||
Master object with detail object ||
Master object with detail object and first lookup ||
Master object with detail object and second lookup
Lookup Standard Report Types
Object by itself ||
Object with first lookup ||
Object with second lookup ||
Object with third lookup ||
Refer to this article if you need more information : Link
Mark this as helpful if this is helpful to you.


text:
Q: Change the style of the border in ChartJS I have a chart using Chart.js library. I want border of this chart to be dotted, not solid. Can someone help me please?

const ctx = document.getElementById('myChart').getContext('2d');

const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: '#ffec87',
      borderWidth: 0,
      borderStyle: 'dotted'
    }]
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<canvas id="myChart" width="400" height="100px"></canvas>

A: The Styling docs list all the config options for axis grid line configuration.

const ctx = document.getElementById('myChart').getContext('2d');

const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: '#ffec87',
      borderWidth: 0,
      borderStyle: 'dotted'
    }]
  },
  options: {
    scales: {
      xAxis: { grid: { display: false } },
      yAxis: { grid: { borderDash: [8, 4] } }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<canvas id="myChart" width="400" height="100px"></canvas>


text:
Q: libgdx how to slowly rotate a model to face a point Hi i am trying to make a libgdx game...but i am stuck on how to rotate a model instance to face another but slowly like 1 or 2 degrees per second
I have two vectors the direction of the first model instance and the position of the second


text:
Q: Perl uninitialized warnings I've got my program keymap (it is not yet actually mapping any keys yet and is currently only printing out what it sees in hex) here:
#!/usr/bin/env perl

use strict;
use warnings;

use Term::ReadKey;
ReadMode 4;
END {
    ReadMode 0; # Reset tty mode before exiting
}

if ($ARGV[0] ~~ ["h", "-h", "--help", "help"]) {
    print "Usage: (h|-h|--help|help)|(code_in codes_out [code_in codes_out]+)\nNote: output codes can be arbitrary length";
    exit;
}

$#ARGV % 2 or die "Even number of args required.\n";

$#ARGV >= 0 or warn "No args provided. Output should be identical to input.\n";

my $interactive = -t STDIN;

my %mapping = @ARGV;

{
    local $| = 1;
    my $key;
    while (ord(($key = ReadKey(0))) != 0) {
        printf("saw \\x%02X\n",ord($key));
        if ($interactive and ord($key) == 4) {
            last;
        }
    }
}

Here's what happens:
slu@new-host:~/util 20:50:20
❯ keymap a b
saw \x61
saw \x62
saw \x04

There I had typed on my keyboard abCtrl+D.
slu@new-host:~/util 20:50:24
❯ echo "^D^Da" | keymap
No args provided. Output should be identical to input.
saw \x04
saw \x04
saw \x61
saw \x0A
Use of uninitialized value $key in ord at /Users/slu/util/keymap line 30.

I'm wondering what the meaning of this is. Is it simply a case of Perl "not counting" the loop condition as "setting" $key? Is there some sort of thing I can do to suppress the warning here? I know about no warnings "uninitialized";, I don't want that.

A: There's a known bug that warnings issued by the condition expression of a while loop can be misattributed to the statement in the loop evaluated just before the while condition.
The code issuing the warning is actually the condition of the while loop, ord(($key = ReadKey(0))) != 0.
ReadKey(0) is returning undef, and you are trying to get the ord or it.
while (1) {
    my $key = ReadKey(0);
    last if !defined($key) || ord($key) == 0;

    printf("saw \\x%02X\n",ord($key));

    last if $interactive and ord($key) == 4;
}


text:
Q: Adding to the session number Alright so I have a task, that I have to let the client try to enter the password 3 times, if he doesn't enter the right password in 3 times, it will redirect him to another page, The thing is that I don't know how can I use the session, how can I do like ++ or  something.
Session["counter"] = 0;

And I am trying to do the following:
Session["counter"]++;

How can I detect if the client tried to enter the password 3 times?
Thanks

A: int counter=1;
Session["counter"]=counter;

When you want to update that, read the value and convert it to int and then increase, save back
if(Session["counter"]!=null)
{
 counter=Convert.ToInt32(Session["counter"]);
}
counter++;
Session["counter"]=counter;

EDIT : As per the comment, This is how you can check the counter value. I wrapped the checking inside 2 methods to set and get, you can even use Properties as others mentioned.
private int GetLoginAttempts()
{
    int counter=0;
    if(Session["counter"]!=null)
    {
     counter=Convert.ToInt32(Session["counter"]);
    }
  return counter;
}
private void IncreaseLoginAttempts()
{
   if(Session["counter"]!=null)
   {
     counter=Convert.ToInt32(Session["counter"]);
   }
   counter++;
   Session["counter"]=counter;
}

and when user tries to login( in your button click / action method ), check the Current value
   if(GetLoginAttempts()==3)
   {
        //This means user already tried 3 times, show him a message !
   }
   else
   {
        //Do the login process, If login fails, increase the counter
       IncreaseLoginAttempts()
   }

A: Try this.
int counter = Int32.Parse(Session["counter"].ToString()); //Session["counter"] may be null

Session["counter"] = ++counter;

A: You could implement it by wrapping it in a property as so:
    public int PasswordAttempts
    {
        get
        {
            if (Session["PasswordAttempts"] == null)
                Session["PasswordAttempts"] = 0;

            return (int)Session["PasswordAttempts"];
        }
        set
        {
            Session["PasswordAttempts"] = value;
        }
    }

    protected void Submit_Click(object sender, EventArgs e)
    {
        PasswordAttempts++;
    }

A: private Int16 Counter
{
    get
    {
        if (ViewState["Counter"] == null)
            return 0;
        else
            return Convert.ToInt16(ViewState["Counter"]);
    }
    set
    {
        Int16 counter = 0;
        if (ViewState["Counter"] == null)
            counter = 0;
        else
            counter = Convert.ToInt16(ViewState["Counter"]);
        ViewState["Counter"] = counter + 1 + value;
    }
}
if(counter == 3)
{
}


text:
Q: Migration disaster from classic asp to .net Does anyone have experience with companies that have migrated from classic Asp to .Net badly?
In this company, the "folder" icon that represents a Solution and the "folder" icon that represents a Project and the "folder" icon that represents a file directory are all the same thing.
The .Net IDE is just a better notepad.
The entire company is in one massive Solution.  The code for what should be many, completely separate Projects is all intermixed within and spread out amongst a set of "folders" in the "Master Solution".  Each of these folders contains motley information for any and every application the place has ever created in .Net.
My question is what happens to companies like this?  Do they go out of business?  Do they stay with it indefinitely, sticking with the same, labor-intensive "code base" maintenance nightmare that no real .Net programmer can stand?  Do they ever see the light?  If so, how?
I must know.

A: It's possible, they won't migrate.  The code still works, it's just old.  Most likely what would happen is that the project will be replaced a small part at a time, but not with an overall strategy.  It will be slow and drudging.  There will be talks about rewriting the application, but it will never actually happen.  A lot of the places have the mentality, if it isn't broken don't fix it.  If it does what they need it to do, it will be around for a long time.

A: I work for the company which has as intranet 30,000 pages.. Written in classic asp. Not to mention the 200+ internet application sin ASP and VB components.  ;-)
We still get good business (almost 60%) online. Cant migrate soon. We do it slowly. Better do new projects in .net. I agree to Kevin if it works why broke it.
Mos of the time the business dont se any good reason to migrate if its working properly.

A: But does it still work? If it does, than why, especially in this economy would you upgrade? just for the heck of it? There needs to be a better reason that that.
Do you scrape all the paint off of your house and re-paint it everythime Glidden introduces a new/better formula that is supposed to last longer? Probably not. You repaint it when it needs repainting.

A: This excellent article is old, but definitely sums up the "new vs. old" technology debate, and what it actually means to business.
If the old technology is a proven, stable money-maker, rewriting it in a newer language only adds risk.


text:
Q: Android Notification. Экран блокировки Как запросить  разрешение на показ уведомления на закрытом экране.
На моем Redmi 7A (Android 10) у каждого приложения есть данный пункт - Разрешить уведомления на экране блокировки.
Как я могу получить из кода данное разрешение? Пока что оно у меня не активно.
Для примера, такие приложения как Telegram, WhatsApp сразу после установки имеют данное разрешение, хочу реализовать что-то подобное в своем проекте.


text:
Q: How to merge, create tags and put an ascending order the feeds of more RSS Feed links like on Yahoo Pipes? I need to take the feeds of more RSS Feed urls that I have to aggregate and show the news in descending order.
Some links don't have an xml tag for <category> so I need to create one: I have to know where feeds come from so that I can categorize them.
This is what I'm trying to achieve: ( for Source n I mean the category)
[![enter image description here][1]][1]
I used to use Yahoo!Pipes to make all these changes.
My attempt was to create a CustomListView for each url and then execute the AsyncTasks all at once but that is not working correctly - the feeds are not displayed in ascending order.
MainActivity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private RSSFeed myRssFeed = null;
    String[] urlFeed = {"url1", "url2"};

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

        for (int i = 0; i < urlFeed.length; i++) {
            News news = new News(i);
            news.execute();
        }
    }

    @Override
    public void onRefresh() {
        for (int i = 0; i < urlFeed.length; i++) {
            News news = new News(i);
            news.execute();
        }
    }

    private class News extends AsyncTask<Object, Void, Void> {
        protected int number;
        public News(int urlNumber) {
            number = urlNumber;
        }

        @Override
        protected Void doInBackground(Object... arg0) {

            String data = "";
            InputStream iStream;

            try{
                URL url = new URL(urlFeed[number]);

                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuilder sbf  = new StringBuilder();

                String line;
                while( ( line = br.readLine())  != null){
                    sbf.append(line);
                }

                data = sbf.toString();

                br.close();

                SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
                XMLReader myXMLReader = mySAXParser.getXMLReader();
                RSSHandler myRSSHandler = new RSSHandler();
                myXMLReader.setContentHandler(myRSSHandler);
                InputSource myInputSource = new InputSource(url.openStream());
                myXMLReader.parse(myInputSource);

                myRssFeed = myRSSHandler.getFeed();

            } catch (ParserConfigurationException | IOException | SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (myRssFeed != null) {

                NestedListView list = (NestedListView)findViewById(android.R.id.list);
                list.setVisibility(View.VISIBLE);
                CustomList adapter = new CustomList(MainActivity.this, myRssFeed.getList());
                adapter.addAll();
                list.setAdapter(adapter);

            } else
                Toast.makeText(MainActivity.this, "Error",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

RSSFeed
public class RSSFeed {
    private String title = null;
    private String description = null;
    private String link = null;
    private String pubdate = null;
    private String image = null;
    private String enclosure = null;
    private String author = null;
    private List<RSSItem> itemList;

    RSSFeed(){
        itemList = new Vector<RSSItem>(0);
    }

    void addItem(RSSItem item){
        itemList.add(item);
    }
    RSSItem getItem(int location){
        return itemList.get(location);
    }
    List<RSSItem> getList(){
        return itemList;
    }

}

RSSItem
public class RSSItem {

    private String title = null;
    private String description = null;
    private String link = null;
    private String pubdate = null;
    private String image = null;
    private String enclosure = null;
    private String author = null;
}

CustomList
public class CustomList extends ArrayAdapter<RSSItem> {

    private static Activity context = null;
    private final List<RSSItem> web;

    public CustomList(Activity context, List<RSSItem> web) {
        super(context, R.layout.new_listview, web);
        CustomList.context = context;
        this.web = web;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        @SuppressLint({"ViewHolder", "InflateParams"}) final View rowView = inflater.inflate(R.layout.new_listview, null, true);
        ImageView imageView = (ImageView)rowView.findViewById(R.id.image);
            Picasso.with(context).load(web.get(position).getImage()).into(imageView);

        TextView textView = (TextView)rowView.findViewById(R.id.title);
        textView.setText(Html.fromHtml(web.get(position).getTitle()));

        TextView textView1 = (TextView)rowView.findViewById(R.id.description);
        textView1.setText(web.get(position).getDescription());

        TextView textView2 = (TextView)rowView.findViewById(R.id.pubdate);
        textView2.setText(pubdate);

        return rowView;

    }

}

RSSHandler
public class RSSHandler extends DefaultHandler {

    final int state_unknown = 0;
    final int state_title = 1;
    final int state_description = 2;
    final int state_link = 3;
    final int state_pubdate = 4;
    final int state_enclosure = 6;
    final int state_image = 5;
    final int state_author = 7;
    int currentState = state_unknown;
    String url;

    RSSFeed feed;
    RSSItem item;

    boolean itemFound = false;

    RSSHandler(){
    }

    RSSFeed getFeed(){
        return feed;
    }

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        feed = new RSSFeed();
        item = new RSSItem();

    }

    @Override
    public void startElement(String uri, String localName, String qName,
                         Attributes attributes) throws SAXException {

        // TODO Auto-generated method stub

        if (localName.equalsIgnoreCase("item")){
            itemFound = true;
            item = new RSSItem();
            currentState = state_unknown;
        }
        else if (localName.equals("enclosure")) {
            url = attributes.getValue("url");
            currentState = state_image;
        }
        else if (localName.equalsIgnoreCase("title")){
            currentState = state_title;
        }
        else if (localName.equalsIgnoreCase("description")){
            currentState = state_description;
        }
        else if (localName.equalsIgnoreCase("link")){
            currentState = state_link;
        }
        else if (localName.equalsIgnoreCase("pubdate")){
            currentState = state_pubdate;
        }
        else if (localName.equalsIgnoreCase("author")){
            currentState = state_author;
        }
        else{
            currentState = state_unknown;
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        if (localName.equalsIgnoreCase("item")){
            feed.addItem(item);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
        throws SAXException {
        // TODO Auto-generated method stub

        String strCharacters = new String(ch,start,length);

        if (itemFound){
            // "item" tag found, it's item's parameter
            switch(currentState){
                case state_enclosure:
                    item.setEnclosure(strCharacters);
                    break;
                case state_title:
                    item.setTitle(strCharacters);
                    break;
                case state_image:
                    item.setImage(url);
                    break;
                case state_description:
                    item.setDescription(strCharacters);
                    break;
                case state_link:
                    item.setLink(strCharacters);
                    break;
                case state_pubdate:
                    item.setPubdate(strCharacters);
                    break;
                case state_author:
                    item.setAuthor(strCharacters);
                    break;
                default:
                    break;
            }
        }
        else{
            // not "item" tag found, it's feed's parameter
            switch(currentState){
                case state_enclosure:
                    feed.setEnclosure(strCharacters);
                    break;
                case state_title:
                    feed.setTitle(strCharacters);
                    break;
                case state_image:
                    feed.setImage(url);
                    break;
                case state_description:
                    feed.setDescription(strCharacters);
                    break;
                case state_link:
                    feed.setLink(strCharacters);
                    break;
                case state_pubdate:
                    feed.setPubdate(strCharacters);
                    break;
                case state_author:
                    feed.setAuthor(strCharacters);
                    break;
                default:
                    break;
            }
        }

        currentState = state_unknown;
    }

A: The solution requires more than one change. The first thing you need to do is make each News task that finishes adds its data to the one big list. That list can then be sorted which requires a Comparator.
You also need a list of the names to show in the placeholder youve called Source n in your image and lastly,  so that you can compare them, you need to parse the dates as actual dates.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private List<RSSItem> totalRssFeed = new ArrayList<>();
    String[] urlFeed = {"MyURL", "MyUrl2", "MyUrl3"};
    String[] names = {"Name", "Name2", "Name3"}
    private CustomList adapter;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        ListView list = (ListView) findViewById(android.R.id.list);
        adapter = new CustomList(MainActivity.this);
        list.setAdapter( adapter );
    }

    @Override
    protected void onResume() {
        // do this here and you dont need to repeat it in refresh and create
        for (int i = 0; i < urlFeed.length; i++) {
            News news = new News(i);
            news.execute();
        }
    }

    public class CustomList extends ArrayAdapter<RSSItem> {

        ...

        public CustomList(Activity context) { //dont start with default data
            super(context, R.layout.new_listview, null);
        }

        ...

    }

    private class News extends AsyncTask<Object, Void, Void> {

        protected int number;

        public News(int urlNumber) {
            number = urlNumber;
        }

        @Override
        protected Void doInBackground(Object... arg0) {
            try {

                //no need to do the input stuff you were doing before here?
                URL url = new URL(urlFeed[number]);
                SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
                XMLReader myXMLReader = mySAXParser.getXMLReader();
                RSSHandler myRSSHandler = new RSSHandler(names[number]);
                myXMLReader.setContentHandler(myRSSHandler);
                InputSource myInputSource = new InputSource(url.openStream());
                myXMLReader.parse(myInputSource);
                totalRssFeed.addAll(myRSSHandler.getFeed());
                Collections.sort(totalRssFeed);

            } catch (ParserConfigurationException | IOException | SAXException e) { /* stuff */ }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            adapter.clear();
            adapter.addAll(totalRssFeed);
        }

    }

    public class RSSItem implements Comparable<RSSItem> {

        public String tag;
        public Date pubdate; //just public so i didnt need setters in this example

        public RSSItem(String defaultTagToUse) {
            //You should set the default to whatever you want displayed
            //when the tag for <category> is missing, and just update it normally otherwise
            tag = defaultTagToUse;
        }

        void setPubDate(Date date) {
            pubdate = date;
        }

        ...

        @Override
        public int compareTo(@NonNull RSSItem another) {
            int res;
            if (pubdate == null) {
                if (another.pubdate == null) {
                    res = 0;
                } else {
                    res = -1;
                }
            } else {
                if (another.pubdate == null || pubdate.getTime() > another.pubdate.getTime()) {
                    res = 1;
                } else {
                    res = -1;
                }
            }
            return res;
        }

    }

    public class RSSHandler extends DefaultHandler {

        ...
        List<RSSItem> feed;
        RSSItem item;
        String mName;

        public RssHandler(String name) {
            mName = name;
        }

        List<RSSItem> getFeed() {
            return feed;
        }

        @Override
        public void startDocument() throws SAXException {
            feed = new ArrayList<>();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (localName.equalsIgnoreCase("item")) {
                itemFound = true;
                item = new RSSItem( name );
                currentState = state_unknown;
            } else ...
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (localName.equalsIgnoreCase("item")) {
                feed.add(item);
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            ...
            case state_pubdate:
                SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); //make sure you match the format from your XML
                item.setPubdate( formatter.parse(stringCharacters) );
            break;
            ...
        }
    }
}

All the ...'s jsut mean leave everything as it was in those places


text:
Q: English spelling and grammar exercise database I have a little odd question, probably borderline applicable to stackoverflow...
What I am looking to do is to write a Windows program, which I will give my kids to exercise in English spelling as well as grammar. I want it to be in a quiz-like format (like: If we * [to cycle] to Dresden, it will be a fantastic trip). However if there are too few different sentences in a quiz, kids would just remember those, and they will be filling them mechanically instead of learning, so I need to get an access to a big pool of exercises, and those should be in a program-accessible format - xml, or database, or some text with a clear format.
Is anyone aware of any English exercise database available in such form?

A: There are many dictionary sites like Dictionary.com that provide API access to their data. Dictionary.com offers an example sentences call that can be queried with a random value to return a random sample sentence in XML.  I would give that a try.


text:
Q: Greedy Sort Of Array By Value - #numOfSameTypeSoFar I have an array that I wish to sort in a specific way according to value & type. In simple words, I wish to sort by value but to also give bonus points to less popular types according to which other elements have already been chosen as bigger. The array looks something like this:
    [1] => Array
        (
            [value] => 7
            [type] => A
        )

    [2] => Array
        (
            [type] => A
            [value] => 5
        )
    [3] => Array
        (
            [type] => B
            [value] => 4
        )
    [4] => Array
        (
            [type] => A
            [value] => 34
        )

And I would like to sort it by value, but also mix things up and give some weight to the type parameter. The more I already have top places with type = X, the more I will give bonus value to other types. I've tried this:
usort($myArray, function(&$a, &$b) {
        static $typeCounts;

        // to mix things up a bit
        $bValue = $b['value'] - 10*$typeCounts[$b['type']];
        $aValue = $a['value'] - 10*$typeCounts[$a['type']];
        $toReturn = $bValue - $aValue; // DESC

        // update type selected
        if ($toReturn > 0) {
            $typeCounts[$b['type']]++;
        } else {
            $typeCounts[$a['type']]++;
        }

        return $toReturn;
    });

The given example array should result looking [4], [1], [3], [2] Where [3] was chosen over [2] because there are already two elements of type A above him. I assume I can implement my own sort function, or sort the array several times, but was looking for an elegant solution.


text:
Q: length is not working correct in twig Below is my category array containing sub arrays and I want to find length of sub-array of each category array item.
[category] => Array(
[0] => Array(
    [name] => Desktops
    [children] => Array(
        [0] => Array(
            [name] => PC
            [children3] => Array()
            [column] => 1
            [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/desktops/pc
            )
        [1] => Array(
            [name] => Mac
            [children3] => Array()
            [column] => 1
            [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/desktops/mac
            )
        )
    [column] => 1
    [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/desktops
    )
[1] => Array(
    [name] => Laptops & Notebooks
    [children] => Array(
        [0] => Array(
            [name] => Macs
            [children3] => Array()
            [column] => 1
            [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/laptop-notebook/macs
            )
        [1] => Array(
            [name] => Windows
            [children3] => Array()
            [column] => 1
            [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/laptop-notebook/windows
            )
        )
   [column] => 1
   [href] => http://192.168.0.101/user1/opc_laddylike3.0/upload/laptop-notebook
 )

)
I want to find length of children of category array. Please check my code and help if I am wrong.
{% for category in categories %}
{% if category.children %}
{% for n in 0..(category.children|length) %}

Here I am getting category.children length as 1 for all array items.
Thanks in advance


text:
Q: RipperX installed but not showing up in Dash I've just installed RipperX from Synaptic.
The program is installed:-
carl@number5:~$ which ripperx
/usr/bin/ripperx

And will run with ripperx from the terminal.
But it does not appear in the Dash at all.
The closest question to this is this one but that relates to non-GUI applications.
Is there something I need to do to get it to show up in Dash, or is this a bug/problem with RipperX itself?
This question has been suggested as a duplicate but the answer links to this question, which starts with the caveat Please note that right now, most of the information contained below is outdated and cannot be updated. Be careful, most of this won't work on Ubuntu 12.04 and newer. I am running 15.10
Additional:-
carl@number5:~$ sudo find /usr -iname ripperx.desktop
[sudo] password for carl:
/usr/share/applications/ripperx.desktop
carl@number5:~$


text:
Q: VS2015 Enterprise Reverse Engineer Code to UML I'm looking at the various Architecture features of Visual Studio 2015 Enterprise edition.  All looks good.
However, I have code that is all ready written and I would like to generate Class Diagrams from it.  NOT the standard Add Class Diagram in a Project - but from the UML Class Diagrams.  I have created a Modelling Project for this.
I cannot see a way to do this - is it possible?  Can I reverse engineer existing code into nice diagrams?
Here is my solution view:

Here is the Class Diagram Designer:

I can drag and drop projects from Solution Explorer into a Layered Diagram but nothing with classes.  Here is one I made earlier:

I can drag and drop classes into Code Map from Solution Explorer.  It would be nice to have all my modelling in one project.  I really hate the old class diagramming where you add it to a single project.
This seemed to be a feature in previous Ultimate editions.  However, the following Url does not have a link for 2015 (only up to 2013).
MSDN
UPDATE
I installed 2013 Ultimate we have a licence for and indeed all of this functionality is in this version.  Why not 2015 Enterprise?  Can we expect Microsoft is not going to support this no longer and is phasing it out?  Or was it a case of there was no time for 2015 and it will be included in an update.

A: TLDR; at this point Visual Studio 2015+ doesn't have plans to support reverse engineering to the UML class diagram, nor to the UML sequence diagram.
Visual Studio 2015 uses brand new compilers (project Roslyn) for C# and VB, and many features that interact with the code had to be reworked to support the new paradigm.
At the same time, our telemetry data shows that reverse engineering is not used that much. Conversations with customers show that many people are moving to faster release cycles, which means that diagrams go out of date too quickly to be useful.
As such we decided to invest in Class Diagrams (not the UML ones) and in Code Map. Both of these support reverse engineering. Code Map in particular has been worked on to eliminate many bugs and improve performance and scalability, and is the technology of choice for analyzing architecture. Here's an article that shows some scenarios that Code Map is good at.
That said, VS 2013 continues to support these scenarios and you can install it side by side. You can ask for features on UserVoice - there is already a request to bring back sequence diagram reverse engineering.
What were you planning to use Reverse Engineer for?


text:
Q: Defining predicates that are true in $\mathbb{N}$ I am a student taking an introduction to the theory of computation course. We have been introduced the simple induction. I was wondering is it possible to define a predicate that is either true or false for $n$ but always true for $n + 1$ where $n \in\ \mathbb{N}$? In other words: $$\text{Is there a P(n) such that P(n)} \rightarrow \text{P(n + 1) is true?}$$
I know that the truth table for implication states that there are 3 cases where $P \rightarrow Q$ is true:

*

*P is true $\rightarrow$ Q is true $= \ true$

*P is false P is true $\rightarrow$ Q $= \ true$

*P is false P is true $\rightarrow$ Q $= \ true$

What predicates could even exist to describe these three cases?
For example if we let $$\text{P(n): n <= n + 1}$$ then obviously that would be always true but this only describe case 1. How do I describe the other two?
Thanks for your time!

A: Note that if such a predicate is true for some $n$, it must be true for all $m\ge n$, by induction.
Now either $P(n)$ holds for some $n$, or not.

*

*If it does hold for some $n$, let $k$ be the smallest value of $n$ for which $P(n)$ holds. Then $P(n)$ is the predicate which is true precisely if $n \ge k$.  (Note that the predicate that is true for all $n$ is included here as the case when $k=0$.)

*The only other possibility is that  $P(n)$ is  false for all $n$.
These are the only predicates $P$ satisfying the desiderata: Either $P(n)$ is the predicate $n\ge k$ for some constant $k$, or $P(n)$ is the predicate that is always false.


text:
Q: Find Markov policy that minimizes(maximizes) the expected discounted cost(reward) It's an exam problem I found online.Here's a link to the pastpaper.
The problem is stated as follows.
A repairman who services Q facilities moves between location s and
location j according to the transition probability p(j|s). An equipment trailer
which carries parts may be located at any one of M sites. If the trailer is at
site m and the repairman is at facility j, the cost of obtaining material from
the trailer is c(m,j). The cost of moving the trailer from site m to j is d(m,j).
The decision maker's objective is to dynamically relocate the trailer so as to
minimize the expected cost. Assume that the decision maker observes the location of the repairman and trailer, relocates the trailer and then the repairman
moves and services a facility. Formulate this as an infnite horizon discounted
Markov Decision Process problem. Does there exist a Markovian deterministic
policy which is optimal? Justify your answer.
I think it is possible to tackle the problem using the value iteration method. But I am not sure how exactly I can formulate this problem into a Markov decision process.
Any explanation would be appreciated.


text:
Q: Mapping vectors That's could be a newbie question.
There is an abstract function $ \mathbf {h(X_i,X_j)}$
what does mean

for some function h mapping $$\mathbb R^q \times \mathbb R^q \to \mathbb R^p$$ where the q -
  dimensional row vectors $\mathbf X_i$ and $\mathbf X_j$ are the nodal covariate vectors
  for the i-th and j-th individuals.

What happens with vectors X?
Thanks for patience =)


text:
Q: jQuery: How do I reference the @Html.TextBoxFor data in the $('??') of the script? I am trying to reference the textboxfor data in the Script above, any ideas please?
<script type="text/javascript">
    $(document).ready(function () {
        $('??').datepicker();
    });
</script>

<div class="editor-label">
    Date:
    @Html.TextBoxFor(model => model.RTDATE)
</div>

A: @Html.TextBoxFor(model => model.RTDATE) will render an input element with the id and name of RTDATE.
Using jQuery you can get a handle on it using:
$("#RTDATE").datepicker();

A: By default asp.net mvc will generate an input with the same name as your model property.
So in your case above you can do
$("#RTDATE").datepicker();

Here's a quick (although not perfectly formatted) list of the helpers and what they output in html in the default cases.


text:
Q: How make open function use bash instead of sh? I want to use bash instead of sh when I use the open function. For instance:
sub run_cmd {
    my ($cmd) = @_;
    my $fcmd;

    print("Run $cmd\n");

    open($fcmd, "$cmd |");
    while ( my $line = <$fcmd> ) {
        print "-> $line";
    }
    close $fcmd;
}

eval{run_cmd('ps -p $$')};

Here, the output is:
Run ps -p $$
->    PID TTY          TIME CMD
-> 189493 pts/6    00:00:00 sh

We can see sh is used by default.
I have some constraints and I need (1) to use the open function and (2) to call bash instead of sh. I tried simply to add bash at the beginning of my command but it doesn't work:
Run ps -p $$
/bin/ps: /bin/ps: cannot execute binary file

What can I do to use bash with the open function?

A: You can explicitly run bash instead.
open($fcd, "bash -c '$cmd' |");

The other answer indeed shows some important best practices for when cmd is not completely trivial, or not under your control.

A: Don't take your chances with quote injections:
open my $fcmd, '-|', qw(bash -c), $cmd;

(Also notice that you don't need to close $fcmd explicitly if you declared it with my; it will be automatically closed at the end of the block; perl is not java ;-))


text:
Q: unable to access the manually created assets folder with Java class using Java Library
Getting below error as-
java.lang.RuntimeException: Font asset not found arial.ttf

A:
Try to create a assest folder like this then put your font file in it, then it will work.

Your asset file structure should show like this [Icon under the file name], yours seems like normal folder.


text:
Q: Hierarchical forecasting in python with scikit-hts leads to Invalid frequency error I'm working with scikit-hts. Here's some code with a small df and hierarchy to get us started (after pip install scikit-hts[auto_arima]:
import hts
import pandas as pd

hierarchy_df = hierarchy_df_test = pd.DataFrame({'date':['1998-01-01', '1998-02-01', '1998-03-01', '1998-04-01', '1998-05-01', '1998-06-01', '1998-07-01', '1998-08-01', '1998-09-01', '1998-10-01', '1998-11-01', '1998-12-01', '1999-01-01', '1999-02-01'], 'total': [21, 40, 31, 21, 29, 40, 30, 21, 24, 30, 40, 22, 32, 32], 'A':[10,20,15,10,14,20,16,10,12,16,20,10,18,16], 'B':[11,20,16,11,15,20,14,11,12,14,20,12,14,16]})

hierarchy = {'total': ['A', 'B']}

I want to convert the dates to a datetime object so I run
hierarchy_df['date'] = pd.to_datetime(hierarchy_df['date'], format='%Y-%m-%d')

Now I do the model fit with auto_arima and 'OLS' as the revision method:
model_ols_arima = hts.HTSRegressor(model='auto_arima', revision_method='OLS', n_jobs=0)
model_ols_arima = model_ols_arima.fit(hierarchy_df, hierarchy)

Everything runs smoothly until I try to predict:
pred_ols_arima = model_ols_arima.predict(steps_ahead=4)

At which point I get a 'ValueError: Invalid frequency: 1'.
Here's the full error:
TypeError                                 Traceback (most recent call last)
/local_disk0/.ephemeral_nfs/envs/pythonEnv-a9bf3a0d-a93e-453d-890b-d123f282d710/lib/python3.8/site-packages/hts/core/regressor.py in _get_predict_index(self, steps_ahead)
    369         try:
--> 370             start = self.nodes.item.index[-1] + timedelta(freq)
    371             end = self.nodes.item.index[-1] + timedelta(steps_ahead * freq)

TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<command-2268273946901309> in <module>
----> 1 pred_ols_arima = model_ols_arima.predict(steps_ahead=4)

/local_disk0/.ephemeral_nfs/envs/pythonEnv-a9bf3a0d-a93e-453d-890b-d123f282d710/lib/python3.8/site-packages/hts/core/regressor.py in predict(self, exogenous_df, steps_ahead, distributor, disable_progressbar, show_warnings, **predict_kwargs)
    350             self.hts_result.errors = (key, error)
    351             self.hts_result.residuals = (key, residual)
--> 352         return self._revise(steps_ahead=steps_ahead)
    353
    354     def _revise(self, steps_ahead: int = 1) -> pandas.DataFrame:

/local_disk0/.ephemeral_nfs/envs/pythonEnv-a9bf3a0d-a93e-453d-890b-d123f282d710/lib/python3.8/site-packages/hts/core/regressor.py in _revise(self, steps_ahead)
    361
    362         revised_columns = list(make_iterable(self.nodes))
--> 363         revised_index = self._get_predict_index(steps_ahead=steps_ahead)
    364         return pandas.DataFrame(revised, index=revised_index, columns=revised_columns)
    365

/local_disk0/.ephemeral_nfs/envs/pythonEnv-a9bf3a0d-a93e-453d-890b-d123f282d710/lib/python3.8/site-packages/hts/core/regressor.py in _get_predict_index(self, steps_ahead)
    374             start = self.nodes.item.index[-1] + freq
    375             end = self.nodes.item.index[-1] + (steps_ahead * freq)
--> 376             future = pandas.date_range(freq=freq, start=start, end=end)
    377
    378         return self.nodes.item.index.append(future)

/databricks/python/lib/python3.8/site-packages/pandas/core/indexes/datetimes.py in date_range(start, end, periods, freq, tz, normalize, name, closed, **kwargs)
   1067         freq = "D"
   1068
-> 1069     dtarr = DatetimeArray._generate_range(
   1070         start=start,
   1071         end=end,

/databricks/python/lib/python3.8/site-packages/pandas/core/arrays/datetimes.py in _generate_range(cls, start, end, periods, freq, tz, normalize, ambiguous, nonexistent, closed)
    375                 "and freq, exactly three must be specified"
    376             )
--> 377         freq = to_offset(freq)
    378
    379         if start is not None:

pandas/_libs/tslibs/offsets.pyx in pandas._libs.tslibs.offsets.to_offset()

pandas/_libs/tslibs/offsets.pyx in pandas._libs.tslibs.offsets.to_offset()

ValueError: Invalid frequency: 1

I did some research and it seems the problem lies in the frequency of date, but I'm unable to resolve the problem. This tutorial here more or less does the same thing (with a larger data set), but without the error. Any help would be much appreciated. Thanks!

A: I was able to resolve the error here by setting the date column as index:
hierarchy_df = hierarchy_df.set_index('date')

Once this was done, the predict() line ran without any errors.


text:
Q: Why is in PHP/.NET CMS all pages are build using ?id= and not direct php page In PHP/.NET we generally see that all the pages on web site are displayed using one php file with id parameter. eg. http://example.org/content.php?id=90. We know that every page can be built independently like http://example.org/1.php , 2.php etc etc. so why is single page entrusted with responsibility of displaying all the pages with an id parameter? This behavior is prevalent in many .NET web sites also.
Br,
Hemanshu.

A: This is generally what a CMS does:
Lets say we have three modules (page elements):
1 form
2 top menu bar
3 left menu bar
Now you have to make page, which requires all of them, if you do it statically (in a single .html/.php file) it will be easy just save module contents as main.php and make a link to the page.
But then you have to make another page, which still requires the top menu but doesn't need the form and the side menu has few more sections. You cannot load main.php so this way, you'll have to make different page with duplicated main menu section.
Instead of doing all that, it is much easier if you have one content.php file, that will low only the needed modules and module elements (i.e. side bar additional sections in the above case) and only when it is needed.


text:
Q: WCF how can I avoid faulted channels if they are closed by server due to inactivity My service host is configured to close connection after 10 mins
<wsHttpBinding>
    <binding receiveTimeout="00:10:00">
</wsHttpBinding>

In my client code before using service it is validated. If it is in closed/faulted state it will create a new one.
    public static T ValidateService<T>(ref T service) where T : class
    {
        if (service is IClientChannel)
        {
            IClientChannel channel = service as IClientChannel;
            CommunicationState state = channel.State;
            if (state == CommunicationState.Faulted || state == CommunicationState.Closed)
            {
                // thread safe logic to create new service
            }
        }
    }

Problem is when channel is closed on server side and channel.State will still return Open state. After I do remote call I get faulted exception and due to receiveTimeout.
Is there any way to have inactivity timeout on client side? something like  receiveTimeout="00:10:00" on server but with few seconds less so I can nicely close a channel from client if not used and than my ValidateService<T> logic will create a new one if needed.
For performance reasons I do not want to create new channel for every remote call because those can be very frequent.
I would like to avoid having heart beat poller for each of my services I am using in my communication.
Thanks

A: You can't avoid handling Faulted and Closed since it is always possible that some network problem or similar leads to a situation where you have to create a new Channel...
EDIT - as per comment:
In production I usually have a client implementation which handles certain exceptions by recreating the Channel and retrying... this takes care of the case you are describing and several other cases like network hickup etc.


text:
Q: How to make a new JSON string from original string by extracting few fields from it? I have a JSON String like this:
{"customerid":null,"clientid":"123456","test_id":"98765","pet_id":0,"qwer_id":0,"timestamp":1411811583000}

I need to make another JSON String like this:
{"customerid":"System.nanoTime()","test_id":"98765","timestamp":1411811583000}

So basically given an original JSON String, I need to extract "customerid", "test_id" and "timestamp" only and then make a new JSON string out of it. Also, value of "customerid" in new json I will make value of System.nanoTime().
Below is my code:
JsonObject originalJSONString = new JsonObject();

// some code here

Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println(gson.toJson(originalJSONString));

// make a new JSON String now

I am using GSON in my example. I am confuse how to extract relevant fields which I am interested from original json and then make a new json out of it?

A: Assuming that originalJSONString represents
{"customerid":null,"clientid":"123456","test_id":"98765","pet_id":0,"qwer_id":0,"timestamp":1411811583000}

you can try with something like
JsonObject newJsonObject = new JsonObject();

newJsonObject.addProperty("customerid", "System.nanoTime()");//new property
newJsonObject.add("test_id", originalJSONString.get("test_id"));//copy property
newJsonObject.add("timestamp", originalJSONString.get("timestamp"));//copy property

System.out.println(gson.toJson(newJsonObject));

Output: {"customerid":"System.nanoTime()","test_id":"98765","timestamp":1411811583000}

A: you can convert the JSON string to a map and then get only the key/values that you need.
something like:
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

....

//convert JSON string to Map
map = mapper.readValue(jsonString, new TypeReference<HashMap<String,String>>(){});

...

//add key and values in a new one
JsonObject newJsonObject = new JsonObject();


text:
Q: Delete interface open camera on Android studio I really need help here. I have project which call MyHeartRate, I downloaded the source code of heart rate project at Github. So I try to run that source code and there is no error. In the interface layout, it display the "camera". Example, when you open your camera then you will see the screen focus on what area that you want to take the picture. So my problem is, I want to remove that "camera" in my layout. I need to know which code need to be delete so then the "camera" not in my layout.
here's my code
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout">
<LinearLayout android:id="@+id/top"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="50dp">
    <TextView android:id="@+id/text"
        android:text="@string/default_text"
        android:textSize="32dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <com.jwetherell.heart_rate_monitor.HeartbeatView android:id="@+id/image"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </com.jwetherell.heart_rate_monitor.HeartbeatView>
    </RelativeLayout>
</LinearLayout>
<SurfaceView android:id="@+id/preview"
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="0dp">
</SurfaceView>

java file(HeartRateMonitor)
public class HeartRateMonitor extends Activity {

private static final String TAG = "HeartRateMonitor";
private static final AtomicBoolean processing = new AtomicBoolean(false);

private static SurfaceView preview = null;
private static SurfaceHolder previewHolder = null;
private static Camera camera = null;
private static View image = null;
private static TextView text = null;

private static WakeLock wakeLock = null;

private static int averageIndex = 0;
private static final int averageArraySize = 4;
private static final int[] averageArray = new int[averageArraySize];

public static enum TYPE {
    GREEN, RED
};

private static TYPE currentType = TYPE.GREEN;

public static TYPE getCurrent() {
    return currentType;
}

private static int beatsIndex = 0;
private static final int beatsArraySize = 3;
private static final int[] beatsArray = new int[beatsArraySize];
private static double beats = 0;
private static long startTime = 0;

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

    preview = (SurfaceView) findViewById(R.id.preview);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    image = findViewById(R.id.image);
    text = (TextView) findViewById(R.id.text);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

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

    wakeLock.acquire();

    camera = Camera.open();

    startTime = System.currentTimeMillis();
}

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

    wakeLock.release();

    camera.setPreviewCallback(null);
    camera.stopPreview();
    camera.release();
    camera = null;
}

private static PreviewCallback previewCallback = new PreviewCallback() {

    @Override
    public void onPreviewFrame(byte[] data, Camera cam) {
        if (data == null) throw new NullPointerException();
        Camera.Size size = cam.getParameters().getPreviewSize();
        if (size == null) throw new NullPointerException();

        if (!processing.compareAndSet(false, true)) return;

        int width = size.width;
        int height = size.height;

        int imgAvg = ImageProcessing.decodeYUV420SPtoRedAvg(data.clone(), height, width);
        // Log.i(TAG, "imgAvg="+imgAvg);
        if (imgAvg == 0 || imgAvg == 255) {
            processing.set(false);
            return;
        }

        int averageArrayAvg = 0;
        int averageArrayCnt = 0;
        for (int i = 0; i < averageArray.length; i++) {
            if (averageArray[i] > 0) {
                averageArrayAvg += averageArray[i];
                averageArrayCnt++;
            }
        }

        int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
        TYPE newType = currentType;
        if (imgAvg < rollingAverage) {
            newType = TYPE.RED;
            if (newType != currentType) {
                beats++;
                // Log.d(TAG, "BEAT!! beats="+beats);
            }
        } else if (imgAvg > rollingAverage) {
            newType = TYPE.GREEN;
        }

        if (averageIndex == averageArraySize) averageIndex = 0;
        averageArray[averageIndex] = imgAvg;
        averageIndex++;

        // Transitioned from one state to another to the same
        if (newType != currentType) {
            currentType = newType;
            image.postInvalidate();
        }

        long endTime = System.currentTimeMillis();
        double totalTimeInSecs = (endTime - startTime) / 1000d;
        if (totalTimeInSecs >= 10) {
            double bps = (beats / totalTimeInSecs);
            int dpm = (int) (bps * 60d);
            if (dpm < 30 || dpm > 180) {
                startTime = System.currentTimeMillis();
                beats = 0;
                processing.set(false);
                return;
            }

            // Log.d(TAG,
            // "totalTimeInSecs="+totalTimeInSecs+" beats="+beats);

            if (beatsIndex == beatsArraySize) beatsIndex = 0;
            beatsArray[beatsIndex] = dpm;
            beatsIndex++;

            int beatsArrayAvg = 0;
            int beatsArrayCnt = 0;
            for (int i = 0; i < beatsArray.length; i++) {
                if (beatsArray[i] > 0) {
                    beatsArrayAvg += beatsArray[i];
                    beatsArrayCnt++;
                }
            }
            int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
            text.setText(String.valueOf(beatsAvg));
            startTime = System.currentTimeMillis();
            beats = 0;
        }
        processing.set(false);
    }
};

private static SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
            camera.setPreviewCallback(previewCallback);
        } catch (Throwable t) {
            Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        Camera.Size size = getSmallestPreviewSize(width, height, parameters);
        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
        }
        camera.setParameters(parameters);
        camera.startPreview();
    }

   @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Ignore
    }
};

private static Camera.Size getSmallestPreviewSize(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;
}

}
tq,
faizal

A: I found the answer. just comment this code
//preview = (SurfaceView) findViewById(R.id.preview);
//previewHolder = preview.getHolder();
//previewHolder.addCallback(surfaceCallback);
//previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

done.


text:
Q: In .NET is there a thread scheduler for long running threads? Our scenario is a network scanner.
It connects to a set of hosts and scans them in parallel for a while using low priority background threads.
I want to be able to schedule lots of work but only have any given say ten or whatever number of hosts scanned in parallel.  Even if I create my own threads, the many callbacks and other asynchronous goodness uses the ThreadPool and I end up running out of resources.  I should look at MonoTorrent...
If I use THE ThreadPool, can I limit my application to some number that will leave enough for the rest of the application to Run smoothly?
Is there a threadpool that I can initialize to n long lived threads?
[Edit]
No one seems to have noticed that I made some comments on some responses so I will add a couple things here.

*

*Threads should be cancellable both
gracefully and forcefully.

*Threads should have low priority leaving the GUI responsive.

*Threads are long running but in Order(minutes) and not Order(days).

Work for a given target host is basically:
  For each test
    Probe target (work is done mostly on the target end of an SSH connection)
    Compare probe result to expected result (work is done on engine machine)
  Prepare results for host

Can someone explain why using SmartThreadPool is marked wit ha negative usefulness?

A: In .NET 4 you have the integrated Task Parallel Library. When you create a new Task (the new thread abstraction) you can specify a Task to be long running. We have made good experiences with that (long being days rather than minutes or hours).
You can use it in .NET 2 as well but there it's actually an extension, check here.
In VS2010 the Debugging Parallel applications based on Tasks (not threads) has been radically improved. It's advised to use Tasks whenever possible rather than raw threads. Since it lets you handle parallelism in a more object oriented friendly way.
UPDATE
Tasks that are NOT specified as long running, are queued into the thread pool (or any other scheduler for that matter).
But if a task is specified to be long running, it just creates a standalone Thread, no thread pool is involved.

A: The CLR ThreadPool isn't appropriate for executing long-running tasks: it's for performing short tasks where the cost of creating a thread would be nearly as high as executing the method itself. (Or at least a significant percentage of the time it takes to execute the method.) As you've seen, .NET itself consumes thread pool threads, you can't reserve a block of them for yourself lest you risk starving the runtime.
Scheduling, throttling, and cancelling work is a different matter. There's no other built-in .NET worker-queue thread pool, so you'll have roll your own (managing the threads or BackgroundWorkers yourself) or find a preexisting one (Ami Bar's SmartThreadPool looks promising, though I haven't used it myself).

A: In your particular case, the best option would not be either threads or the thread pool or Background worker, but the async programming model (BeginXXX, EndXXX) provided by the framework.
The advantages of using the asynchronous model is that the TcpIp stack uses callbacks whenever there is data to read and the callback is automatically run on a thread from the thread pool.
Using the asynchronous model, you can control the number of requests per time interval initiated and also if you want you can initiate all the requests from a lower priority thread while processing the requests on a normal priority thread which means the packets will stay as little as possible in the internal Tcp Queue of the networking stack.
Asynchronous Client Socket Example - MSDN
P.S. For multiple concurrent and long running jobs that don't do allot of computation but mostly wait on IO (network, disk, etc) the better option always is to use a callback mechanism and not threads.

A: I'd create your own thread manager. In the following simple example a Queue is used to hold waiting threads and a Dictionary is used to hold active threads, keyed by ManagedThreadId. When a thread finishes, it removes itself from the active dictionary and launches another thread via a callback.
You can change the max running thread limit from your UI, and you can pass extra info to the ThreadDone callback for monitoring performance, etc. If a thread fails for say, a network timeout, you can reinsert back into the queue. Add extra control methods to Supervisor for pausing, stopping, etc.
using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApplication1
{
    public delegate void CallbackDelegate(int idArg);

    class Program
    {
        static void Main(string[] args)
        {
            new Supervisor().Run();
            Console.WriteLine("Done");
            Console.ReadKey();
        }
    }

    class Supervisor
    {
        Queue<System.Threading.Thread> waitingThreads = new Queue<System.Threading.Thread>();
        Dictionary<int, System.Threading.Thread> activeThreads = new Dictionary<int, System.Threading.Thread>();
        int maxRunningThreads = 10;
        object locker = new object();
        volatile bool done;

        public void Run()
        {
            // queue up some threads
            for (int i = 0; i < 50; i++)
            {
                Thread newThread = new Thread(new Worker(ThreadDone).DoWork);
                newThread.IsBackground = true;
                waitingThreads.Enqueue(newThread);
            }
            LaunchWaitingThreads();
            while (!done) Thread.Sleep(200);
        }

        // keep starting waiting threads until we max out
        void LaunchWaitingThreads()
        {
            lock (locker)
            {
                while ((activeThreads.Count < maxRunningThreads) && (waitingThreads.Count > 0))
                {
                    Thread nextThread = waitingThreads.Dequeue();
                    activeThreads.Add(nextThread.ManagedThreadId, nextThread);
                    nextThread.Start();
                    Console.WriteLine("Thread " + nextThread.ManagedThreadId.ToString() + " launched");
                }
                done = (activeThreads.Count == 0) && (waitingThreads.Count == 0);
            }
        }

        // this is called by each thread when it's done
        void ThreadDone(int threadIdArg)
        {
            lock (locker)
            {
                // remove thread from active pool
                activeThreads.Remove(threadIdArg);
            }
            Console.WriteLine("Thread " + threadIdArg.ToString() + " finished");
            LaunchWaitingThreads(); // this could instead be put in the wait loop at the end of Run()
        }
    }

    class Worker
    {
        CallbackDelegate callback;
        public Worker(CallbackDelegate callbackArg)
        {
            callback = callbackArg;
        }

        public void DoWork()
        {
            System.Threading.Thread.Sleep(new Random().Next(100, 1000));
            callback(System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
    }
}

A: Use the built-in threadpool. It has good capabilities.
Alternatively you can look at the Smart Thread Pool implementation here or at Extended Thread Pool for a limit on the maximum number of working threads.


text:
Q: CodeIgniter 2.x generate pdf then redirect page I have problem with redirect page in codeigniter. to the point :
I have 2 functions in one controllers like below :

*

*function to generate pdf (download)
function generate_sprint()
{
$tanggal = mdate('%d');
$tahun = mdate('%Y');
$bulan = mdate('%m');
$tanggal_masuk = $this->input->post('tanggal_masuk');
$bulan_masuk = $this->input->post('bulan_masuk');
$tahun_masuk = $this->input->post('tahun_masuk');

$no_spt = '1';
$bln_spt = $bulan;
$thn_spt = $tahun;
$data['no_spt'] = 'No : ' . $no_spt . ' / CSI - HRD / SPT / ' .$bln_spt. ' / ' . $thn_spt;
$data['waktu'] = "".$tanggal." ".$bln." ".$tahun;
$data['creator'] = $this->session->userdata('nama');
$data['nik'] = $this->app_model->GenerateNIK();
$data['jabatan'] = $this->input->post('jabatan');
$data['nama'] = $this->input->post('nama');
$data['tgl_masuk'] = $tanggal_masuk." ".$bln." ".$tahun_masuk;
$data['site_name'] = $this->app_model->CekSiteName();

$info =  "".$data['nik']." , ".$data['nama']." , ".$data['jabatan'];
$this->load->library('ciqrcode');
$params['data'] = $info;
$params['level'] = 'H';
$params['size'] = 5;
$params['savename'] = FCPATH.'MyCode.png';
$bar = $this->ciqrcode->generate($params);

$data['barcode'] = $bar;
$this->load->view('karyawan/generate_sprint', $data);
}

*function for processing data (input)
$this->app_model->insertData("biodata_karyawan",$in);
$this->app_model->insertData("absensi_karyawan",$in2);
                                            $this->generate_sprint();    --> this is for execute generate pdf
redirect(base_url() . 'karyawan_front/tambah/' . $site, 'refresh' ); --> after that the page will be direct
Can someone help me?
thanks for your time guys...
Regards


text:
Q: How to apply HSB color filters to UIImage I've been struggling for a few days for a project on UIImage colorization.
The idea is that the app will embark a set of images that I will have to colorize with values retrieved from a webservice. Some sort of themes if you wish.
The designer I work with gave me a background image on all of his Photoshop values.
The first problem is that Photoshop uses HSL and iOS uses HSB. So the first challenge was to translate the values from Photoshop.
Photoshop HSL: -28 (range -180 => +180), 100 (range -100 => +100), 25 (range -100 => +100).
Luckily I found some code online, here it is.
//adapted from https://gist.github.com/peteroupc/4085710
- (void)convertLightnessToBrightness:(CGFloat)lightness withSaturation:(CGFloat)saturation completion:(void (^)(CGFloat, CGFloat))completion
{
    if (!completion)
        return; //What's the point of calling this method without a completion block!

    CGFloat brightness = 0.0f;
    CGFloat saturationOut = 0.0f;

    if (lightness > 0.0f)
    {
        CGFloat lumScale = (1.0f - MAX((lightness - 0.5f), 0.0f) * 2.0f);
        lumScale = ((lumScale == 0) ? 0 : (1.0f / lumScale));

        CGFloat lumStart = MAX(0.0f, (lumScale - 0.5f));

        CGFloat lumDiv = (lumScale - lumStart);
        lumDiv = (lumStart + (saturation * lumDiv));

        saturationOut = ((lumDiv == 0) ? 0.0f : (saturation / lumDiv));
        brightness = (lightness + (1.0f - lightness) * saturation);
    }

    NSLog(@"saturation: %0.2f - brightness: %0.2f", saturationOut, brightness);

    completion(saturationOut, brightness);
}

Using an online converter I verified that this method returns the good values.
I needed to change the ranges (H: 0->360, S: 0->100, L: 0->100)

So HSL 152, 100, 62 gives HSB 152, 76, 100. And the method returns 75 for saturation and 100 for brightness so we are good.
Next I needed to apply those values to the image, so here is the code to change...
The HUE:
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0f * M_PI)

- (void)colorize:(UIImage *)input hue:(CGFloat)hueDegrees completion:(void(^)(UIImage *outputHue))completion
{
    if (!completion)
        return; //What's the point of calling this method without a completion block!

    CGFloat hue = DEGREES_TO_RADIANS(hueDegrees);

    NSLog(@"degress: %0.2f | radian: %0.2f", hueDegrees, hue);

    CIImage *inputImage = [CIImage imageWithCGImage:input.CGImage];

    //---
    CIFilter *hueFilter = [CIFilter filterWithName:@"CIHueAdjust" keysAndValues:kCIInputImageKey, inputImage, nil];
    [hueFilter setDefaults];
    [hueFilter setValue:[NSNumber numberWithFloat:hue] forKey:kCIInputAngleKey];
    //---

    CIImage *outputImage = [hueFilter outputImage];
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *outputUIImage = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);

    completion(outputUIImage);
}

The SATURATION:
- (void)colorize:(UIImage *)input saturation:(CGFloat)saturation completion:(void(^)(UIImage *outputSaturation))completion
{
    if (!completion)
        return; //What's the point of calling this method without a completion block!

    NSLog(@"saturation: %0.2f", saturation);

    CIImage *inputImage = [CIImage imageWithCGImage:input.CGImage];

    //---
    CIFilter *saturationFilter = [CIFilter filterWithName:@"CIColorControls" keysAndValues:kCIInputImageKey, inputImage, nil];
    [saturationFilter setDefaults];
    [saturationFilter setValue:[NSNumber numberWithFloat:saturation] forKey:@"inputSaturation"];
    //---

    CIImage *outputImage = [saturationFilter outputImage];
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *outputUIImage = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);

    completion(outputUIImage);
}

The BRIGHTNESS:
- (void)colorize:(UIImage *)input brightness:(CGFloat)brightness completion:(void(^)(UIImage *outputBrightness))completion
{
    if (!completion)
        return; //What's the point of calling this method without a completion block!

    NSLog(@"brightness: %0.2f", brightness);

    CIImage *inputImage = [CIImage imageWithCGImage:input.CGImage];

    //---
    CIFilter *brightnessFilter = [CIFilter filterWithName:@"CIColorControls" keysAndValues:kCIInputImageKey, inputImage, nil];
    [brightnessFilter setDefaults];
    [brightnessFilter setValue:[NSNumber numberWithFloat:brightness] forKey:@"inputBrightness"];
    //---

    CIImage *outputImage = [brightnessFilter outputImage];
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *outputUIImage = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);

    completion(outputUIImage);
}

And everything put together:
CGFloat hue = -28.0f; //152 in 360° range (180 - 28 = 152)
CGFloat saturation = 1.0f; //((100 + 100.0f) / 200.0f)
CGFloat lightness = 0.625f; //((25 + 100.0f) / 200.0f)

[self convertLightnessToBrightness:ligthness withSaturation:saturation completion:^(CGFloat saturationOut, CGFloat brightness) {

    //saturarationOut = 0.75f and brigthness = 1.0f
    [self colorize:input hue:hue completion:^(UIImage *outputHue) {

        [self colorize:outputHue saturation:saturationOut completion:^(UIImage *outputSaturation) {

            [self colorize:outputSaturation brightness:brightness completion:completion];

        }];

    }];

}];

The last completion block simply applies the output image to the image view.
Now here are the results:
Base image

Colorize (hue only)

Colorize (hue and saturation)

Colorize (hue, saturation and brightness)

Expected result

As you can see, the final image is completely white (brigthness is 100%).
I'm completely lost here, I've tried many combination (applying H, S and B in every order), I've tried others libs such as iOS-Image-Filters, without any success. I've also read a lot of question here on Stack Overflow.
Links:

*

*Core Image Filter Reference

*CIHueAdjust core image filter setup

*How to programmatically change the hue of UIImage?

*iOS: Values for CIFilter (Hue) from Photoshop
As anyone succeeded to apply HSL/HSB value to UIImages?

A: Well finally, we decided to change techniques.
I'm now using a semi-transparent image to wich I apply a blend mode with the desired color.
Following this post I made a category on UIImage.
- (UIImage *)tintedBackgroundImageWithColor:(UIColor *)tintColor
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);

    [self drawInRect:bounds blendMode:kCGBlendModeSourceAtop alpha:1.0f];

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return tintedImage;
}


text:
Q: Why switching between two Tasks does not update file edited in these Tasks? What is Task in PhpStorm about? These are steps I did:

*

*open task 1 (create branch from master, create changelist)

*do some edit in thefile

*open task 2 (create branch from master, create changelist)

*do some edit in thefile

*switching to task 1 and thefile contain edits made in task 2

So content of thefile is always the same in both tasks.
Why switching between two Tasks does not update file edited in these Tasks? What is Task in PhpStorm about?


text:
Q: Cause of neo4j IndexOutOfBoundsException on getRelationships() This is happening in neo4j version 2.3.0-M02
Why might this code ....
Iterable<Relationship> rels = node.getRelationships( ... any various args ... );
for (Relationship rel : rels) {
    // Some computation
}

... cause this stack trace ?
Caused by: java.lang.IndexOutOfBoundsException
    at org.neo4j.io.pagecache.impl.muninn.MuninnPageCursor.setOffset(MuninnPageCursor.java:410)
    at org.neo4j.kernel.impl.store.RelationshipGroupStore.getRecord(RelationshipGroupStore.java:117)
    at org.neo4j.kernel.impl.store.RelationshipGroupStore.getRecord(RelationshipGroupStore.java:77)
    at org.neo4j.kernel.impl.api.StoreRelationshipIterable$DenseIterator.<init>(StoreRelationshipIterable.java:214)
    at org.neo4j.kernel.impl.api.StoreRelationshipIterable.iterator(StoreRelationshipIterable.java:96)
    at org.neo4j.kernel.impl.api.StoreRelationshipIterable.iterator(StoreRelationshipIterable.java:76)
    at org.neo4j.kernel.impl.api.store.DiskLayer.nodeListRelationships(DiskLayer.java:241)
    at org.neo4j.kernel.impl.api.store.CacheLayer.nodeListRelationships(CacheLayer.java:424)
    at org.neo4j.kernel.impl.api.StateHandlingStatementOperations.nodeGetRelationships(StateHandlingStatementOperations.java:925)
    at org.neo4j.kernel.impl.api.StateHandlingStatementOperations.nodeGetRelationships(StateHandlingStatementOperations.java:933)
    at org.neo4j.kernel.impl.api.ConstraintEnforcingEntityOperations.nodeGetRelationships(ConstraintEnforcingEntityOperations.java:426)
    at org.neo4j.kernel.impl.api.OperationsFacade.nodeGetRelationships(OperationsFacade.java:361)
    at org.neo4j.kernel.impl.core.NodeProxy$2.iterator(NodeProxy.java:194)
    at org.neo4j.kernel.impl.core.NodeProxy$2.iterator(NodeProxy.java:186)

Update:

*

*Issue #5691 on Github

*Same bug again in version 2.3.0

A: You should upgrade to Neo4j 2.3.0-M03.
Milestone releases tend to be unstable and you are using old one. It is known that M02 has bugs, and lot of them are fixed in M03.
So, upgrade and check if this works for you.


text:
Q: typescript extends interface Подскажите, почему в Intellisence VSCode всплывает IEntity вместо расширенного интерфейса? Обойти получается только с generic types.
Можно ли получать то же самое только без generic types?
В js скрипте Channel получает в __proto__ методы Entity, соответственно this в них - Channel. Но базовый интерфейс не переопределяется на расширенный в методах.
Channel.prototype.method = Entity.method

Компилируется с ошибкой, т.к. воспринимает channel as IEntity
file.ts:52:48 - error TS2339: Property 'hangup' does not exist on type 'IEntity'.

Если что, это тайпинг для node-ari-client

A: Разобрался.
Ts поддерживает в тайпингах this.
    interface IEntity {
        on(eventName: TeventType, cb: TEventCb<this>): void
    }

Может это кому-нибудь поможет.