text:
Q: passport js vs firebase authentication system Is there any valid reason to use passport js based authentication using express js in backend over firebase authentication system in frontend using react?
just explored passport js and want to know before using in a MERN Stack project

A: PassportJS is just an authentication middleware that can be used with different authentication strategies. If I understood you correctly you might be comparing Passport's local strategy with Firebase auth's username/password one, in this case:
My answer would be a classical "IT DEPENDS", first I will answer the first part:
Why use Firebase-auth (or any other third-party authentication service)

Authentication is hard, and you may not want to deal with it on your own (most of the time).

If you are planning to use a "local" authentication strategy with a username/email and a password, you might need to consider and maintain a set of best practices to avoid having a broken-authentication system, you will need to encrypt your passwords and ensure that they're safe on at-rest and in-transit, you also want to ensure that your system uses libraries or logic to avoid timing attacks. Also, you may need to consider forcing some rules on password lengths and that they're not too weak (ex: they belong to a list of most-known passwords)...
Besides these, you may also want to implement password recovery mechanisms, email change, and maybe "Email confirmation" logic which might be tricky sometimes.
Did I forget to mention reCaptcha and 2FA? Bots are getting smarter nowdays.
I definitely missed some other best practices or risks that should be considered when not using a managed service like Firebase-auth.
These services are built by people who only care about "Authentication" for you.
Firebase-auth is not the only service, you may want to look into other options like auth0.
Of course, this option is not the cheapest in terms of cost and flexibility. Firebase auth has a generous free tier, but it will be paid when your application grows, see: https://firebase.google.com/pricing.
So, if you go with this option, consider organizing your application code to be easily decoupled from Firebase in case you wanted to migrate from it someday.
Why use Passport-local
Using the middleware on your own means that you will have more flexibility in managing your different authentication strategies and you will only pay an extra cost of maintaining your application's authentication logic (which might be high as you need to keep in mind the best practices and risks)
Other considerations
This depends on your use case, and your team:

*

*You may look into some services that handle the authentication out of the box like Keycloak

*Use Passport.js as a core library but with strategies like Auth0's (https://www.passportjs.org/packages/passport-auth0/)


text:
Q: Create Windows Installation Media with Updates I often need to install a specific version of Windows 10 from a flash drive; however, the problem is that after I install it, it needs to install security updates from the internet, which takes an extraordinarily long time since there have been so many security updates since the release of this version.
I'm wondering; is it possible to install Windows from a flash drive with these security updates already installed (obviously not accounting for future updates)? If so, how?

redpajama_set_name: RedPajamaStackExchange


text: Q: How to run a Universal Windows Application as a daemon? I have a C# Console application that needs to open and run a Universal Windows Application in the background. Universal Windows Applications do not have .exe's so I cannot seem to use System.Diagnostics.Process like I normally would with another exe. How can I open the Universal Windows Application from a Console application and read Debug.WriteLine from it ?


text:
Q: How to run Node.js jobs routines Right now I have a weekly email job that works by first checking a last_email_sent timestamp against the current time, it then uses setTimeout to schedule a routine that is exactly a week from the last_email_sent timestamp. If the process ever restarts, the setTimeout would be queued again but the interval would of course be smaller. This works for a weekly email job, but is there a better way to handle jobs in node.js? Maybe there's a module out there that can let me manage my jobs that I'm not aware of.

A: There's a handy module in npmjs.org called node-cron.
It'll give you more flexibility.

A: Many of the modules listed in the node.js wiki under "Message Queues" will help with this type of system. Being a TJ Holowaychuck fanboy, I myself would probably first look at Kue.


text:
Q: Hum Cancelling Circuit Consider the following circuit:

I was just thinking about how connecting consumer grade unbalanced electronics together has a tendency to generate hum. For example, I have a little mixer that has an SMPS supply and some unbalanced outboard gear that has it's own supply and a guitar FX thing that has it's own SMPS and unbalanced output. Computer audio is always a good source of hum as well.
Normally, the proper solution for this sort of problem is to use an active balanced circuit or maybe even transformers if one can afford it. But with short runs of cable between unbalanced gear, the problem is not noise induced in the cables, it's ground loops. The grounds of each peice of gear are bouncing around at different potentials. So I really just need to isolate the grounds.
To explore this with LTSpice I created the above circuit. V2 is suppose to simulate hum (although 6.5kHz was used instead of 60Hz just so that I could see the effect visually in the waveform). So the idea is very simple, instead of connecting the grounds together, they are isolated using a 10k resistor (R7) and then any AC is coupled to the non-inverting input through C1 thereby canceling out the ground loop hum.
This seems to work. The model is not perfect because when you plot something it is always relative to the one ground. But the op amp out has the hum and the net between R5 R6 is clean. So the hum is actually being canceled.
So the question is, would the circuit above work in practice? Is there a circuit like this that is used in practice? If yes, can you point to a schematic?

A: My first concern would be what would happen if you had two channels. Remember that the ground is usually common. If you try to separate it in one side, it will most certainly be joined on the other. Then your two circuits will be fighting one another, which I suspect would make things unstable.
My second concern would be what would happen on the corner frequency. Have you tried an AC simulation?
My third concern is (an this is just a hunch) common mode gain. I haven't thought it through, but this reminds me of a differential amplifier with imbalanced resistors and those exhibit common mode gain.


text:
Q: How to properly wait while `GET` returns the completion status equal to 0 I need to use API that performs a task in two steps:

*

*POST request: to submit a task and get back the results URL

*GET request: to check for a status of the results URL and get the result when the status is "completed"

Below I provide my implementation. However, I don't know how to perform the waiting while GET returns the completion status equal to 0.
import requests

url = "https://xxx"

headers = {"Content-Type": "application/json", "Ocp-Apim-Subscription-Key": "xxx"}

body = {...}

response = requests.post(url, headers=headers, json=body)

status_code = response.status_code
url_result = response.headers['url-result']

# Step 2
s2_result = requests.get(url_result, headers=headers)
s2_result = s2_result.json()
s2_result_status = s2_result['completed']
if s2_result_status == 1:
# ...
else:
# wait 1 second and repeat

A: You need to repeat the get in a loop. I suggest you use Session() to prvent connection errors
with requests.Session() as s:
    c = 0
    while c < 10: # add a limit
        s2_result = s.get(url_result, headers=headers)
        s2_result = s2_result.json()
        s2_result_status = s2_result['completed']
        if s2_result_status == 1:
            break
        else:
            time.sleep(1)
            c += 1

A: The idea of waiting for 1 second and repeating can definitely solve your problem. You can use time.sleep(1). For example,
# Step 2
while True:
    s2_result = requests.get(url_result, headers=headers)
    s2_result = s2_result.json()
    s2_result_status = s2_result['completed']
    if s2_result_status == 1:
    # ...
        break
    else:
    # wait 1 second and repeat
        time.sleep(1)

Reminders: Do not forget to check the http status code of response before you call s2_result.json(). And, using s2_result.get('completed') rather than s2_result['completed'] makes your program more robust.


text:
Q: Allow Magento shipping methods with recurring profile I've installed a plugin that enables a custom shipping method into my store (calculates shipping method with my postal service).
It works with any product, except those with recurring profile enabled.
I found this link http://www.magentocommerce.com/knowledge-base/entry/working-with-recurring-profiles/Magento-Knowledge-Base-Working-with-Recurring-Profiles saying:

... For products with recurring profiles, the customer can only choose
  between the fixed-price shipping methods (flat, table or free) when
  checking out. ...

Why there is this rule? How can I make my custom shipping method work with recurring profile products?
I've tried these plugins and both doesn't work.
https://github.com/pedro-teixeira/correios
https://github.com/willstorm/correios
Which files should I look at to edit to solve this?

A: To solve this you need to basically change your shipping method class in order to add this:
class Namespace_Shipping_Model_Carrier_Customrate
    extends Mage_Shipping_Model_Carrier_Abstract
    implements Mage_Shipping_Model_Carrier_Interface
{
    protected $_code = 'my_customrate';
    protected $_isFixed = true; // << THIS ONE
...
}


text:
Q: Loop of creation via a user input, WPF C# The system needs a way of taking input from txtBox.
I then need the system to take the number input, 1-10. And repeat the ticket and file creation for that x amount of times.
This code also creates a file on the pc with the Lottery ticket in it.
the files have to be named LottoKupon1, LottoKupon2 and so on, this needs to match user input of course.
this is for creation of file and folder
namespace Lottery
{
    internal class FolderCreater
    {
        static string folderName = @"C:\lotto";
        public static string fileName = @"C:\lotto\LottoKupon.txt";

        public static void CreateFolder()
        {
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }
            else if (!File.Exists(fileName))
            {
                File.Create(fileName);
            }
            else { }
        }
    }
}

This is for creation of Lottry Ticket
namespace Lottery
{
    // the system needs a way of taking input
    // from txtBox, int user = int.Parse(txtBox.Text.Trim());  which this line does
    // i then need the system to take the number input, 1-10.
    // and repeat the ticket and file creation for that x amount of times.
    public partial class MainWindow : Window
    {
        public List<long> ListOfAllArrays = new List<long>();
        int i = 1;

        Random randNum = new Random();
        public MainWindow()
        {
            InitializeComponent();
        }

        public void Lotto ()
        {

            StreamWriter sw = new StreamWriter(FolderCreater.fileName);

             sw.WriteLine("    " + "Lotto " + DateTime.Now.ToString("dd/MM/yyyy\n"));
             sw.WriteLine("         " + "1-uge\n" + "       LYN-LOTTO\n");
             Random randNum = new Random();
             int[][] AllArrays = new int[10][];
             for (int i = 0; i < 10; i++)
             {
                AllArrays[i] = new int[7];
             }
             int RowNr = 0;
             foreach (int[] row in AllArrays)
             {
                RowNr++;
                sw.Write(RowNr + ". ");
                for (int j = 0; j < 7; j++)
                {
                    int number = randNum.Next(1, 37);
                    while (row.Any(n => n == number))
                    {
                        number = randNum.Next(1, 37);
                    }
                    row[j] = number;
                }

                Array.Sort(row);
                for(int l = 0; l < 7; l++)
                {
                    sw.Write(row[l].ToString("00") + " ");
                }
                sw.Write("\n");
             }
             TestIfSame(AllArrays);

                if (CheckBox.IsChecked == true)
                {
                    sw.WriteLine("\n****** Joker Tal ******");
                    int[][] AllJokerRows = new int[2][];
                    for (int i = 0; i < 2; i++)
                    {
                        AllJokerRows[i] = new int[7];
                    }
                    foreach (int[] n in AllJokerRows)
                    {
                        sw.Write(" ");
                        for (int i = 0; i < 7; i++)
                        {
                            var JokerNumber = randNum.Next(1, 10);
                            n[i] = JokerNumber;
                        }
                        Array.Sort(n);
                        for (int u = 0; u < 7; u++)
                        {
                            sw.Write(n[u] + "  ");
                        }
                        sw.Write("\n");
                    }
                }
                sw.Close();

        }

        public void TestIfSame(int[][] AllArrays)
        {
            //List<long> ListOfAllArrays = new List<long>();
            for (int i = 0; i < AllArrays.Length; i++)
            {
                ListOfAllArrays.Add(MakesLongNumber(AllArrays[i]));
            }

            for (int i = 0; i < AllArrays.Length; i++)
            {
                long temp = ListOfAllArrays[0];
                ListOfAllArrays.Remove(ListOfAllArrays[0]);

                if (ListOfAllArrays.Contains(MakesLongNumber(AllArrays[i])))
                {
                    Lotto();
                }
                else
                {
                    ListOfAllArrays.Add(temp);
                }
            }
            long MakesLongNumber(int[] row)
            {
                string a = "";
                for (int i = 0; i < row.Length; i++)
                {
                    a += row[i].ToString();
                }
                return Convert.ToInt64(a);
            }
        }
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void cmdOk_Click_1(object sender, RoutedEventArgs e)
        {
            FolderCreater.CreateFolder();
            Lotto();
            // add a ListBox.Items.Add(); within this needs to be the command for the Lottery ticket, so i can have it shown on a list box.
        }

**This is for a Lottery assignment, its on a lower level of coding, so no answer that is way too complicated, hope you understand. please ask questions if needed.
I tried a dew things with a for loop around the first void which took user input, but i could not make it work.
the code is expected to create files and Lottery ticket depending on users input**


text:
Q: Please Help me solve this problem i have trying to solve Range extraction The problem i try to solve is this using js :
A format for expressing an ordered list of integers is to use a comma separated list of either:
-individual integers
-or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17"
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Example:
solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20"

so my idea was to use 3 functions :
1- newRangeStart: creates a new Array in results to store the range numbers and puts in it the first element of the range (RangeStarter).
2-olSupp : deletes elements from the list that were used by the 3rd function RangeArr so that we get a new Arr with a new RangeStarter using 1st function.
3-RangeArr : uses the 1st function than adds elements from the list to the array created by it which are consecutive starting from the Range starter, and then uses the 2nd function to delete the elements used from the ol so the next time we use the RangeArr function it creates another range.
By repeating the RangeArr function with a while loop that runs until ol becomes empty we will have a resuts array with arrays inside of it that contains ranges.
now the poblem is when i run RangeArr function it doesn't delete the used elements from the ol as i want i tried to fix the olSupp function several times but it just doesn't work i think there is a problem in my entire code pls someone help me to fix it here is my code:
function solution(list){
    // TODO: complete solution

    let ol = [...list];
    let results = [];

    /*This adds a new array for a range by adding the first number of the range to
    an array (2D array) and stores it in the resuts array  */
    function newRangeStart(orderedlist,result){
        result.push([orderedlist[0]]);
        return result;
    }
    /*This functions takes the ol and deletes elements that are found in the results
    so that the next time we run the newRangeStart function it creates an other array
    for another range with a different start number*/
    function olSupp(orderedlist,result){
        let toRemove = result.flat();
        let newList = [];
        for (let i = 0; i < orderedlist.length; i++) {
            if(!toRemove.includes(orderedlist[i])){
                newList.push(orderedlist[i]);
            }
        }
        orderedlist = [...newList];
        return orderedlist;
    }

    /*Finally RangeArr function creates a range from the ol (ordered list)
    starting by the first element of the results array and then uses olSupp to delete
    the used numbers from the ol */
    function RangeArr (orderedlist,result){
        newRangeStart(orderedlist,result);
        let i = 0;
        while(orderedlist[i+1]- orderedlist[i] == 1 && orderedlist[i+2]- orderedlist[i+1]== 1) {
            result[i].push(orderedlist[i+1],orderedlist[i+2]);
            i = i+1;
        }
        olSupp(orderedlist,result);
        return result;
    }

    /*we execute the RangeArr function until ol becomes emepty
    and this will give us multiple arrays in the result array containing
    the elements of each range found in the ol */
    //PS: i didnt put the code beacuse it causes an infinte loop using while

    RangeArr(ol,results);
    console.log(ol,results);

}

solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);

A:

const solution = arr => {
    let s = null, d = 0;

    const result = arr.sort((a, b) => a - b).reduce((p, c, i, arr) => {
        d++;
        if (!s) s = c;
        if (arr[i + 1] - s > d) {
            s === c ? p.push(s) : d < 3 ? p.push(s, c) : p.push(`${s}-${c}`);
            s = null;
            d = 0;
        }
        if (arr[i + 1] === undefined) s === c ? p.push(s) : d < 3 ? p.push(s, c) : p.push(`${s}-${c}`);

        return p;
    }, []);

    return result;
}

console.log(solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]));

Variables:

*

*s (start) for saving the number that starts a range.

*d (distance) for counting the distance between the start and end of a range.

*for a and b read the doc for javascript sort method to learn more.

*same with p (pervious), c (current), i (index) and arr (original array) read the doc for javascript reduce method
Logic:
we can determine a range (for example: [1, 2, 3, 4, 5] is equal to "1-5") by calculate the distance between the starting number 1 and the ending number 5. so the distance between 1 and 5 is 4 because 1 needs to increment by 1 four times to reach 5 and the distance inside the array between the starting number 1 (index 0) and the ending number 5 (index 4) is also 4. so if we take the end minus the start 5 - 1 = 4 if it matches to the correct distance inside the array which is 4 then it is a range "1-5". let's have another example [1, 2, 3, 6, 7, 8], this should be "1-3" and "6-8". when we calculate the distance with 1 and 6 (6 - 1 = 5) we get 5 which is incorrect, because it doesn't match the correct distance inside the array (1 is at index 0 and 6 is at index 3, 3 - 0 = 3. the distance between 1 and 6 is only 3 index apart and not 5, that isn't a range). but if we do the calculate with 1 and 3 it matches our criteria and it's a range "1-3".
Code:
we have to do the calculation inside a loop (i'm using reduce method because it's convenient). first thing i do in the loop is d++ to track the distance of index(s) that the loop had travel inside the array. if (!s) s = c; is for check we've saved a starting number or not. if (arr[i + 1] - s > d) { ... } this is where we do the calculation to see if the current element inside the array minus s is greater than the distance index we've travel or not. if it's true then it means s and the last element must be a range and we push that range in the result array. and then we reset s and d to let them work on the next range.
Update

const solution = arr => {
    let s = null;

    return arr.sort((a, b) => a - b).reduce((p, c, i, arr) => {
        if (!s) s = c;
        if (c + 1 !== arr[i + 1]) {
            s === c ? p.push(s) : c - 1 === s ? p.push(s, c) : p.push(`${s}-${c}`);
            s = null;
        }
        return p
    }, [])
}

console.log(solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]));


text:
Q: Display checked in the table according id value in the array I have a problem displaying checked in the table according to id value in the array if I have to click the Show checked if id values are 1 and 5 button. For example, I want to display checked in the table if id values are 1 and 5.
But I using below sample javascript coding cannot show the selected checked in the table followed by the id value:
Javascript
function show_value() {
  var selected_value = "1,5";
  var checkbox_state = []
  var id_value = []
  //use each loop
  $("[name=checkbox_val]").each(function() {
    checkbox_state.push($(this).is(":checked"))
    id_value.push($(this).closest("tr").find("[name=id_value]").val()) //push value in array
    $("#checkbox_val").attr("checked", true);

  })
  var id_value_true = id_value.toString();

  if(jQuery.inArray(selected_value, id_value_true) !== -1){
      $("#checkbox_val").attr("checked", true);
  }else{
      $("#checkbox_val").attr("checked", false);
  }

  console.log("checkbox -- " + checkbox_state.toString() + " ID VALUE --" + id_value.toString())

}

Below is my whole sample coding:

function show_value() {
  var selected_value = "1,5";
  var checkbox_state = []
  var id_value = []
  //use each loop
  $("[name=checkbox_val]").each(function() {
    checkbox_state.push($(this).is(":checked"))
    id_value.push($(this).closest("tr").find("[name=id_value]").val()) //push value in array
    $("#checkbox_val").attr("checked", true);

  })
  var id_value_true = id_value.toString();

  if(jQuery.inArray(selected_value, id_value_true) !== -1){
      $("#checkbox_val").attr("checked", true);
  }else{
      $("#checkbox_val").attr("checked", false);
  }

  console.log("checkbox -- " + checkbox_state.toString() + " ID VALUE --" + id_value.toString())

}

<!DOCTYPE html>

    Checkbox
    ID Value
    Contact
    Country

    <input type="checkbox" id="checkbox_val" name="checkbox_val" value="0">
    <input type="text" id="id_value" name="id_value" value="1"/>
    Maria Anders
    Germany

    <input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0">
    <input type="text" id="id_value" name="id_value" value="2"/>
    Francisco Chang
    Mexico

    <input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0">
    <input type="text" id="id_value" name="id_value" value="3"/>
    Roland Mendel
    Austria

    <input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0">
    <input type="text" id="id_value" name="id_value" value="4"/>
    Helen Bennett
    UK

    <input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0">
    <input type="text" id="id_value" name="id_value" value="5"/>
    Yoshi Tannamuri
    Canada

    <input type="checkbox" id="checkbox_val" name="checkbox_val" value="0">
    <input type="text" id="id_value" name="id_value" value="6"/>
    Giovanni Rovelli
    Italy

<button type="button" id="updateBtn_5" class="btn btn-sm btn-primary" onclick="show_value()">Show checked if id values are 1 and 5</button>

Actually, I want the expected result like below the picture:

Hope someone can guide me on how to solve this problem. Thanks.

A: The first issue you have is that you are repeating the same id in multiple elements in the DOM which is invalid. id attributes must be unique.
To achieve your goal you can split the selected_values string in to an array and use it to filter() the existing id_value elements to retrieve only those who have a matching value. From there you can traverse the DOM to find the related checkbox and set its checked property to true. Try this:

$('#updateBtn_5').on('click', () => {
  var selected_values = "1,5".split(',');

  $('input[name="id_value"]')
    .filter((i, el) => selected_values.indexOf(el.value) != -1)
    .closest('tr').find(':checkbox').prop('checked', true);
})
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

    Checkbox
    ID Value
    Contact
    Country

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="1" />
    Maria Anders
    Germany

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="2" />
    Francisco Chang
    Mexico

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="3" />
    Roland Mendel
    Austria

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="4" />
    Helen Bennett
    UK

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="5" />
    Yoshi Tannamuri
    Canada

    <input type="checkbox" name="checkbox_val" value="0">
    <input type="text" name="id_value" value="6" />
    Giovanni Rovelli
    Italy

<button type="button" id="updateBtn_5" class="btn btn-sm btn-primary">Show checked if id values are 1 and 5</button>


text:
Q: JavaFX TextField Auto-suggestions I want to make this TextField have suggestions feature just like in Lucene. I've searched all the web and I just find it for ComboBox.
TextField instNameTxtFld = instNameTxtFld();

private TextField instNameTxtFld() {
    TextField txtFld = new TextField();
    txtFld.setPrefSize(600, 75);
    return txtFld;
}

The reason that I can't use the method for ComboBox is because I can't input the value to database below if I use ComboBox.
private void goNext() {

    if (nameTxtFld.getText() == null || nameTxtFld.getText().trim().isEmpty()
            || instNameTxtFld.getText()== null || instNameTxtFld.getText().trim().isEmpty()
            || addTxtArea.getText() == null || addTxtArea.getText().trim().isEmpty()) {
        alertDialog.showAndWait();
    } else {
        String satu = idNumTxtFld.getText();
        String dua = nameTxtFld.getText();
        String tiga = addTxtArea.getText();
        String empat = instNameTxtFld.getText();
        int delapan = idType.getSelectionModel().getSelectedIndex();
        String sembilan = timeStamp.getText();
        try {
            KonekDB.createConnection();
            Statement st = KonekDB.conn.createStatement();
            String sql = "INSERT INTO privateguest"
                    + "(idNumber, name, address, institution, idType, startTime) "
                    + "VALUES "
                    + "('" + satu + "','" + dua + "','" + tiga + "','" + empat + "','" + delapan + "','" + sembilan + "')";

            System.out.println(sql);
            st.executeUpdate(sql);

        } catch (SQLException ex) {

            System.out.println(satu + " " + dua + " " + tiga + " " + empat + " " + delapan + " " + sembilan);
            System.out.println("SQL Exception (next)");
            ex.printStackTrace();
        }
        Frame3Private frame3 = new Frame3Private(english);
        this.getScene().setRoot(frame3);
    }

}

Please help me to make the most simple code for doing TextField suggestions/ auto-complete.

A: This example https://gist.github.com/floralvikings/10290131 only allowed Strings.
I edited it to allow any object and just use that object's toString method. This allows you to use the object selected to do other things rather than just populate the TextField. Also fixed a bug where an exception would occur if you are deleting a String in the TextField that is not a part of the entries.
Example usage:
SortedSet<Address> entries = new TreeSet<>((Address o1, Address o2) -> o1.toString().compareTo(o2.toString()));

entries.add(new Address("50", "Main Street", "Oakville", "Ontario", "T6P4K9"));
entries.add(new Address("3", "Fuller Road", "Toronto", "Ontario", "B6S4T9"));

AutoCompleteTextField<Address> text = new AutoCompleteTextField(entries);

text.getEntryMenu().setOnAction(e ->
{
    ((MenuItem) e.getTarget()).addEventHandler(Event.ANY, event ->
    {
         if (text.getLastSelectedObject() != null)
         {
            text.setText(text.getLastSelectedObject().toString());
            System.out.println(text.getLastSelectedObject().getProvince());
         }
    });
});

AutoCompleteTextField.java
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.Side;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.TextField;

import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;

/**
 * This class is a TextField which implements an "autocomplete" functionality,
 * based on a supplied list of entries.

 *
 * If the entered text matches a part of any of the supplied entries these are
 * going to be displayed in a popup. Further the matching part of the entry is
 * going to be displayed in a special style, defined by
 * {@link #textOccurenceStyle textOccurenceStyle}. The maximum number of
 * displayed entries in the popup is defined by
 * {@link #maxEntries maxEntries}.

 * By default the pattern matching is not case-sensitive. This behaviour is
 * defined by the {@link #caseSensitive caseSensitive}
 * .

 *
 * The AutoCompleteTextField also has a List of
 * {@link #filteredEntries filteredEntries} that is equal to the search results
 * if search results are not empty, or {@link #filteredEntries filteredEntries}
 * is equal to {@link #entries entries} otherwise. If
 * {@link #popupHidden popupHidden} is set to true no popup is going to be
 * shown. This list can be used to bind all entries to another node (a ListView
 * for example) in the following way:
 *

 *
 * AutoCompleteTextField auto = new AutoCompleteTextField(entries);
 * auto.setPopupHidden(true);
 * SimpleListProperty filteredEntries = new SimpleListProperty(auto.getFilteredEntries());
 * listView.itemsProperty().bind(filteredEntries);
 *
 *

 *
 * @author Caleb Brinkman
 * @author Fabian Ochmann
 * @param <S>
 */
public class AutoCompleteTextField<S> extends TextField
{

    private final ObjectProperty<S> lastSelectedItem = new SimpleObjectProperty<>();

    /**
     * The existing autocomplete entries.
     */
    private final SortedSet<S> entries;

    /**
     * The set of filtered entries:

     * Equal to the search results if search results are not empty, equal to
     * {@link #entries entries} otherwise.
     */
    private ObservableList<S> filteredEntries
            = FXCollections.observableArrayList();

    /**
     * The popup used to select an entry.
     */
    private ContextMenu entriesPopup;

    /**
     * Indicates whether the search is case sensitive or not.

     * Default: false
     */
    private boolean caseSensitive = false;

    /**
     * Indicates whether the Popup should be hidden or displayed. Use this if
     * you want to filter an existing list/set (for example values of a
     * {@link javafx.scene.control.ListView ListView}). Do this by binding
     * {@link #getFilteredEntries() getFilteredEntries()} to the list/set.
     */
    private boolean popupHidden = false;

    /**
     * The CSS style that should be applied on the parts in the popup that match
     * the entered text.

     * Default: "-fx-font-weight: bold; -fx-fill: red;"
     *

     * Note: This style is going to be applied on an
     * {@link javafx.scene.text.Text Text} instance. See the JavaFX CSS
     * Reference Guide for available CSS Propeties.
     */
    private String textOccurenceStyle = "-fx-font-weight: bold; "
            + "-fx-fill: red;";

    /**
     * The maximum Number of entries displayed in the popup.

     * Default: 10
     */
    private int maxEntries = 10;

    /**
     * Construct a new AutoCompleteTextField.
     *
     * @param entrySet
     */
    public AutoCompleteTextField(SortedSet<S> entrySet)
    {
        super();
        this.entries = (entrySet == null ? new TreeSet<>() : entrySet);
        this.filteredEntries.addAll(entries);

        entriesPopup = new ContextMenu();

        textProperty().addListener((ObservableValue<? extends String> observableValue, String s, String s2) ->
        {

            if (getText() == null || getText().length() == 0)
            {
                filteredEntries.clear();
                filteredEntries.addAll(entries);
                entriesPopup.hide();
            } else
            {
                LinkedList<S> searchResult = new LinkedList<>();
                //Check if the entered Text is part of some entry
                String text1 = getText();
                Pattern pattern;
                if (isCaseSensitive())
                {
                    pattern = Pattern.compile(".*" + text1 + ".*");
                } else
                {
                    pattern = Pattern.compile(".*" + text1 + ".*", Pattern.CASE_INSENSITIVE);
                }
                for (S entry : entries)
                {
                    Matcher matcher = pattern.matcher(entry.toString());
                    if (matcher.matches())
                    {
                        searchResult.add(entry);
                    }
                }
                if (!entries.isEmpty())
                {
                    filteredEntries.clear();
                    filteredEntries.addAll(searchResult);
                    //Only show popup if not in filter mode
                    if (!isPopupHidden())
                    {
                        populatePopup(searchResult, text1);
                        if (!entriesPopup.isShowing())
                        {
                            entriesPopup.show(AutoCompleteTextField.this, Side.BOTTOM, 0, 0);
                        }
                    }
                } else
                {
                    entriesPopup.hide();
                }
            }
        });

        focusedProperty().addListener((ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean aBoolean2) ->
        {
            entriesPopup.hide();
        });

    }

    /**
     * Get the existing set of autocomplete entries.
     *
     * @return The existing autocomplete entries.
     */
    public SortedSet<S> getEntries()
    {
        return entries;
    }

    /**
     * Populate the entry set with the given search results. Display is limited
     * to 10 entries, for performance.
     *
     * @param searchResult The set of matching strings.
     */
    private void populatePopup(List<S> searchResult, String text)
    {
        List<CustomMenuItem> menuItems = new LinkedList<>();
        int count = Math.min(searchResult.size(), getMaxEntries());
        for (int i = 0; i < count; i++)
        {
            final String result = searchResult.get(i).toString();
            final S itemObject = searchResult.get(i);
            int occurence;

            if (isCaseSensitive())
            {
                occurence = result.indexOf(text);
            } else
            {
                occurence = result.toLowerCase().indexOf(text.toLowerCase());
            }
            if (occurence < 0)
            {
                continue;
            }
            //Part before occurence (might be empty)
            Text pre = new Text(result.substring(0, occurence));
            //Part of (first) occurence
            Text in = new Text(result.substring(occurence, occurence + text.length()));
            in.setStyle(getTextOccurenceStyle());
            //Part after occurence
            Text post = new Text(result.substring(occurence + text.length(), result.length()));

            TextFlow entryFlow = new TextFlow(pre, in, post);

            CustomMenuItem item = new CustomMenuItem(entryFlow, true);
            item.setOnAction((ActionEvent actionEvent) ->
            {
                lastSelectedItem.set(itemObject);
                entriesPopup.hide();
            });
            menuItems.add(item);
        }
        entriesPopup.getItems().clear();
        entriesPopup.getItems().addAll(menuItems);

    }

    public S getLastSelectedObject()
    {
        return lastSelectedItem.get();
    }

    public ContextMenu getEntryMenu()
    {
        return entriesPopup;
    }

    public boolean isCaseSensitive()
    {
        return caseSensitive;
    }

    public String getTextOccurenceStyle()
    {
        return textOccurenceStyle;
    }

    public void setCaseSensitive(boolean caseSensitive)
    {
        this.caseSensitive = caseSensitive;
    }

    public void setTextOccurenceStyle(String textOccurenceStyle)
    {
        this.textOccurenceStyle = textOccurenceStyle;
    }

    public boolean isPopupHidden()
    {
        return popupHidden;
    }

    public void setPopupHidden(boolean popupHidden)
    {
        this.popupHidden = popupHidden;
    }

    public ObservableList<S> getFilteredEntries()
    {
        return filteredEntries;
    }

    public int getMaxEntries()
    {
        return maxEntries;
    }

    public void setMaxEntries(int maxEntries)
    {
        this.maxEntries = maxEntries;
    }

}

A: There is another solution with JFoenix. Since February 2018 they added autocompletion class. This is implementation of it.
// when initializing the window or in some other method
void initialize() {
    JFXAutoCompletePopup<String> autoCompletePopup = new JFXAutoCompletePopup<>();
    autoCompletePopup.getSuggestions().addAll("option1", "option2", "...");

    autoCompletePopup.setSelectionHandler(event -> {
        textField.setText(event.getObject());

        // you can do other actions here when text completed
    });

    // filtering options
    textField.textProperty().addListener(observable -> {
        autoCompletePopup.filter(string -> string.toLowerCase().contains(textField.getText().toLowerCase()));
        if (autoCompletePopup.getFilteredSuggestions().isEmpty() || textField.getText().isEmpty()) {
            autoCompletePopup.hide();
            // if you remove textField.getText.isEmpty() when text field is empty it suggests all options
            // so you can choose
        } else {
            autoCompletePopup.show(textField);
        }
    });
}

This is a bit new approach and worked fine with me. Hope it will help and thanks to JFoenix developers.

A: Here is my solution based on This.
public class AutocompletionlTextField extends TextFieldWithLengthLimit {
    //Local variables
    //entries to autocomplete
    private final SortedSet<String> entries;
    //popup GUI
    private ContextMenu entriesPopup;

    public AutocompletionlTextField() {
        super();
        this.entries = new TreeSet<>();
        this.entriesPopup = new ContextMenu();

        setListner();
    }

    /**
     * wrapper for default constructor with setting of "TextFieldWithLengthLimit" LengthLimit
     *
     * @param lengthLimit
     */
    public AutocompletionlTextField(int lengthLimit) {
        this();
        super.setLengthLimit(lengthLimit);
    }

    /**
     * "Suggestion" specific listners
     */
    private void setListner() {
        //Add "suggestions" by changing text
        textProperty().addListener((observable, oldValue, newValue) -> {
            String enteredText = getText();
            //always hide suggestion if nothing has been entered (only "spacebars" are dissalowed in TextFieldWithLengthLimit)
            if (enteredText == null || enteredText.isEmpty()) {
                entriesPopup.hide();
            } else {
                //filter all possible suggestions depends on "Text", case insensitive
                List<String> filteredEntries = entries.stream()
                        .filter(e -> e.toLowerCase().contains(enteredText.toLowerCase()))
                        .collect(Collectors.toList());
                //some suggestions are found
                if (!filteredEntries.isEmpty()) {
                    //build popup - list of "CustomMenuItem"
                    populatePopup(filteredEntries, enteredText);
                    if (!entriesPopup.isShowing()) { //optional
                        entriesPopup.show(AutocompletionlTextField.this, Side.BOTTOM, 0, 0); //position of popup
                    }
                //no suggestions -> hide
                } else {
                    entriesPopup.hide();
                }
            }
        });

        //Hide always by focus-in (optional) and out
        focusedProperty().addListener((observableValue, oldValue, newValue) -> {
            entriesPopup.hide();
        });
    }

    /**
    * Populate the entry set with the given search results. Display is limited to 10 entries, for performance.
    *
    * @param searchResult The set of matching strings.
    */
    private void populatePopup(List<String> searchResult, String searchReauest) {
        //List of "suggestions"
        List<CustomMenuItem> menuItems = new LinkedList<>();
        //List size - 10 or founded suggestions count
        int maxEntries = 10;
        int count = Math.min(searchResult.size(), maxEntries);
        //Build list as set of labels
        for (int i = 0; i < count; i++) {
          final String result = searchResult.get(i);
          //label with graphic (text flow) to highlight founded subtext in suggestions
          Label entryLabel = new Label();
          entryLabel.setGraphic(Styles.buildTextFlow(result, searchReauest));
          entryLabel.setPrefHeight(10);  //don't sure why it's changed with "graphic"
          CustomMenuItem item = new CustomMenuItem(entryLabel, true);
          menuItems.add(item);

          //if any suggestion is select set it into text and close popup
          item.setOnAction(actionEvent -> {
              setText(result);
              positionCaret(result.length());
              entriesPopup.hide();
          });
        }

        //"Refresh" context menu
        entriesPopup.getItems().clear();
        entriesPopup.getItems().addAll(menuItems);
    }

    /**
    * Get the existing set of autocomplete entries.
    *
    * @return The existing autocomplete entries.
    */
    public SortedSet<String> getEntries() { return entries; }
}

You must extends from "TextField" instead of "TextFieldWithLengthLimit" and delete constructor with "Length limit".
I use static methods to work with Styles. It's used here to "highlight" entered text inside suggestion results. Here is the code of methos from this class:
/**
 * Build TextFlow with selected text. Return "case" dependent.
 *
 * @param text - string with text
 * @param filter - string to select in text
 * @return - TextFlow
 */
public static TextFlow buildTextFlow(String text, String filter) {
    int filterIndex = text.toLowerCase().indexOf(filter.toLowerCase());
    Text textBefore = new Text(text.substring(0, filterIndex));
    Text textAfter = new Text(text.substring(filterIndex + filter.length()));
    Text textFilter = new Text(text.substring(filterIndex,  filterIndex + filter.length())); //instead of "filter" to keep all "case sensitive"
    textFilter.setFill(Color.ORANGE);
    textFilter.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
    return new TextFlow(textBefore, textFilter, textAfter);
}

You may add this "AutocompletionlTextField" in FXML (dont forget about "imports") or inside constructor. To set "suggestions" list on use "entries" getter:
AutocompletionlTextField field = new AutocompletionlTextField();
field.getEntries().addAll(YOUR_ARRAY_OF_STRINGS);

It seems like that in my application:

Hope it helps.

A: You can use ControlsFX --> maven
Solution:
TextFields.bindAutoCompletion(textfield,"text to suggest", "another text to suggest");

A: Here is my solution - a complete method only with a ComboBox parameter:
 /**
 * My own autocomplete combobox
 *
 * @param categoryComboBox
 */
public static void bindAutoCompleteToComboBox(ComboBox<String> categoryComboBox) {

    /**
     * backup the original list
     */
    List<String> categoryComboBoxItemsList = new ArrayList<String>(categoryComboBox.getItems());

    /**
     * if mouse pressed: select all of the text field
     */
    categoryComboBox.getEditor().setOnMousePressed(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    if (categoryComboBox.getEditor().isFocused() && !categoryComboBox.getEditor().getText().isEmpty()) {
                        categoryComboBox.getEditor().selectAll();
                    }
                }
            });
        }
    });

    /**
     * events on text input
     */
    categoryComboBox.setOnKeyReleased(new EventHandler<KeyEvent>() {

        private List<String> reducedList = new ArrayList<String>();

        @Override
        public void handle(KeyEvent event) {

            if (event.getCode().isLetterKey() || event.getCode().isDigitKey() || event.getCode().equals(KeyCode.BACK_SPACE)) {

                /**
                 * Open comboBox if letter, number or backspace
                 */
                categoryComboBox.show();

                String temp = categoryComboBox.getEditor().getText();
                reducedList = new ArrayList<String>();

                /**
                 * If backspace pressed, selection refers to the basic list again
                 */
                if (event.getCode().equals(KeyCode.BACK_SPACE)) {
                    categoryComboBox.getItems().clear();
                    categoryComboBox.getItems().addAll(categoryComboBoxItemsList);

                    // java fx workaround to restore the default list height of 10
                    categoryComboBox.hide();
                    categoryComboBox.setVisibleRowCount(10);
                    categoryComboBox.show();
                }

                /**
                 * loop through all entrys and look whether input contains this text.
                 *
                 * after that, entry will be added to the reduced list
                 */
                for (String element : categoryComboBox.getItems()) {
                    if (StringUtils.containsIgnoreCase(element, temp)) {
                        reducedList.add(element);
                    }
                }

                /**
                 * all elements are cleared, the reduced list will be added. First element is selected
                 */
                categoryComboBox.getItems().clear();
                categoryComboBox.getItems().addAll(reducedList);
                categoryComboBox.getSelectionModel().select(0);
                categoryComboBox.getEditor().setText(temp);

            } else if (event.getCode().equals(KeyCode.ENTER)) {

                /**
                 * if enter, the element which is selected will be applied to the text field and the dropdown will be closed
                 */
                if (categoryComboBox.getSelectionModel().getSelectedIndex() != -1) {
                    categoryComboBox.getEditor().setText(categoryComboBox.getItems().get((categoryComboBox.getSelectionModel().getSelectedIndex())));
                } else {
                    categoryComboBox.getEditor().setText(categoryComboBox.getItems().get(0));
                }

            } else if (event.getCode().equals(KeyCode.DOWN)) {

                /**
                 * arrow down shows the dropdown
                 */
                categoryComboBox.show();
            }

            /**
             * Tab marks everything (when tabbing into the field
             */
            if (event.getCode().equals(KeyCode.TAB)) {

                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        if (categoryComboBox.getEditor().isFocused() && !categoryComboBox.getEditor().getText().isEmpty()) {
                            categoryComboBox.getEditor().selectAll();
                        }
                    }
                });

            } else {
                /**
                 * all entries except for tab put the caret on the last character
                 */
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        categoryComboBox.getEditor().positionCaret(categoryComboBox.getEditor().getText().length());
                    }
                });
            }

        }
    });

    /**
     * focus lost
     */
    categoryComboBox.focusedProperty().addListener(new ChangeListener<Boolean>() {

        /**
         * if focus lost: refill the category combo box with the original items
         */
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {

            if (oldValue) {

                /**
                 * saves whether textfield was empty before reset the comboBox
                 */
                boolean emptyTextField = categoryComboBox.getEditor().getText().isEmpty();

                if (categoryComboBox.getSelectionModel().getSelectedIndex() != -1) {
                    categoryComboBox.getEditor().setText(categoryComboBox.getItems().get(categoryComboBox.getSelectionModel().getSelectedIndex()));
                }

                String temp = categoryComboBox.getEditor().getText();

                categoryComboBox.getItems().clear();
                categoryComboBox.getItems().addAll(categoryComboBoxItemsList);

                if (!emptyTextField) {
                    categoryComboBox.getSelectionModel().select(temp);
                } else {
                    categoryComboBox.getEditor().setText("");
                }
            }
        }
    });
}

A: This is a quite old topic, but since I have just had this problem, I assembled my solution of parts that were already mentioned.
Like @RicherdK already said, you can use controlsfx and the most simple way to bind it is like he said:
TextFields.bindAutoCompletion(textfield,"text to suggest", "another text to suggest");

In the comments of his post is mentioned that this is quite slow for an autocomplete. This is true since it takes 250ms without a keyboard stroke to show the suggestions. Therefore you can just set the delay to whatever you want:
TextFields.bindAutoCompletion(textfield,"text to suggest", "another text to suggest").setDelay(50);

Beside this small detail, I had a problem using this lib, I had to add:
--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED

to my VM options. Some other people had similar problems, you can find it here and make sure your JavaFx versions matches

A: If you don't want to use any external libraries like controlsfx , here  is my solution:

*

*Create a TextField for the user to enter text.

*Create a ListView to display the suggestions.

*Bind the text property of the TextField to a string property in your JavaFX controller class.

*Create an event handler for the text property that updates the suggestions based on the current value of the text field.

*Populate the ListView with the suggestions.

*Handle user interaction with the ListView to select a suggestion, which would then be displayed in the TextField.

Here's an example of what the code could look like in your JavaFX controller class:
public class AutocompleteController {

    @FXML
    private TextField textField;

    @FXML
    private ListView<String> suggestionsList;

    private final ObservableList<String> suggestions = FXCollections.observableArrayList();

    private final StringProperty text = new SimpleStringProperty();

    public void initialize() {
        text.bind(textField.textProperty());
        text.addListener((observable, oldValue, newValue) -> updateSuggestions(newValue));
        suggestionsList.setItems(suggestions);
        suggestionsList.setOnMouseClicked(event -> {
            String selectedSuggestion = suggestionsList.getSelectionModel().getSelectedItem();
            if (selectedSuggestion != null) {
                textField.setText(selectedSuggestion);
                suggestions.clear();
            }
        });
    }

    private void updateSuggestions(String enteredText) {
        // Clear the previous suggestions
        suggestions.clear();

        // Get the new suggestions based on enteredText and add them to the suggestions list
        List<String> newSuggestions = getSuggestions(enteredText);
        suggestions.addAll(newSuggestions);
    }

    private List<String> getSuggestions(String enteredText) {
        // Implement your logic to retrieve suggestions based on enteredText
        // ...

        return suggestions;
    }
}

If you want your suggestion listview to be dynamic so that its height depends on the items on the listview create a DoubleBinding that calculates the height of the ListView based on the number of items in the list and the fixed cell size. The binding is then applied to the prefHeight property of the ListView to make the height dynamic.
Here is an example:
suggestionsList.setFixedCellSize(24.0); // Set a fixed height for each cell

DoubleBinding heightBinding = new DoubleBinding() {
    {
        super.bind(suggestionsList.getItems());
    }
    @Override
    protected double computeValue() {
        return suggestionsList.getFixedCellSize() * suggestionsList.getItems().size();
    }
};

suggestionsList.prefHeightProperty().bind(heightBinding);


text:
Q: Passing Tuple model to MVC grid I have tuple view model contains list of Version and list of User.This tuple value I have to pass it to MVC grid.
Index.cshtml Page
@model Tuple<IEnumerable<Version>,IEnumerable<user>>
@Html.Grid(Model.Item1.AsEnumerable()).Columns(columns =>
{
   columns.Add(c => c.VersionId).Titled("Version Id");
   columns.Add(c => c.VersionName).Titled("Version Name").Filterable(true);
   columns.Add(c => c.Description).Titled("Description");
}).WithPaging(20).Sortable(true)

Controller.cs
public ActionResult Index()
      {
        List<version> versionList = null;
        List<user> userList = null;
        versionList = _settingsRepo.GetVersionList();
        userList = _settingsRepo.GetUserList();
        var tuple = Tuple.Create<List<version>, List<user>>(versionList,
        userList);
        return View(tuple);
      }

Facing error " 'Version' does not contain a definition for 'VersionId' and no extension method 'VersionId' accepting a first argument of type 'Version' could be found (are you missing a using directive or an assembly reference?) " at line  columns.Add(c => c.VersionId).Titled("Version Id") in Index.cshtml page.

A: Within your view you have
@model Tuple<IEnumerable<Version>,IEnumerable<user>>

whereas your controller is defined as
var tuple = Tuple.Create<List<version>, List<user>>(versionList,
    userList);

Update the view to use the lower case version class


text:
Q: Copying cell from one sheet to another without formatting probably a simple one to your geniuses however I need a fresh pair of eyes as I've been on this a while and can't see my error. I'm merely wanting to copy the contents of a cell from one cell to another cell on another sheet, but I don't want all the formatting to go with it, only the value.
My code is below
  Range("H" & Target.Row).Copy Destination:=Sheets("Accepted Template").Range("P4").PasteSpecial Paste:=xlPasteValues

Any idea what I have done wrong here.  VBA keeps throwing out an unexpected end error.

A: You can try this Code will Copy Formatted cell value from Sheet 1 & Paste in Sheet 2 at destination cell/cells without Formatting (Only Value).
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A3").Copy
Sheets("Sheet2").Range("A3, A4").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub

N.B.

*

*If you want to copy Formatted range then replace line 2 in the code
with this, Sheets("Sheet1").Range("A3:A10").Copy

Note,

*

*This code can be used as Standard Module also.

*Just to test the code purposely I've used  2 destination cells, you
may use one or even many.

*This can be done even by use of  Paste Special and Value option also.


text:
Q: What condition variables can do that unlock+yield cannot? In POSIX, there's the requirement that when a wait is called on a condition variable and a mutex, the 2 operations - unlocking the mutex and blocking the thread, be atomically performed, in such way that any broadcast/signal should take effect as if they happened after blocking. I suppose there should be equivalent requirements on C11, C++ condition variables as well, and I won't go on to do a verbose enumeration.
However, in some system (such as many people's nostalgia WinXP), there wasn't a condition variable mechanism. Instead, they have to perform a unlock+yield to achieve similar (same?) effect. And this works, because even if the broadcast/signal occured in-between the unlock and yield, when the thread is re-scheduled, its observable behavior is the same as if the wake occured after the block. WinXP supported mutex, and it had an SleepEx function that can work like an yield.
So it begs the question: What condition variables can do, that unlock+yield cannot?

In response to the comment: I use WinXP as an example because it happens to be one that supported mutex but not condvar, and the fact that it's one generation's memory. Of course, we assume correctness and reasonable performance, and the question doesn't specifically ask Windows and it asks any implementation in general.


text:
Q: execute commands one after other in new line shell script I want to print  commands on remote server one after other in new line
echo "Hostname is: `hostname`"
echo
echo "Disk Space is: `df -h /`"
echo
echo "free Space is: `free -m`

i get following output
Hostname is:   echo Disk Space is: Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root  /

Its not printing on new line

A: Use this form instead:
echo "Hostname is: $(hostname)"
echo
echo "Disk Space is: $(df -h)"
echo
echo "free Space is: $(free -m)"


text:
Q: number of different kinds of partitions of $n$ are the same I want to prove that:
The number of partitions of $n$ into parts congruent to $1$ or $5$ ($\text{mod}$ 6) equals number of partitions of $n$ into distinct parts all congruent to $1$ or $2$ ($\text{mod}$ 3).
Is there a way to prove this using the well known Mobius inversion formula? I have been trying to establish a bijection between the set of partitions of $n$ of the first kind and the set of partitions of $n$ of the latter kind, but it is very difficult to establish uniqueness. Any help is appreciated. Thank you.

A: Once approach is to use the generating functions. Let $S_1, S_2$ denote the sets $\{m \in \mathbb{N} : m \equiv 1,2 \pmod 3\}$ and $\{m \in \mathbb{N} : m \equiv 1,5 \pmod 6\}$. If $p_{S}(n)$ denotes the number of partitions of $n$ into elements of $S$ and $\overline{p_S}(n)$ denotes the number of partitions of $n$ into distinct elements of $S$, then as formal power series
$$\sum_{n=0}^{\infty}\overline{p_{S_1}}(n)q^n = \prod_{j=0}^{\infty}(1 + q^{3j + 1})(1 + q^{3j + 2})$$
and
$$\sum_{n=0}^{\infty}p_{S_2}(n)q^n = \prod_{j=0}^{\infty}\frac{1}{(1 - q^{6j + 1})(1 - q^{6j + 5})}.$$
We have
\begin{equation*}
\begin{aligned}
&\mathrel{\phantom{=}}\prod_{j=0}^{\infty}(1 + q^{3j + 1})(1 + q^{3j + 2}) \\
&= \prod_{j=0}^{\infty}\frac{(1 - q^{6j + 2})(1 - q^{6j + 4})}{(1 - q^{3j + 1})(1 - q^{3j + 2})} \\
&= \prod_{j=0}^{\infty}\frac{(1 - q^{6j + 2})(1 -q^{6j+ 4})}{(1 - q^{6j + 1})(1 - q^{6j + 4})(1 - q^{6j + 2})(q - q^{6j + 5})} \\
&= \prod_{j=0}^{\infty}\frac{1}{(1 - q^{6j + 1})(1 - q^{6j + 5})}.
\end{aligned}
\end{equation*}
thus
$$\overline{p_{S_1}}(n) = p_{S_2}(n).$$
Here the second line follows from the difference of two squares identity and the third line follows by noting that $\{m \in \mathbb{N} : m \equiv 1,2 \pmod 3\} = \{m \in \mathbb{N} : m \equiv 1,2,4,6 \pmod 6\}$.


text:
Q: Google Storage Image Serving Cache Using the GoogleStorageTools class's CloudStorageTools::getImageServingUrl and then replacing the storage object of the image with another image of the same name, the old image is still displayed upon subsequent calls of getImageServingUrl
I tried using CloudStorageTools::deleteImageServingUrl and then CloudStorageTools::getImageServingUrl again, but this doesn't work.
Is there any way to interact with Cloud Storage and tell it to refresh the image or the image URL? I'm guessing not, and am going to ensure the filenames are unique, instead, but it feels like there ought to be a way.

A: If you refresh the image, does the new image show up? It's possible there's a cache-control policy set on the image. Google Cloud Storage allows users to specify what cache-control headers should be sent to browsers, but I'm not sure whether app engine's getImageServingUrl respects that value.
As an experiment, could you try going to console.developers.google.com, heading over to "storage > cloud storage > storage browser", choosing the appropriate object, choosing "edit metadata," and then seeing whether there's a Cache-Control policy on the object? Try changing the cache-control section to "max-age=0,no-cache".


text:
Q: Field with one element example? $$\frac{1}{\mu(B)}\int_B \vert x \vert d\mu(x) = \frac{1}{p+1}$$
This formula holds for the unit ball in $\mathbb{Q_p}$. This formula also holds for
$\mathbb{R}$ when $p=1$. Should one expect $$\mathrm{Frac}(W_{1^{\infty}} (\mathbb{F_1}))=\mathbb{R}?$$
What (mathematical) criteria do people use to rule-out field with one element phenomena? What makes point counting formulas better (or worse)?

A: It is true that if $f(T)\in \mathbb Z[T]$ then,
  $$ \frac{1}{\mu_p(B)}\int_{\mathbb Z_p} f(\vert x \vert_p) d\mu_p(x) \to \frac{1}{\vert B \vert}\int_{B}f(\vert x \vert)dx \mbox{ as } p\to 1.$$
It is not in general true that
 $$ \frac{1}{\mu_p(B)}\int_{\mathbb Z_p} \vert f( x )\vert_p d\mu_p(x) \to \frac{1}{\vert B \vert}\int_{B}\vert f( x )\vert dx \mbox{ as } p\to 1.$$
When $f(x) = x^2-1$ we have
  $$\int_{\mathbb Z_p} \vert x^2-1 \vert_p d\mu(x) = \frac{1+p(p-2)}{p}+ \frac{1}{(p+1)p} \to 1/2 \mbox{ as } p \to 1 $$
and
 $$\frac{1}{2}\int_{-1}^1 \vert x^2-1\vert dx = 2/3.$$
http://imgur.com/a/m6KYA
A couple remarks:

*

*You should have also written $\mathbb Q_1 = \mathbb{R}$ instead of that terrible notation $\mathrm{Frac}(W_{1^{\infty}}(\mathbb{F}_1))$.

*The question as posed is a little stupid since if someone had a procedure for "ruling our phenomena" not only would they would probably have category in mind, but they would be able to compute with it. I think the correct answer is $\mathbb F_1$ numerology is justified when it can be categorified''. This is kind of a weak version of the statement "a conjecture is true when you can prove it". I guess a vague question deserves a vague answer.
The first part of the question seems to be about Arakelov geometry and replacing the place at infinity with the place 1. It seems that the answer is no. Another bad question would be to ask for more examples where it does make sense.
The last part of the original question can be made more precise:
-Are there examples of formulas for $|X(\mathbb F_q)|$ such that $X$ is definable in either  monoidal algebraic geometries or Borger's $\Lambda$-ring categorifications of schemes over $\mathbb F_1$ such that the point counting formula's in the category do not agree with $|X(\mathbb F_q)|$ as $q\to 1$? (if you know of another categorification that justifies $GL_n(\mathbb{F}_1)=S_n$ this question applies there too (Maybe Durov's Category?).)


text:
Q: Using multiple clauses in where What is the correct way to include multiple wheres in a LINQ call for OR
List<Pos> posList = DbContext.PosList
                             .Where<Pos>(p => p.Pos == "51000785" ||
                                         p => p.Pos == "123")
                             .ToList<Pos>();

A: The Linq where clause takes one expression and returns one bool value. Yours is taking two expressions each with their own return value. You would need to combine these two into one lambda expression that returns one value rather than the two separate ones in your example.
List<Pos> posList = DbContext.PosList
         .Where<Pos>(p => p.Pos == "51000785" || p.Pos == "123")
         .ToList<Pos>();


text:
Q: Utf-8 accent marks error only occuring in Chrome in Rails production on heroku I have a simple site that has spanish,german team names some with accent marks -  www.ftbll.net/predict/bundesliga. They appear as normal in development mode on chrome but when it's in production on heroku I get errors, e.g Atlético Madrid appears as Atlético Madrid
I have no idea what the problem is or how to solve it!

A: We could start with your meta tag, not sure if this is going to solve the problem. But I'm sure it's part of the problem.
Your meta tag appears as follows:
<meta>charset="utf-8"</meta>

And it should looks like this:
<meta charset="utf-8">


text:
Q: my alarmmanager sometimes not firing my alarmmanager sometimes not firing
Main_activity:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, tp1.getCurrentHour());
cal.set(Calendar.MINUTE, tp1.getCurrentMinute());
cal.set(Calendar.SECOND, 0);

long timeDif = cal.getTimeInMillis() - System.currentTimeMillis();
long horaFinal = System.currentTimeMillis() + AlarmManager.INTERVAL_DAY + timeDif;
long result = (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
long results = (horaFinal- System.currentTimeMillis())/1000;
long alarma;

if(result >= 0 && result < 60){
     alarma = cal.getTimeInMillis();
}else{
    alarma = horaFinal;
}

Intent intent = new Intent(this, Temporizador.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
        this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarma, pendingIntent);

    if (result >= 0 && result < 60) {
        Toast.makeText(this, "La alarma sonará en menos de un minuto.",
                Toast.LENGTH_LONG).show();
    } else if (result < 3600 & result >= 60) {
        result = result / 60;
        Toast.makeText(this,
                "La alarma sonará en " + result + " minutos.",
                Toast.LENGTH_LONG).show();
    } else if (result >= 3600) {
        int resultado = (int) (result / 3600);
        long minutos = (result % 3600) / 60;
        Toast.makeText(
                this,
                "La alarma sonará en " + resultado + " horas y "
                        + minutos + " minutos.", Toast.LENGTH_LONG)
                .show();
    }else{
       if(results >= 0 && results < 60){
           Toast.makeText(this, "La alarma sonará en menos de un minuto.",
                Toast.LENGTH_LONG).show();
       } else if (results < 3600 & results >= 60) {
        results /= 60;
        Toast.makeText(this,
                "La alarma sonará en " + results + " minutos.",
                Toast.LENGTH_LONG).show();
       }else if (results >= 3600) {
        int resultado = (int) (results / 3600);
        long minutos = (results % 3600) / 60;
        Toast.makeText(
                this,
                "La alarma sonará en " + resultado + " horas y "
                        + minutos + " minutos.", Toast.LENGTH_LONG)
                .show();
       }
    }

The "Temporizador" class I have the following:
package com.example.alarmarockfm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class Temporizador extends BroadcastReceiver {
    @Override

    public void onReceive(Context context, Intent intent) {
        /*Intent i = new Intent(this, EmisoraRadio.class );
        startActivity(i);*/
        Intent i = new Intent(context, EmisoraRadio.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

    }

}

And finally, in my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmarockfm"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmarockfm.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>
         <receiver android:name="Temporizador"></receiver>
         <activity android:name="EmisoraRadio"></activity>
         <activity android:name="Configuracion"></activity>
    </application>

</manifest>

Usually works, but if my app is running in the background fails, or if the phone is  a long time locked

A: You could try like this
SystemClock.elapsedRealtime() instead of System.currentTimeMillis()
And also see this difference
ELAPSED_REALTIME_WAKEUP :trigger the alarm since boot time and
  RTC_WAKEUP: trigger the alarm according to the clock time


text:
Q: How to iterate through a while loop of parameters to return the sum? if test $# -lt 1
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        args=0
        while args -eq "$#"; do
                echo $args
                shift
        done
fi

echo $sum
echo $n

The error I'm receiving is
./whileParamList: 15: ./whileParamList: args: not found
The while loop will increment to the previous parameter with a +=

A: Bash isn't designed for numerical calculations.  It's an orchestrator, not a "language" in the sense that C or Python is.  See more detail:

*

*Why is using a shell loop to process text considered bad practice?

The way I would do this would be something like:
mysum() (
  IFS=+
  bc<<<"$*"
)

Or perhaps:
mysum() (
  IFS=+
  echo "$(($*))"
)

Then call it like so:
$ mysum 5 89 83 7 0 2
186

A: Something like this i think it is ok:
if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        for arg in "$@"
        do
          echo "$arg"
          sum=$(($sum+$arg))
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"

If you prefer the parameter shift method, this also work:
if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        while [[ $# -ne 0 ]];
        do
          echo "arg=$1"
          sum=$(($sum+$1))
          shift
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"


text:
Q: Change default endpoint in IdentityServer 4 I was working around IdentityServer 4 (1.0.0-beta5).
By default, the endpoint for authentication is: '/connect/token'.
How can I change the default endpoints in IdentityServer, for instance to: '/api/login'?
Thanks

A: Right now you cannot change the endpoint URLs of the protocol endpoints. If you think this is needed, please open an issue on github.

A: it is a bit old question now, this is just another way that not seems much as a hack
IdentityServer4 provides a service called IEndpointRouter this service if was overridden with your custom logic will allow you to map the path requested by your client to the one of IdentityServer4 endpoints.
based on default implementation of IEndpointRouter (which is internal btw) i have written this class to do the mapping on my own.
internal class CustomEndpointRouter : IEndpointRouter
{
    const string TOKEN_ENDPOINT = "/oauth/token";

    private readonly IEnumerable<Endpoint> _endpoints;
    private readonly IdentityServerOptions _options;
    private readonly ILogger _logger;

    public CustomEndpointRouter (IEnumerable<Endpoint> endpoints, IdentityServerOptions options, ILogger<CustomEndpointRouter > logger)
    {
        _endpoints = endpoints;
        _options = options;
        _logger = logger;
    }

    public IEndpointHandler Find(Microsoft.AspNetCore.Http.HttpContext context)
    {
        if (context == null) throw new ArgumentNullException(nameof(context));

        if (context.Request.Path.Equals(TOKEN_ENDPOINT, StringComparison.OrdinalIgnoreCase))
        {
            var tokenEndPoint = GetEndPoint(EndpointNames.Token);
            return GetEndpointHandler(tokenEndPoint, context);
        }
        //put a case for all endpoints or just fallback to IdentityServer4 default paths
        else
        {
            foreach (var endpoint in _endpoints)
            {
                var path = endpoint.Path;
                if (context.Request.Path.Equals(path, StringComparison.OrdinalIgnoreCase))
                {
                    var endpointName = endpoint.Name;
                    _logger.LogDebug("Request path {path} matched to endpoint type {endpoint}", context.Request.Path, endpointName);

                    return GetEndpointHandler(endpoint, context);
                }
            }
        }
        _logger.LogTrace("No endpoint entry found for request path: {path}", context.Request.Path);
        return null;
    }

    private Endpoint GetEndPoint(string endPointName)
    {
        Endpoint endpoint = null;
        foreach (var ep in _endpoints)
        {
            if (ep.Name == endPointName)
            {
                endpoint = ep;
                break;
            }
        }
        return endpoint;
    }

    private IEndpointHandler GetEndpointHandler(Endpoint endpoint, Microsoft.AspNetCore.Http.HttpContext context)
    {
        if (_options.Endpoints.IsEndpointEnabled(endpoint))
        {
            var handler = context.RequestServices.GetService(endpoint.Handler) as IEndpointHandler;
            if (handler != null)
            {
                _logger.LogDebug("Endpoint enabled: {endpoint}, successfully created handler: {endpointHandler}", endpoint.Name, endpoint.Handler.FullName);
                return handler;
            }
            else
            {
                _logger.LogDebug("Endpoint enabled: {endpoint}, failed to create handler: {endpointHandler}", endpoint.Name, endpoint.Handler.FullName);
            }
        }
        else
        {
            _logger.LogWarning("Endpoint disabled: {endpoint}", endpoint.Name);
        }

        return null;
    }
}

internal static class EndpointOptionsExtensions
{
    public static bool IsEndpointEnabled(this EndpointsOptions options, Endpoint endpoint)
    {
        switch (endpoint?.Name)
        {
            case EndpointNames.Authorize:
                return options.EnableAuthorizeEndpoint;
            case EndpointNames.CheckSession:
                return options.EnableCheckSessionEndpoint;
            case EndpointNames.Discovery:
                return options.EnableDiscoveryEndpoint;
            case EndpointNames.EndSession:
                return options.EnableEndSessionEndpoint;
            case EndpointNames.Introspection:
                return options.EnableIntrospectionEndpoint;
            case EndpointNames.Revocation:
                return options.EnableTokenRevocationEndpoint;
            case EndpointNames.Token:
                return options.EnableTokenEndpoint;
            case EndpointNames.UserInfo:
                return options.EnableUserInfoEndpoint;
            default:
                // fall thru to true to allow custom endpoints
                return true;
        }
    }
}

public static class EndpointNames
{
    public const string Authorize = "Authorize";
    public const string Token = "Token";
    public const string DeviceAuthorization = "DeviceAuthorization";
    public const string Discovery = "Discovery";
    public const string Introspection = "Introspection";
    public const string Revocation = "Revocation";
    public const string EndSession = "Endsession";
    public const string CheckSession = "Checksession";
    public const string UserInfo = "Userinfo";
}

Then you just need to register this CustomEndpointRouter service like below
services.AddTransient<IEndpointRouter, CustomEndpointRouter>();

please note that this updated path's will not appear in discovery document

A: You can try this
services.AddIdentityServer(options => options.PublicOrigin = "URL")
check this link.
http://amilspage.com/set-identityserver4-url-behind-loadbalancer/

A: Once you setup Identity Server 4 at Startup - you could use this "hack" and update the endpoint paths:
        var builder = services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients());

        builder.Services
            .Where(service => service.ServiceType == typeof(Endpoint))
            .Select(item => (Endpoint)item.ImplementationInstance)
            .ToList()
            .ForEach(item => item.Path = item.Path.Value.Replace("/connect", ""));

Basically - Endpoint's such as TokenEndpoint, AuthorizeEndpoint classes are internally registered once you call AddIdentityServer - when it calls AddDefaultEndPoints method. Now Endpoint's are iterated upon receiving each request to match the requested Url; so changing the path would immediately take effect.

Please note that in the above example - I have removed all the
  "/connect" values from any of the paths that were prefixed with it.


text:
Q: 4-Dimensional database grid Right now, I have a two-dimensional grid that shows the (1) requirements for a particular (2) service. It looks something like this on the front-end:
                FEATURE          TRAILER           MARKETING
DVD               x
Streaming         x                x
Theatrical        x                                   x

How I am storing it now in the database is:
`service`
  - id
  - name (e.g., "DVD")

` requirements`
  - id
  - name (e.g., "Marketing")

`requirements_grid`
  - service_id
  - requirement_ids (csv of all requirement ids)

Now I can say describe something like, "For a DVD, I need a Feature as a requirement."
I now need to add two additional parameters, (3) content type; and (4) provider. These will be changes (additions or removals) from the default requirement grid.
This would allow me to describe something like "For a Television (content type) DVD for Fox (provider), I need a Feature and a Trailer.
How would I structure the database to store this? And also, what would be a possible way to display this on the front-end?

A: To answer your first question - how to store a four dimensional grid - just continue in the direction you're already headed, but normalize the requirement_ids column.
So in the current schema, if you have
| service_id | requirement_ids |
|          1 |           1,2,3 |
|          2 |               2 |

In the new schema, you get:
| service_id | requirement_id |
|          1 |              1 |
|          1 |              2 |
|          1 |              3 |
|          2 |              2 |

After this change, adding new dimensions is really easy:
`service`
  - id
  - name (e.g., "DVD")

` requirements`
  - id
  - name (e.g., "Marketing")

`content_type`
  - id
  - name

`provider`
  - id
  - name

`requirements_grid`
  - service_id
  - requirement_id
  - content_type_id
  - provider_id

I can't help you with the other question. Consider moving it to a separate Stackoverflow question.

A: CREATE TABLE requirement
(service_id INT NOT NULL
requirement_id INT NOT NULL
content_type --type??
provider --type??,
PRIMARY KEY ? (service_id,requirement_id,content_type,provider type));

A: This is the schema I chose to go with based on feedback:
`requirements_grid`
  - service_id NOT NULL
  - requirement_ids (csv of all requirement ids) NOT NULL
  - content_type
  - provider

Keeping the csv field just makes it a little easier to access for me.


text:
Q: Why is Mission Control lagging when using the discrete GPU in Mavericks? I just switched to Mavericks (10.9.4) from the latest Mountain Lion and noticed that my screen, especially noticeable with Mission Control, lags a bit when using the discrete GPU.
I've recorded my screen and uploaded a video to show the problem.
I switch to the dedicated card using an utility called gfxCardStatus, but using the "official" method through System Preferences -> Energy Saver -> High performance yields the same result.
Additionally my mouse speed seems to be bit lower when using the dedicated GPU. This is not visible in the video.
I'm on a 15 inch Mid 2009 MacBook Pro 5,3 with an integrated GeForce 9400M card and a dedicated GeForce 9600M GT. All worked fine before on Mountain Lion. The Mavericks system requirements state that my laptop is supported.

I've tinkered around and found that the GPU that is working on startup functions correctly. So if I restart while the discrete GPU is used all works fine and switching to the integrated GPU now yields in the screen lagging as shown in the video above. Switching the GPU back to the one that was in use during startup gives smooth graphics.
How can I find the origin of this problem? How can I solve it?


text:
Q: How to customize calendar selection in ASP.NET i'm trying to come up with a DateTime Picker in ASP.Net using textBox, Calendar, Button and Updatefields.
if a user clicks a button the panel with a hidden calendar will become visible, and if a user selects a date calendar's visibility will become false and he date will be assigned to textBox.
My problem comes if a user wants to change month because in this case calendar will disappear because selectionChange is being triggered.
My question is how can I fish out the changing of the month and bound the hiding of the panel only if a date is selected?
thank you very much in advance.
here are the code samples:
front part:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>
    <asp:TextBox ID="TextBox2" runat="server" />
            <asp:ImageButton ID="Imbut" runat="server" ImageUrl="imagesNew/calender.png" Height="17px" Width="17px" />
    </ContentTemplate>
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Calendar1" EventName="SelectionChanged" />
        </Triggers>
    </asp:UpdatePanel>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <asp:Panel ID="Panel1" runat="server">
            <asp:Calendar ID="Calendar1" runat="server" Height="129px" Width="209px">
            </asp:Calendar>
        </asp:Panel>
        </ContentTemplate>
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Imbut" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

back part
Protected Sub Imbut_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Imbut.Click
    Panel1.Visible = True
End Sub

Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Calendar1.SelectionChanged

        TextBox2.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy")
        Panel1.Visible = False

End Sub

A: I struggled with a similar problem. The problem is (as you stated) on the postback the control gets reset. I never found a means to do this elegantly with asp.net controls. I was able to accomplish this using the jQuery calendar and asp:hidden field. Keeping it client side via javascript I was able to allow the user to navigate the calendar change dates etc. When a date was selected the values were set to both a textbox within the ui as well as a hidden field then on submission, the value within the textbox or hidden field was picked up server side and used (in my situation) as a filter parameter.


text:
Q: VB.net Iterating Structures and setting data types I am using the following structure many times throughout my code to pass a set of data to a function:
Public Structure MyStruct
    Dim ResourceID As String
    Dim RSRCName As String
    Dim CommercialType As String
    Dim ParticipantName As String
    Dim ASReserveZone As String
    Dim SCADAStatusQuality As String
    Dim SCADAStatus As String
    Dim SCADAMWQuality As String
    Dim ManualDispatchReason As String

    Dim RegUpQual As Boolean
    Dim RegDownQual As Boolean
    Dim SuppQual As Boolean
    Dim SpinQual As Boolean
    Dim UseEmergencyLimits As Boolean
    Dim FollowLastDispatch As Boolean

    Dim ASOfferCurveDict As HybridDictionary

    Dim XIC As Integer
    Dim PriceBased As Integer
    Dim PNodeID As Integer
    Dim Committed As Integer
    Dim CommitmentStatus As Integer
    Dim ManualDispatch As Integer
    Dim LastApprdNumOfIntervalsToMax As Integer

    Dim MWCurve() As Double
    Dim EnergyOfferCurve() As Double
    Dim PlannedMW As Double
    Dim SCADAMW As Double
    Dim InitialOnHours As Double
    Dim LastApprdDispatchMW As Double
    Dim TotalRampedCRDeployMW As Double
End Structure

Dim Struct as MyStruct

I can use Struct = Nothing to reset the data, but I would rather iterate through the structure and set all the numeric values to 999999999. Any idea how to do this?

A: You could do it with reflection, but I wouldn't necessarily recommend it.  I'd sooner just add a Clear or Reset method to the structure which sets all the values to their default values.  Another option would be to set the default values when the fields are declared:
Public Structure MyStruct
    ' ...
    Dim XIC As Integer = 999999999
    Dim PriceBased As Integer = 999999999
    Dim PNodeID As Integer = 999999999
    ' ...
End Structure

Then, to reset a variable to all the default values, just do this:
myVariable = New MyStruct()

I should also mention, unless it really needs to be a structure for some reason, you should change this to a class.  It's quite a lot of data to be passing around on the stack all the time.


text:
Q: Put build number in web.config I'm trying to get my build number into the web.config of an ASP.Net MVC project (long story, but there is a reason)... something like this:
<appSettings>
    <add key="version" value="1.0.3936.27150" />
</appSettings>

Right now, I'm doing it with an executable on the post-build event by looking at the assembly to get the version and stuff that into the web.config. It works, but isn't exactly what I was looking for.
Any easy way to do this easier / cleaner? Thanks for any advice / suggestions.

A: You have a few options here, the first being the one you picked, which is old skewl.  The next option would be to use a Visual Studio Macro... this will only work in Visual Studio and on the system that it was configured on.  The next two options would be the best.  Use an MSBuild script as a post build event... or a NAnt script as a post build event to make the mod.  I would lean in favor of the NAnt my self, but then I have a black belt in NAnt.  :-)

A: I had to also place the build number in the web.config before deploying the project. I followed the tutorial here  http://www.ewaldhofman.nl/post/2010/05/13/Customize-Team-Build-2010-e28093-Part-5-Increase-AssemblyVersion.aspx.
Since the above tutorial did not exactly show me how to modify the web.config I had to modify the custom activity (code below):
 [BuildActivity(HostEnvironmentOption.All)]
public sealed class UpdateWebConfigWithBuild : CodeActivity {

    // Define the activity arguments of type string
    [RequiredArgument]
    public InArgument<IBuildDetail> BuildDetail { get; set; }

    // The SourcesDirectory as initialized in the Build Process Template
    [RequiredArgument]
    public InArgument<string> SourcesDirectory { get; set; }

    // The SourcesDirectory as initialized in the Build Process Template
    [RequiredArgument]
    public InArgument<string> TFSBuildNumberAppSettingName { get; set; }

    public OutArgument<string> TextOut { get; set; }

    // If your activity returns a value, derive from CodeActivity<TResult>
    // and return the value from the Execute method.
    protected override void Execute(CodeActivityContext context) {
        // Obtain the runtime value of the Text input argument
        // Contains the build number
        IBuildDetail buildDetail = context.GetValue(this.BuildDetail);
        // The TFS directoty
        string sourcesDirectory = context.GetValue(this.SourcesDirectory);
        // web config app setting
        string TFSBuildNumberSetting = context.GetValue(this.TFSBuildNumberAppSettingName);

        // output String
        string output = String.Empty;

         // Get all AssemblyInfo files
        foreach (string file in Directory.EnumerateFiles(sourcesDirectory,"web.config", SearchOption.AllDirectories)) {
             // IS tag founds
            bool settingFound = false;

            FileAttributes attributes = File.GetAttributes(file);

            // Remove readonly attribute
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
                //Remove readonly
                File.SetAttributes(file,attributes^FileAttributes.ReadOnly);
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(file);
            // iterate through all the app settings to find the TFS BUILD
            foreach (XmlNode node in xmlDoc.SelectNodes("/configuration/appSettings/add")) {
                // MATCH
                if (node.Attributes.GetNamedItem("key") != null && node.Attributes.GetNamedItem("value") != null && node.Attributes.GetNamedItem("key").Value.Equals("TFSBuildNumber")) {
                    node.Attributes.GetNamedItem("value").Value = buildDetail.BuildNumber;
                    settingFound = true;
                    output += "MODIFIED with BuildNumber " + buildDetail.BuildNumber.ToString() + " :" + file + "\n";
                    break;
                }
            }
            // if the app setting is not found then add it
            if (!settingFound) {
                XmlNode node = xmlDoc.SelectSingleNode("/configuration/appSettings");
                if (null != node) {
                    XmlElement elem = xmlDoc.CreateElement("add");
                    XmlAttribute attrKey = xmlDoc.CreateAttribute("key");
                    attrKey.Value = "TFSBuildNumber";
                    XmlAttribute attrVal = xmlDoc.CreateAttribute("value");
                    attrVal.Value = buildDetail.BuildNumber;
                    elem.Attributes.Append(attrKey);
                    elem.Attributes.Append(attrVal);
                    node.AppendChild(elem);
                    output += "ADDED with BuildNumber " + buildDetail.BuildNumber.ToString() + " :" + file + "\n";
                }
            }
            // Save file
            xmlDoc.Save(file);

            //add readonly attribute back to web.config file
            File.SetAttributes(file,attributes | FileAttributes.ReadOnly);
        }
        // Set the values
        context.SetValue<string>(this.TextOut,output);
    }


text:
Q: ¿Cómo insertar una imagen en la columna (jsPDF autoTableHtmlToJson)? no me muestra la imagen siendo que lo hago mal y la muestra la tabla pdf no
Codigo
var res2 = pdf.autoTableHtmlToJson(document.getElementById("dataTable1"));
pdf.autoTable(
    [![res2][1]][1].columns,
    res2.data,
    {
        margin: {top: 300, left:55, right:100, width: 10000}
    }
)


text:
Q: link dll and jar file to android studio This question might seem too basic but I'm struggling a lot about this stuff, please help me or guide me.
I downloaded opencv (open source computer vision) libraries and I want Android Studio to be able to use those libraries.
I checked this answer also-How to use opencv in android studio using gradle build tool?
but this answer talks about having opencv-android-sdk and nowadays I think opencv has not anything like opencv-android-sdk , so I couldn't follow that answer.
Now the main point is, what I downloaded and extracted has a folder named java , there is a opencv-320.jar file and two folder x86 and x64, x64 folder contains opencv_java320.dll file. I believe these two files are only files needed to get opencv libraries in Android Studio. But I don't know how it can be done. Please help me.

A: You should not be using any dll or jar file that is not specifically for Android.
OpenCV has an Android version: http://opencv.org/platforms/android/
Follow the instructions and example there in order to use it.


text:
Q: Changing Div with URL I am trying to make a navigation bar on the left.
|   1   |
|   2   |
|   3   |

I was wondering how facebook does their left navigational bar because when you click Messages on their bar, it turns into www.facebook.com?sk=inbox.
How do you change ur main div changing your url? Do you put

but then I was wondering what the action was that changes the div?
Would I have to use $_Request['sk']?
Thanks

A: I have done something similar to this before:
I had a class called navigation and in my main nav ul I had the following snippet:
    foreach($aAllPages as $key => $value){

        $sOutput .= '
'.$value.'
'."\n";

    }

After I have started the function I set the following:
$pageManager = new PageManager();

        $aAllPages = $pageManager->getAllPages();

The page manager was the model name that had a function called getAllPages that processed the specific data from the DB

A: If I understand you correctly, I think you are referring to how Facebook modifies the URL of the page while making an AJAX call to populate the main div of the page with the new content. If you notice in IE the URL will look like

http://www.facebook.com/#!/?sk=inbox

instead of

http://www.facebook.com/?sk=inbox

Facebook is taking advantage of HTML5 features for modifying the history state (https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history).
This SO post (http://stackoverflow.com/questions/5527617/using-html5-pushstate-in-ie9) points to a history plugin that will take advantage of the new HTML5 features as well as fall back gracefully to older browsers with hashchange functionality.


text:
Q: GMAT related question: If the standard deviation of $a,b$ and $c$ is $d$. What is the standard deviation of $105\%$ of $a$ ,$105b/100$ and $1.05c$? GMAT-related question: If the standard deviation of $a,b$ and $c$ is $d$. What is the standard deviation of $105\%$ of $a$ ,$105b/100$ and $1.05c$?
A)$d$
b)$5d$
c)None of these
d)$125\%  d$
e)$1.05d$
From the above, we know that the mean equals $(a+b+c)/3$ and that $105\%$ of $a$ can be expressed as $1.05a; 105b/100$ as $1.05b$, so the answer should be option e). More than the solution, I would like to know the intuition/strategy in order to solve this problem efficiently. It is a GMAT advance problem.

A: If a random variable $X$ has standard deviation $\sigma$ = $d$, then its variance $\sigma^2=d^2$. Also note that $Var(aX)=a^2Var(X)=a^2\sigma^2$. To find the standard deviation, you simply have to again find the square root. Thus the answer will be $(e)$. Hope this helps.


text:
Q: Scala Play Framework on Windows NoClassDefFoundError out of the box I am trying to run the starter scala Play Framework code on my windows machine. I run:
git clone https://github.com/playframework/play-scala-starter-example

import it into IntelliJ, and type sbt run on the command line. It runs the server on port 9000, but when I try to access the page, it fails with a bunch of java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter. So it fails right out of the box. I don't know if it has to do with me using Windows. Any ideas?

A: This is because you're using Java 9
You need to add --add-modules=java.xml.bind option to your JVM. For example in Windows you need to go to the folder your project resides at
.\sbt-dist\bin

and change set _JAVA_OPTS=%JAVA_OPTS% to set _JAVA_OPTS=%JAVA_OPTS% --add-modules=java.xml.bind in sbt.bat


text:
Q: Deleting the ActiveX textbox and command buttons without using VBA i.e directly from sheet I am not able to understand the working of activex controls:
1) I inserted a text box and command box on my worksheet
2) I double-clicked on them and the VBA editor opens
3) I typed some code and ran it

Now, when I go back to the worksheet and try to delete any of those, I am not able to. Because right-click on those boxes is not working and left-click only runs the program.

Please help