text:
Q: where can I find new themes for SugarCRM? I'm in version 5.2 I would like to download new themes for sugar crm...I have looked for it in internet but I haven't found any link where I can download themes. Can you help to me? Thanks

A: Usually you just make them yourself, either starting from scratch or customizing the existing themes (Documentation).
It is possible to download some themes, but they usually require some (minor) changes, due to SugarCRM version differences:

*

*http://www.sugarforge.org/softwaremap/trove_list.php?form_cat=335

*http://www.crmthemeclub.com/en/

A: For developing your own theme this GitHub project by Epicom is a great starting point: Epicom/Google theme
If you aren't looking to make your own theme for SugarCRM check out the themes available here: SugarOutfitters Themes. So far the Google Style SugarTheme has been the most popular. However, EasyTheme has some nice built in basic reporting features.


text:
Q: Windows Desktop Gadgets crash I suddenly started getting
"Windows Desktop Gadgets has stopped working."
The crash details are:
Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: sidebar.exe
  Application Version:  6.1.7100.0
  Application Timestamp:    49ee9780
  Fault Module Name:    kernel32.dll
  Fault Module Version: 6.1.7100.0
  Fault Module Timestamp:   49eeaac7
  Exception Code:   c0000005
  Exception Offset: 0000000000003892
  OS Version:   6.1.7100.2.0.0.256.1
  Locale ID:    1033
  Additional Information 1: d8fd
  Additional Information 2: d8fd8161e9ac0930383dc216f4c34d70
  Additional Information 3: a87e
  Additional Information 4: a87eb7be9617da7857e04259db193484

It happened while in the midst of installing the software that comes with Logitech's Webcam Pro 9000, which might be related, but it won't start at all any more. Using Windows 7 RC build 7100.

A: I would first suggest that you try and restore the Default Gadgets. From here:

*

*Control Panel

*Appearance and Personalization

*Restore desktop gadgets installed with Windows

This should reset the setting and get it working. Also according to my understanding the Gadgets will NOT work if you have UAC disabled. If you prefer not to be bugged by the popup confirming permission you can change to silent elevation as described on TechNet here:

*

*Log on to a Windows Vista computer with an administrator account in Admin Approval Mode.

*Click the Start button, click Run, type secpol.msc, and then click OK.

*At the User Account Control dialog box for the Microsoft Management Console, click Continue.

*In Local Security Settings, expand Local Security Settings, expand Local Policies, and then expand Security Options.

*Right click the User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode setting and select Properties.

Lastly, uninstall the Logitec Software and see if the problem still exists. The few references I have seen to this error seems to be related to the Logitech software, and it may be worthwhile (althought I suspect you have already) to check for newer drivers, or alternatively check if there is newer drivers on Windows Update. If the drivers is not the problem and it's the software to control the device, you may be out of luck. I am not aware of any replacement software, but most messenger client for examples can natively read the cams without the need for the official software.
Disclaimer: As a rule I never install the software that comes with the device, I rarely if ever use it or need it

A: If you kill the LVPrS64H.exe and LVPrcSrv.exe processes, it will start working.  And then you can uninstall the logitech webcam software without rebooting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add extra attribute in the 'Page Attribute' section in wp-admin for pages? I would like to add a select list in the Page Attribute box you see on the right side in the administration interface for pages.
Does anyone know if that is possible?
Or at least add a custom box below this box?

A: Woohoo! As of WP 4.9.0, there is an action hook to add code to the Page Attributes meta box: 'page_attributes_misc_attributes'. See the Codex for reference.
Example:
function wpse44966_page_attributes( $post ) {

    wp_nonce_field( 'wpse44966_page_attributes_nonce', 'wpse44966_page_attributes_nonce' );
    ?>

        <?php _e( 'Option Label', 'textdomain' ); ?>
        <input id="wpse44966_option" name="wpse44966_option" type="checkbox" value="1" style="margin-left: 5px;"<?php if( isset( $post->wpse44966_option ) && $post->wpse44966_option ) echo ' checked="checked"'; ?>>

    <?php
}
add_action( 'page_attributes_misc_attributes', 'wpse44966_page_attributes' );

function wpse44966_metabox_save_post( $post_id ) {
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if( ! isset( $_POST['wpse44966_page_attributes_nonce'] ) || ! wp_verify_nonce( $_POST['wpse44966_page_attributes_nonce'], 'wpse44966_page_attributes_nonce' ) ) return;
    if( ! current_user_can( 'edit_post', $post_id ) ) return;
    $wpse44966_option = (int) ( isset( $_POST['wpse44966_option'] ) && $_POST['wpse44966_option'] );
    update_post_meta( $post_id, 'wpse44966_option', $wpse44966_option );
}
add_action( 'save_post', 'wpse44966_metabox_save_post' );

A: There are no convenient hooks to add something to that box.
You could do one of two things.
1. Add a new Meta Box
You do this by hooking into the add_meta_boxes action and calling add_meta_box.  You can specify a callback function in your call to add_meta_box.  That callback will take care of echoing out your select list.
<?php
add_action( 'add_meta_boxes', 'wpse44966_add_meta_box' );
/**
 * Adds the meta box to the page screen
 */
function wpse44966_add_meta_box()
{
    add_meta_box(
        'wpse44966-meta-box', // id, used as the html id att
        __( 'WPSE 44966 Meta Box' ), // meta box title, like "Page Attributes"
        'wpse44966_meta_box_cb', // callback function, spits out the content
        'page', // post type or page. We'll add this to pages only
        'side', // context (where on the screen
        'low' // priority, where should this go in the context?
    );
}

/**
 * Callback function for our meta box.  Echos out the content
 */
function wpse44966_meta_box_cb( $post )
{
    // create your dropdown here
}

2. Remove the Default Page attributes meta box, add your own version
All the content on the post editting screen, with the exception of the main editor and title area, is a meta box.  You can remove them by calling remove_meta_box, then replace them with your own.
So, first up, modify the add function above to include a remove meta box call.  Then you'll need to copy the page_attributes_meta_box function body from wp-admin/includes/meta-boxes.php and put your stuff below it.
<?php
add_action( 'add_meta_boxes', 'wpse44966_add_meta_box' );
/**
 * Adds the meta box to the page screen
 */
function wpse44966_add_meta_box( $post_type )
{
    // remove the default
    remove_meta_box(
        'pageparentdiv',
        'page',
        'side'
    );

    // add our own
    add_meta_box(
        'wpse44966-meta-box',
        'page' == $post_type ? __('Page Attributes') : __('Attributes'),
        'wpse44966_meta_box_cb',
        'page',
        'side',
        'low'
    );
}

/**
 * Callback function for our meta box.  Echos out the content
 */
function wpse44966_meta_box_cb( $post )
{
    // Copy the the `page_attributes_meta_box` function content here
    // add your drop down
}

Either way you do this, you'll need to hook into save_post to save the value of your field with add_post_meta and/or update_post_meta.
<?php
add_action( 'save_post', 'wpse44966_save_post' );
/**
 * Save our custom field value
 */
function wpse44966_save_post( $post_id )
{
    // check nonces, permissions here
    // save the data with update_post_meta
}

This tutorial might help you out.


text:
Q: Should JUnit test cases really sit next to the class undertest? C# developer here, working through basic Java examples. JUnit test cases appear to be packaged with the class under test in the tutorials I've seen. Is that right? In C# we create a new Test project - surely in Java the common pattern is similar?

A: As I said in my comment, these days the defacto standard is the Maven structure where tests are in the same package (Namespace in C#) but under a different source roots (src/main/java and src/test/java respectively), though you are free to put the tests wherever you want.
There are however, some benefits to having the tests in the same package because the Java visibility rules mean the test has access to both protected and package private methods, allowing it to be that little bit more interment with the class under test (this isn't something you should rely on all the time but it's useful now and again).
Anyway, I digress, the structure would look something like this:
my-project
+ src
  + main
  | + java
  |   + com
  |     + company
  |       + MyNewClass
  + test
    + java
      + com
        + company
          + MyNewClassTest

In the Java world it's the norm to have an external build tool, Maven being the current flavor of the month.  It's supported by most IDEs, which will recognize this structure when they're sync'd with the Maven project file (pom).
That doesn't mean you can't use this structure if you don't used Maven, you'll just have to manually add additional source roots to the IDE project/module.
In IntelliJ, you do this in the Project Settings -> Modules on the Sources tab.  You do something similar in Eclipse, but not sure the exact path (sure somebody will add how in the comments :-)


text:
Q: Front-End Business Rules / JSON I am working on a project that now needs business rules. One design discussed is to make API calls (based on the form we are on) which responds with business rules for form input. I am unsure if this is the best way. The business rules are in JSON, but the business rules server actually has a business rules engine (so the engine crunches the rules and spits out JSON).
Some background:
In our web app, various forms exist, such as for logging in, registering, editing a profile, etc. Maybe 25-30 forms. They are content managed.
For any of these forms, various rules exist to show or hide fields, or present error messages on the form based on logic such as a field name being too long, too short, or not meeting a regular expression. Other things such as required field validators, etc, exist.
The idea was to have everything centralized in a different environment (as mentioned above...on the business rules server).
I am concerned about making so many calls to a server to get simple rules like a first name being required, or showing or hiding a button based on if a person sells a certain number of widgets, etc.
Perhaps a better solution would be to have this rules engine publish to our server, and we just call the local server rather than make API calls from the front end each time.
What does everyone think? Is it natural to make API calls from our .net forms (using jquery) to get our rules for each form, each time?
Thanks!

A: You will have to answer several questions in order to know what will work best. These are in no particular order.
Are your business rules static based on the question/field being shown/hidden?
If they are static, you can cache the business rules locally (on the page or server as appropriate). If they aren't, can you determine what the output difference is and then cache that?  Also, how often do the rules change?
Can the value(s) selected/entered affect another field's business rules?
If I choose a truck instead of a car, will I still be allowed to select a hatchback type of vehicle? Should an electric motor driven vehicle have a choice for numbers of cylinders for the engine?
Does your validation change based on values selected/entered?
Selecting car manufacturer A sets your VIN validation to some number of letters, followed by some number of digits, where manufacturer B has letters, numbers, a couple of glyphs, and more numbers.
Does your data change based on values selected/entered?
Cascading dropdowns are very common for this type of item; manufacturers listed in the first dropdown, models in the second.
Where will the application be run?
If it will be on your network, it is possible that your throughput will be sufficiently fast that you don't need to consider caching. You may also have caching routers between you and the business rule server that will limit the number of calls to the business rule server.
How many users will be using the application?
If this number is small enough, then the added expense of caching will probably not be worth it.
How much network overhead will the application add?
You are going to have to measure this. It will depend on more factors than I can list here easily. Ask yourself if the trade off in bandwidth is worth the difference in added complexity of your application.


text:
Q: How to execute sh command set in shell variable? I have this linux command:
candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> /dev/null > /tmp/can.log &
It works correctly when I run it directly in shell.
I want to add it in my script with this method:
#!/bin/sh

# I tried this 2 syntax
# MYVAR="candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> /dev/null > /tmp/can.log &"
MYVAR='candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> /dev/null > /tmp/can.log &'
$MYVAR

When I execute my script I get this error:
SIOCGIFINDEX: No such device
I have tested these script and it works:
#!/bin/sh

MYVAR='ls -l'
$MYVAR

Result:
total 8
drwxr-xr-x  2 root root     0 Nov  5  2015 bin
drwxr-xr-x  2 root root     0 Oct 22  2015 boot
drwxr-xr-x  5 root root 13460 Jan  1 00:00 dev
drwxr-xr-x  8 root root     0 Nov  5  2015 etc
drwxr-xr-x  3 root root     0 Nov  5  2015 home
-rwsr-xr-x  1 root root   258 Nov  5  2015 init
drwxr-xr-x  3 root root     0 Nov  5  2015 lib
drwxr-xr-x  3 root root     0 Nov  5  2015 media
drwxr-xr-x  3 root root     0 Nov  5  2015 mnt
dr-xr-xr-x 67 root root     0 Jan  1 00:00 proc
drwx------  2 root root     0 Oct 22  2015 root
drwxr-xr-x  4 root root     0 Jan  1 00:00 run
drwxr-xr-x  2 root root     0 Nov  5  2015 sbin
dr-xr-xr-x 14 root root     0 Jan  1 00:00 sys
-rwxr-xr-x  1 root root    33 Jan  1 00:04 test
drwxrwxrwt  2 root root     0 Jan  1 00:00 tmp
drwxr-xr-x  9 root root     0 Oct 22  2015 usr
drwxr-xr-x  7 root root     0 Oct 22  2015 var

I can't see the error, can you explain me the error?

A: Better (and safer) to use a shell function rather that a variable:
#!/bin/sh

myfunc() {
   candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2>/dev/null >/tmp/can.log &
}

# call it
myfunc


text:
Q: how do I compare a character with a string? #include <iostream>
#include <string>//needed to make string array
#include <fstream>//Needed for redaing in from external file
#include <cstdlib>//needed for rand() function (for random word)
#include <ctime>//needed for time() funtion to seed rand()
using namespace std;

/*
    April 25,2020
    This program will take read in a random word from an external file and use it for a game of hang man */

void greeting();
void wordPick();

int main()
{
    char playAgain;
    int tries;
    char playerGuess;
    string secretWord;

    greeting();
    ifstream inFile("randwords.txt");
    if (inFile.is_open())
    {
        string wordlist[10];
        for(int i = 0; i < 10; ++i)
        {
            inFile >> wordlist[i];
        }
        srand(time(0));

        string secretword = wordlist[rand() % 10];
        cout << secretword << endl;
        inFile.close();
    }

    //wordPick();

    //ask user to guess a letter
    cout << "Please guess a letter: " << endl;
    cin >> playerGuess;
    if (playerGuess == secretWord[0])
    {
        cout << "Thats correct!" << secretWord [0];
    }
    else if (playerGuess == secretWord[1])
    {
        cout << "thats correct!" << secretWord[1];
    }
    else if (playerGuess == secretWord[2])
    {
        cout << "Thats correct!" << secretWord[2];
    }

    cout << "Do you want to play again? Y or N: ";
    cin >> playAgain;
    while (playAgain != 'Y' && playAgain != 'y' && playAgain != 'N' && playAgain != 'n')
    {
        cout << "Invalid, please enter Y or N: ";
        cin >> playAgain;
    }

    return 0;
}

void wordPick()//reads in external file and puts it in an array for a library of words to randomly choose
{
    ifstream inFile("randwords.txt");
    if (inFile.is_open())
    {
        string wordlist[10];
        for(int i = 0; i < 10; ++i)
        {
            inFile >> wordlist[i];
        }
        srand(time(0));

        string secretword = wordlist[rand() % 10];
        // cout << secretword << endl;
        inFile.close();
    }
}

void greeting()//welcomes the player to the game and starts the game
{
    string name;

    cout << "Hello, Player welcome to Hangman! " << endl;
    cout << "What should I call you?" << endl;
    cin >> name;

    cout << "Hello " << name << ", in this game you will try to guess a random 3 letter word." << endl;
    cout << "You will have at least 6 ties to guess the word or else the drawing will complete. Good luck!" << endl;

What I am attempting to do is to check if the char playerGuess is one of the characters in string secretWord, but it isn't outputting the letter even if it is correct. Maybe there is an easier way to compare that I'm just missing?
I thought since this still compares that it should work, but it's just ending the program after guessing the letter.

A: You assigned the randomly chosen word to secretword (with small w), but the judge is based on secretWord (with large W), to which no word is assigned.
The part
        string secretword = wordlist[rand() % 10];
        cout << secretword << endl;

should be
        secretWord = wordlist[rand() % 10];
        cout << secretWord << endl;

Also note that you mustn't declare secretWord in the if block, or the assignment won't be visible to the judge part.


text:
Q: /bin/sh: zypper: not found (Docker) I am trying to create and image. But when I run docker build. I keep getting the error:
Step 6/7 : RUN zypper update && zypper upgrade -y && zypper install -y git
 ---> Running in 81e84f3be4f0
/bin/sh: zypper: not found
The command '/bin/sh -c zypper update && zypper upgrade -y && zypper install -y git' returned a non-zero code: 127

First I was getting something similar with git not being found. So after a bit of Googling, i found out that I probably need to install git in the docker file.
So I added something like:
FROM maven:3.8.4 AS maven
FROM eclipse-temurin:11-jdk-alpine

RUN mkdir -p $HOME/images/lib/ && cd $HOME/images/lib/

RUN zypper update && zypper upgrade -y && zypper install -y git

#RUN apt-get update && apt-get upgrade -y && apt-get install -y git

RUN git clone MY_GIT_URL

But it errors out on the second line.
My Docker info is :
Client:
 Context:    default
 Debug Mode: false

Server:
 Containers: 9
  Running: 0
  Paused: 0
  Stopped: 9
 Images: 8
 Server Version: 20.10.17-ce
 Storage Driver: btrfs
  Build Version: Btrfs v4.15
  Library Version: 102
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux oci runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 10c12954828e7c7c9b6e0ea9b0c02b01407d3ae1
 runc version: v1.1.4-0-ga916309fff0f
 init version:
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.14.21-150400.24.33-default
 Operating System: openSUSE Leap 15.4
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 9.714GiB
 Name: localhost.localdomain
 ID: U76D:CEPC:3L3J:ZTTL:C5UQ:TOEZ:DLXA:5NQQ:HOQ7:SHRC:KXBZ:HLJE
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Username: MY_USERNAME
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

A: The container image eclipse-temurin:11-jdk-alpine is based on Alpine Linux, not Suse. Thus, to install operating system packages, use apk instead of zypper. For example:
RUN apk update && apk add git


text:
Q: Specify which file the webpack runtime should be in I'm trying to configure code splitting in a way that...

*

*does not include the webpack runtime in all the output files

*does not require an additional common.chunks.js file for the webpack run time

*allows me to specify which output file to include the webpack runtime in.

In my specific example, I have a header.js file, that needs to run before the rest of the page loads. I would like to specify which modules exist in this file, AND the webpack runtime.
And I have a bundle.js file, which is the bulk of the code for my app. Since the webpack runtime will be loaded in header.js, I'd like to ensure it's not included in bundle.js
My entry point looks something like this
entry: {
    header: './src/js/doStuffInHeader.js', //<-- I need webpack in here
    bundle: './src/js/main.js'             //<-- not in here
},

The webpack documentation says,

Entry chunk
  An entry chunk contains the runtime plus a bunch of modules. If the chunk contains the module 0 the runtime executes it. If not, it waits for chunks that contains the module 0 and executes it (every time when there is a chunk with a module 0).
Normal chunk
  A normal chunk contains no runtime. It only contains a bunch of modules. The structure depends on the chunk loading algorithm. I. e. for jsonp the modules are wrapped in a jsonp callback function. The chunk also contains a list of chunk id that it fulfills.

But there aren't any instructions on how to distinguish between a normal chunk and and entry chunk in the webpack configuration.

A: I believe you can use the Commons Chunk Plugin with multiple entry points to specify your chunks.
var webpack = require("webpack");
module.exports = {
  entry: { a: "./a", b: "./b" },
  output: { filename: "[name].js" },
  plugins: [ new webpack.optimize.CommonsChunkPlugin("init.js") ]
}

So init.js is a file with just your runtime (i.e. header.js)

A: You can specify entry that will contain webpack runtime code with CommonsChunkPlugin. For example, with app, vendor and polyfill entries it may look like:
  new webpack.optimize.CommonsChunkPlugin({
    filename: '[name].bundle.js',
    names: [ 'app', 'vendor', 'polyfill', 'webpack' ]
  });

The last name (webpack here) will become an entry containing webpack runtime.


text:
Q: Replace SubString on Partial match of word I have two strings :-
String S1 = "This is my\r\n string."
String S2 = "This is my\n self."

I want to have a generic method to replace any existence of "\n" to "\r\n". But it should not replace any part of the string if it already has "\r\n".

A: Use regular expression with negative lookbehind:
string result = Regex.Replace(input, @"(?<!\r)\n", "\r\n");

It matches all \n which are not preceded by \r.

A: Assuming you have well-behaved standard input text, i.e. no consecutive \r, you can simply use:
var result = S1.replace("\n","\r\n").replace("\r\r","\r")

This won't work in general cases, obviously

A: Try something like this:
var unused = "§";
S2 =
    S2
        .Replace("\r\n", unused)
        .Replace("\n", unused)
        .Replace(unused, "\r\n");


text:
Q: Why am I unable to activate java web in netbeans? I have installed Apache netbeans IDE 13. I can see the option "java web" in  installed plugins. But it is grey colour, but it is not allowing me to activate it. Why is it?

A: When you close (button cancel) the dialog and reopen the project dialog (File > New Project), you should have the following view, and click Next button:


text:
Q: Sorting map containing a key and list of objects I have a map with the structure as Map<String, List<EmployeeIncome>> where the key holds the employee Id and the Employee Income holds the employee details such as empName, empCompany,incomeSrc.The source of income might be multiple (salary , house let out for rent etc).
public class EmployeeIncome{
     private String empName;
     private String empCompany;
     private String incomeSrc;

    public String getEmpName() {
        return empName;
     }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public String getEmpCompany() {
        return empCompany;
    }
    public void setEmpCompany(String empCompany) {
        this.empCompany = empCompany;
    }
    public String getIncomeSrc() {
        return incomeSrc;
    }
    public void setIncomeSrc(String incomeSrc) {
        this.incomeSrc = incomeSrc;
    }

 }

The employee company name will be unique for an employee id will be the same in all case of income source.Now maps contains multiple data of employee, i would like to sort the map based on employee name.Though I am trying to use Comparator and trying out but not able to get the desired output.
Thanks in advance.

A: A sorting map like TreeMap would sort based on its keys, not the values being assigned to them. So, since your keys are employee id strings, you'll get your output sorted by id only.
You should probably rethink your data structure. It's better to map an Employee object as the key. Then you would have access to both, the employee's name as well as his id.
public class Employee implements Comparable<Employee> {

    private long id;
    private String name;

    public long getId() {
        return id;
    }

    public long getName() {
        return name;
    }

    public int compareTo(Employee other) {
      if (name != null) {
        if (other != null) {
          return name.compareTo(other.getName());
        }
        return 1;
      }
      if (other != null && other.getName() != null) {
         return -1;
      }
      return 0;
}

You would also implement Comparable so that the TreeMap sorts your employees by their names.

A: Because you haven't shown what you have done so far, I am simply going to suggest things. You can use a TreeMap<EmployeeName, OtherValue> where EmployeeName is unique as you said? TreeMap is an implementation of NavigableMap (special case of SortedMap where navigational features such as nearest match floor, ceil, etc.) are allowed.
Also, Your keys will be ordered using "Natural ordering". E.g. if your EmployeeName is in String, they will be ordered lexicographical.

A: Your are asking for wrong data structure. Most map implementations have unsorted keys.
Only exception - TreeMap is sorging keys only. In your example key is employee id, not their name.
If you want to have a sorted list by employee names, you would have to extract all employees from your map, put them to a list and use comparator that compares empName.
In short your map will always be sorted by employee id, because it is this map key.


text:
Q: Generate random number to 2 decimal places blah = CInt(Int((7 * Rnd()) + 0))

Generates a random integer between 0 and 6.
How can I modify this to give me a random number with 2 decimal places, still between 0 and 6?
As suggested below, I'm now using this code, and it seems to work:
Dim prng As New Random

Private Function aRand() As Double
    Return Math.Round(prng.Next(0, 601) / 100, 2)
End Function

currentApp.statements(Pick, 7) = aRand()
currentApp.statements(Pick, 8) = aRand()

Thanks for all the suggestions.

A: Like this
Dim prng As New Random

Private Function aRand() As Double
    Return prng.Next(0, 601) / 100
End Function

note that the location of the random.
Your code would look like
    currentApp.statements(Pick, 7) = aRand()
    currentApp.statements(Pick, 8) = aRand()

A: The OP says between 0.00 and 6.00, so I believe that the advice from @HansPassant is the best to try but enlarging the upper limit to 601 ( if he means the limits are inclusive of course)
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, 601)
Dim d = x / 100
Console.WriteLine(d)

A: Based on @Steve's answer, here is a generic implementation:
Function RandomDouble(maxValue As Integer, precision As Integer) As Double
  Static rnd As New Random
  Dim scale As Double = 10 ^ precision
  Dim x As Integer = rnd.Next(0, maxValue * scale + 1)
  Return x / scale
End Function

And the usage (tested in an empty console app, sub main):
Dim dbl As Double = RandomDouble(6, 2)
Debug.WriteLine(dbl)

So you can reuse it like this:
currentApp.statements(Pick, 7) = RandomDouble(6, 2)
currentApp.statements(Pick, 8) = RandomDouble(6, 2)

Or with DRY principle (=don't repeat yourself):
For i As Integer = 7 To 8
  currentApp.statements(Pick, i) = RandomDouble(6, 2)
Next

A: I thought I would throw my hat in the ring on this question because I just expanded on @dbasnett answer to make a nice generic generator.
Note: I used Decimal but Double can be substituted as the output with no seen issues.
''' <summary>
''' Random Decimal generator with variable precision"
''' </summary>
''' <param name="L">Minimum Value</param>
''' <param name="U">Maximum Value</param>
''' <param name="P">Precision</param>
''' <returns>Decimal</returns>
''' <remarks></remarks>
Private Function DRandom(L As Integer, U As Integer, P As Integer) As Decimal
    Dim Rand As New Random
    Dim Upper As String = U.ToString
    Dim Precision As String = "1"
    For I = 0 To P
        If I > 0 Then
            If I = P Then
                Upper = Upper + "1"
            Else
                Upper = Upper + "0"
            End If
            Precision = Precision + "0"
        End If
    Next
    Return Rand.Next(L, Upper.toInteger) / Precision.toInteger
End Function

With my generic toInteger extension:
''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
    Dim S As String = X.ToString
    Try
        If S = String.Empty Then
            Return I
        Else
            Return Integer.Parse(S)
        End If
    Catch
        Dim result As String = String.Empty
        Dim ReturnInt As Integer
        Dim Parsed As Byte
        For Each Character In S.ToCharArray
            If Character = "-" Then
                If S.Substring(0, 1).ToString <> "-" Then
                    result = Character + result
                End If
            End If
            If Character = "." Then
                Exit For
            End If
            If Byte.TryParse(Character, Parsed) Then
                result = result + Parsed.ToString
            End If
        Next
        If result <> String.Empty Then
            If Integer.TryParse(result, ReturnInt) Then
                Return Integer.Parse(ReturnInt)
            Else
                If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
                    Return Integer.MaxValue
                ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
                    Return Integer.MinValue
                Else
                    Return I
                End If
            End If
        Else
            Return I
        End If
    End Try
End Function

This generator takes a variable precision as well as letting you choose in the code what the upper and lower bounds are allowing for (in my opinion) maximum re-usability for a random number generator.
Hope this helps people.


text:
Q: Javascript: create a copy of an array using slice(); I need to create a copy of an array so that I can do modification on one array without affecting the other.
for example:
var a = [[1],[2],[3]];
var b = a.slice(0);
b[1].push(100);
b // [[1],[2, 100],[3]];
a // expect: [[1],[2],[3]]; , actual: [[1],[2, 100],[3]];

I have also tried:
var b = new Array(a);

but this puts all [1],[2],[3] to index 0 in the new array.
What am I missing here?
Thanks guys!

A: you also have to copy the inner arrays:
 var b = a.map(sub => sub.slice());

A: slice() makes a shallow copy, for n levels you could use JSON.parse(JSON.stringify(a)) or recursion:

var a = [[[1]],[2],[3]];

var b = JSON.parse(JSON.stringify(a))

b[0][0][0] = 999;

console.log(a)

console.log(b)


text:
Q: UIDatePicker crash on iOS 14 while setting `textColor` via KVC In my app I use UIDatePicker with custom text color and on iOS 12/13 this code works fine:
timePicker.setValue(UIColor.red, forKeyPath: "textColor")

But on iOS 14 my app crashed.
Stacktrace:
-[_UIDatePickerIOSCompactView _setTextColor:]: unrecognized selector sent to instance 0x7ff09265a8c0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIDatePickerIOSCompactView _setTextColor:]: unrecognized selector sent to instance 0x7ff09265a8c0'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000011b0eea2a __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x000000011aa004ce objc_exception_throw + 48
    2   CoreFoundation                      0x000000011b0fd579 +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0
    3   UIKitCore                           0x00000001235db925 -[UIResponder doesNotRecognizeSelector:] + 292
    4   CoreFoundation                      0x000000011b0f2cf4 ___forwarding___ + 859
    5   CoreFoundation                      0x000000011b0f4f98 _CF_forwarding_prep_0 + 120
    6   Foundation                          0x0000000110c0a6ae -[NSObject(NSKeyValueCoding) setValue:forKey:] + 325
    7   UIKitCore                           0x0000000123af85c5 -[UIView(CALayerDelegate) setValue:forKey:] + 171

Does anyone know how can I use custom text color on iOS 14+?

A: Using KVC is unsafe in swift because if the key is missing, your application will crash.
In order to change the color of the text in UIDatePicker, using the property tintColor.
var picker = UIDatePicker()
picker.tintColor = UIColor.blue

A: This may only available for preferredDatePickerStyle = .wheels
So you can add this below check
     if #available(iOS 13.4, *) {
        <yourPickerview>.preferredDatePickerStyle = .wheels
    } else {
        // Fallback on earlier versions
    }

A: As I replied in the answer Larme linked, textColor is a private property of UIDatePicker. There's no guarantee that it will exist in any version of iOS, so what you are doing is not safe.
KVC lets you try to change properties of an object without any compile-time checking, so if the property gets removed, you crash.


text:
Q: Can't display phplot with foreach $user (height, weight) I want to make a Scatterplot with phplot and laravel so i get all user with height, weight but they just show 2 point/52 user. I don't know why please help me.
  $users = User::all();
    $maxHeight = $users->filter()->max('height');
    $maxWeight = $users->filter()->max('weight');
    $data = array();

    foreach ($users as $user) {
        $data[] = array('', (int)$user->height, (int)$user->weight);
    }

    $plot = new PHPlot(800, 600);
    $plot->SetImageBorderType('plain');

    $plot->SetPlotType('points');
    $plot->SetDataType('data-data');

    # Main plot title:
    $plot->SetTitle('Scatterplot (User plot)');

    $plot->SetXTitle('weight');
    $plot->SetYTitle('height');
    $plot->SetDataValues($data);

    # Need to set area and ticks to get reasonable choices.
    $plot->SetPlotAreaWorld(0, 0, $maxWeight, $maxHeight);
    $plot->SetXTickIncrement(5);
    $plot->SetYTickIncrement(5);

    $plot->SetYTickPos('yaxis');

    # Turn on 4 sided borders, now that axes are inside:
    $plot->SetPlotBorderType('full');

    # Draw both grids:
    $plot->SetDrawXGrid(True);
    $plot->SetDrawYGrid(True);  # Is default

    $plot->SetIsInline(true);
    $plot->SetOutputFile("test.png");

    $plot->DrawGraph();

Then they just show 2 point with 2 user but not all:
Image


text:
Q: sign android apk with existing .keystore I'm using Eclipse, and except for the default keystore path specified in windows->preferences->android->build, I didn't specify any other customized keystore path in eclipse.
I have the debug.keystore in two locations. one is in the default path, and the other say c:\customised_path.
however, when i wanted to generate the cert:

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 20000
  it'll generate the debug.keystore in the java\bin folder.

and if i try:
C:\Java\jdk1.6.0_25\bin>keytool -genkey -v -keystore C:\default_path\.android\d
ebug.keystore
keytool error: java.io.IOException: Invalid keystore format
java.io.IOException: Invalid keystore format
        at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:633)
        at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:3
8)
        at java.security.KeyStore.load(KeyStore.java:1185)
        at sun.security.tools.KeyTool.doCommands(KeyTool.java:620)
        at sun.security.tools.KeyTool.run(KeyTool.java:172)
        at sun.security.tools.KeyTool.main(KeyTool.java:166)

it'll gimme the same error to generate the key in the customized path too.
i have debug.keystore in both folders still i'll have this:
C:\Java\jdk1.6.0_25\bin>keytool -list
keytool error: java.lang.Exception: Keystore file does not exist: C:\customiesed_path\.keystore

and
    C:\Java\jdk1.6.0_25\bin>keytool -list -keystore C:\the_default_path_specified_in_eclipse.keystore
    keytool error: java.lang.Exception: Keystore file does not exist: C:\default_path
Eclipse is using the .keystore in the default folder to sign the apk, and i have the .keystore in the default folder, but it just doesn't allow me to sign it and gives me annoying error when I try to run my application.
Could somebody help here please?

A: Bingo! problem solved! it seems that the .keystore is somehow changed and after I re-download it, it works again.
I re-downloaded the .keystore that I need to use and run eclipse again. Now everything works normal. So next time someone has problems generating apk file using an existing key, please take into consideration "run" in eclipse not from cmd as well as download a new keystore.
One more thing: signing in debug mode is different from release mode! Eclipse uses "run" to sign in debug mode. Using command line won't work because they're simply for release.


text:
Q: Convert Javascript array of objects into one object Let's say I have an array like this
var myarray=[{"id":1234, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1235, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1236, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1237, "listtext":open, "prop3":value3 ,"prop4": value4}];

but I want to convert it to an object like this:
{1234:open,1235:close, 1236: pending,1237:awaiting response}

Can this be done? all the methods I have tried keep getting only the last key value pair.

A: If you are using ES6 or above:
const converted = Object.assign({}, ...myArray.map(object => ({[object.id]: object})))

A: You can simply loop over the array and create a new object

var myarray=[{"id":1234, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1235, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1236, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1237, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'}];
const res = {};
myarray.forEach(obj => {
    res[obj.id] = obj.listtext;
})
console.log(res)

A:

var myarray = [
  { id: 1234, listtext: 'open' },
  { id: 1235, listtext: 'closed' },
  { id: 1236, listtext: 'pending' },
  { id: 1237, listtext: 'open' }
]

var output = myarray.reduce(function (acc, item) {
  acc[item.id] = item.listtext
  return acc
}, {})

console.log(output)

A:

var myarray=[{"id":1234, "listtext":"open", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1235, "listtext":"closed", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1236, "listtext":"pending", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1237, "listtext":"open", "prop3":'value3' ,"prop4": 'value4'}];

var myObjects = [];  // create an empty array to hold the converted objects.

// loop through the array to convert them one by one
myarray.forEach(function(element) {
  var obj = {};    // create an empty object
  obj[element.id] = element.listtext;
  myObjects.push(obj);  // add the object to the array
});

myObjects.forEach(function(object){
   console.log(object);
});


text:
Q: Phalcon Zephir vs APC vs HHVM Performance I started to read about HHVM and Zephir. I was very excited at first, that performance jumps up thanks to this technologies.
But then I started to ask myself a question. If It really gives you such performance like owners of this technologies says.
Now I am going to say, how do I think it looks like. Correct me, if I am wrong.
Php Script Live Process:
Run Script -> Compile -> Execute Script
The obvious problem here, is with compiling. We need to compile our script every time it has been started.
Let's pretend I have Apache2 installed and I am running my php script named "test.php" with:
APC:
APC turned on and APC option to check for changes off.
It should looks like that:
Run Script -> Execute Script
Because it's already compiled to our memory and ready to use.
HHVM:
Hip Hop Virtual Machine, would behave similar to APC. The difference here is, virtual machine, which for standard PHP with APC is Zend Engine.
So it goes like that:
Run Script -> Execute Script
Because it's already compiled (in memory?) and ready to use.
Zephir:
I compiled my script to C extension. So I guess it doesn't need compiling? (I am not sure about this). So the functions inside my php script are native ones now.
So, if I write another script named "test2.php", which will run my native functions which were in "test.php" (Yes it should have .zep format, but it doesn't matter for now).
Now using APC I avoid compiling process.
Run Script -> Execute Script
And now I am confused. As far as you can see it's all the same now. I dont see any kind of advantages of using Zephir and HHVM over standard APC.
So I would like to hear, if I am correct or totally wrong?

A: Zephir can't handle high level objective oriented code. Speed of your application will be worse than clean PHP way.
Here you can find comparsion of clean PHP vs Zephir.
https://github.com/dgafka/zephir-BookStore
So, if you want to rewrite your application to zephir, think twice before you will do it.
https://github.com/phalcon/zephir/issues/694#issuecomment-67987616

A: Zephir is pretty fast (of course, as it is compiled to a C extension)! https://www.simonholywell.com/static/files/2014-02-28/index.html
Hack is pretty fast too, less than Zephir, but on the other hand it's far more mature/active/documented than Zephir.
The main advantage of using Zephir/Hack is that you get static typing as a bonus. It is a real relief to add that kind of security to PHP code.
Dynamic typing has its limits, and permits too much ugly/dangerous things.

A: Use Zephir for abstract functional coding.
For example, a library of functions that do string formats specific to your project. All advance PHP OOP (business logic) and such should be done within PHP.
Simple as that!
Use the tool that matches the project.


text:
Q: Find layers in current map view with Leafletjs I have an app that displays recent jobs on a map  as pinpoints using Leafletjs.
With Leafletjs, when you want to zoom to the user's detected location, you call something like:
map.locate({'setView' : true, 'timeout' : 10000, maxZoom: 10});

However, for some locations, the zoom level 10 does not contain any job points, so I'd like to dynamically set the zoom so that at least on job is visible to the users.
I know that I can listen for the locate function's success and then check  with something like:
map.on('locationfound', function() {
  //for marker in markers{
  //is point within currently visible bounds
  //break on first positive
  //else,
  //zoom up a level, repeat previous checks
  }
}

but that's quite inefficient, especially if I have a large number of points.
Does Leaflet have any built in functions/methods to provide information about layers within the current map view?

A: If you do some things on the server side, you can probably do the calculations fast enough.

*

*Store the locations in pixel coordinates in your database at some way-zoomed-in zoom level (I use zoom level 23).  I call this coordinate system "Vast Coordinate System".  Then, to get the tile coordinates for a point at a specific location is IIRC one bitwise shift -- very fast, and something you can do in SQL.

*Convert your users' location to pixel coords at that way-zoomed in level.

*Iterate on zoom level.  Get the tile coord for the user's location at that zoom level, then do an SQL query which counts the number of points on that tile.  If > 0, stop.

Your SQL will be something like (sorry, I'm being lazy and doing it from memory/thinking instead of actually trying it out)
SELECT count(*) WHERE (vcsX>>(zoom+8)==userX>>(zoom+8)) AND (vcsY>>(zoom+8)==userY>>(zoom+8));

where vcsX and vcsY are the pixel coordinates in Vast Coordinate System.


text:
Q: Send notification to smartphone when a new child is added in Firebase Realtime Database Even if I have the feeling that this question has already been answered, something is missing in my reflexion.
If I want, when a new child is added in my Firebase Realtime Database, to send a notification to some users smartphones (it could be iOS or Android), I have to setup a NodeJS server and install Cloud Messaging to monitor the database and send the order to Notifications in Firebase to send the notifications.
Am I right?
Thanks!


text:
Q: Modeling skewed delay for combinational logic I need help to model a block with different delays for various input-output paths?
input A;
input [3:0] B, C;
output [3:0] Y;

Y = B xor C if A = 1 else Y = 0
with A->Y delay of 10us when posedge A (rise delay) and 5us when negedge A(fall delay)
and B,C - > Y delay is 1us (applicable only if A = 1)
For my case, I might need to use procedural way and assign statements might not suit.

A: Here is something that worked best for me.
`timescale 1us/1ns

module xor_w_enabled(input A, input B, input C, output Y);
wire A_delayed;
wire B_xor_C_delayed;

assign #1 B_xor_C_delayed = B^C;
assign #(10,5) A_delayed = A;

assign Y = (A_delayed == 1) ? B_xor_C_delayed : 0;

endmodule

Please let me know if I'm missing anything.

A: For non-synthesizable models you can use #delay constructs combined with `timescale to model delays. something like the following code
`timescale 1us/1us

module delayModule(A,B,C,Y);
   input A;
   input [3:0] B, C; // this should probably be output
   output [3:0] Y;

   reg [3:0]    tmpb, tmpy;

   always @(posedge A)
       #10us tmpb <= 1;
   always @(negedge A)
       #5us tmpb <= 0;

   always @* begin
     if (A == 1)
       #1us tmpy =(B^C);
   end
   assign B = tmpb;
   assign Y = tmpy;

endmodule // delayModule


text:
Q: Batch file to open Steam shortcuts not working I created a batch file to pick a random file from a folder. This includes steam games as URL shortcuts but the games fail to read Steam and end up crashing because they lack a connection to their DRM.
The code:
@echo off & setlocal
 :: start of main
 :letsago
 rem Set your path here:
 set "workDir=C:\Users\Nader\Desktop\Gaming"
 rem Set the name of the file here:
 set "name=Random.bat"

 set /a "rdm=%random%"

 rem Push to your path.
 pushd "%workDir%"

 rem Count all files in your path. (dir with /b shows only the filenames)
 set /a "counter=0"
 for /f "delims=" %%i in ('dir /b ^|find "."') do call :sub1

 rem This function gives a value from 1 to upper bound of files
 set /a "rdNum=(%rdm%*%counter%/32767)+1"

 rem Start a random file
 set /a "counter=0"
 for /f "delims=" %%i in ('dir /b ^|find "."') do set "fileName=%%i" &call :sub2

 rem Pop back from your path.
 popd "%workDir%"
 echo Closing in 5 seconds...
 ping -n 6 -w 1000 127.0.0.1 > nul
 goto :eof
 :: end of main

 :: start of sub1
 :sub1
 rem For each found file set counter + 1.
 set /a "counter+=1"
 goto :eof
 :: end of sub1

 :: start of sub2
 :sub2
 rem 1st: count again,
 rem 2nd: if counted number equals random number then start the file.
 set /a "counter+=1"
 if %counter%==%rdNum% (start "" "%fileName%" &echo Starting %fileName%)

 goto :eof
 :: end of sub2

A: I've not used BAT in years so I can't really help with a script, but there is an easier way to do this:

*

*Find the Steam Library Folders that you want to randomly launch apps from (include in a list of random folder options?) and scrape the names of all of the files with the extension ".acf" from it. These are Steam's appmanifest files which contain some of the data & settings for installed apps, and have a name format like appmanifest_#.acf where the # is the Steam appid of the app, which is unique for every app and is needed for the next part.

*When a Steam app is selected to be launched (noticeable to the script because of the appmanifest_ part of the file name) extract the appid from the file name (only the number portion, not the appmanifest_ part, and of course not the extension) and then launch Steam with a command-line argument using something like C:\Program Files (x86)\Steam\Steam.exe -applaunch # where # is the appid to launch.
This will start Steam and have it launch the game for you, so there should be no issues with any games not finding the client.

A: This is working in registry and .bat file:
start "" "C:\Program Files (x86)\Steam\Steam.exe" steam://rungameid/322330

A: Just make a desktop shortcut for the steam game then copy the link finally add the link to this code.
start "" "(Your Link)"
It works for me.


text:
Q: Join two tables in hibernate sql query I have Two tables in my system, the table request and table service.
The table service is connected to a request, it has its id.
I like to join two tables in request business class using hibernate, like this sql command:
select * from request r INNER JOIN  service s  ON s.request_id = r.id  WHERE s.is_last_service=1 and s.expiration_date>'2015-12-15';

How can i make this query  string for hibernate?


text:
Q: How to improve the framerate in simple java game loop? I'm working on a java 2d game, using this simple game loop to cap the FPS and UpdatesPS to 60:
public void run() {

        final int MAX_FPS = 60;
        final int MAX_UPS = 60;

        final double fOPTIMAL_TIME = 1000000000 / MAX_FPS;
        final double uOPTIMAL_TIME = 1000000000 / MAX_UPS;

        double uDeltaTime = 0, fDeltaTime = 0;
        int frames = 0, updates = 0;
        long startTime = System.nanoTime();
        long timer = System.currentTimeMillis();

        // GameLOOP starts here
        while (running) {

            long currentTime = System.nanoTime();
            uDeltaTime += (currentTime - startTime);
            fDeltaTime += (currentTime - startTime);
            startTime = currentTime;

            if (uDeltaTime >= uOPTIMAL_TIME) {
                gameUpdate();
                updates++;
                uDeltaTime -= uOPTIMAL_TIME;
            }

            if (fDeltaTime >= fOPTIMAL_TIME) {
                gameRender();
                gameDraw();
                frames++;
                fDeltaTime -= fOPTIMAL_TIME;
            }

            if (System.currentTimeMillis() - timer >= 1000) {

                fps = frames;   //saves the current FPS
                ups = updates;  //saves the current UPS

                updates = 0;
                frames = 0;
                timer += 1000;
            }

        }
    }

The loop works, but I get only 30 FPS for the first ~10 Seconds after starting the game.
After I wait, the FPS raises up to the wanted 60. I don't have a problem to wait a few seconds to let the program stabilize and reach the wanted framerate. But I can't find the reason like a methode who drops the FPS because it's fetching a big file after startup.
Do you have any idea why my engine needs so long to stabilize the framerate?
Thanks for your help!

A: I think this should do the trick:
    public static void run()
    {
        final int desiredFPS = 60;
        final int desiredUPS = 60;

        final long updateThreshold = 1000000000 / desiredUPS;
        final long drawThreshold = 1000000000 / desiredFPS;

        long lastFPS = 0, lastUPS = 0, lastFPSUPSOutput = 0;

        int fps = 0, ups = 0;

        loop:
        while(true)
        {
            if((System.nanoTime() - lastFPSUPSOutput) > 1000000000)
            {
                System.out.println("FPS: " + (double)fps);
                System.out.println("UPS: " + (double)ups);

                fps = 0;
                ups = 0;

                lastFPSUPSOutput = System.nanoTime();
            }

            if((System.nanoTime() - lastUPS) > updateThreshold)
            {
                lastUPS = System.nanoTime();
                updateGame();
                ups++;
            }

            if((System.nanoTime() - lastFPS) > drawThreshold)
            {
                lastFPS = System.nanoTime();
                drawGame();
                fps++;
            }

            // Calculate next frame, or skip if we are running behind
            if(!((System.nanoTime() - lastUPS) > updateThreshold || (System.nanoTime() - lastFPS) > drawThreshold))
            {
                long nextScheduledUP = lastUPS + updateThreshold;
                long nextScheduledDraw = lastFPS + drawThreshold;

                long minScheduled = Math.min(nextScheduledUP, nextScheduledDraw);

                long nanosToWait = minScheduled - System.nanoTime();

                // Just in case
                if(nanosToWait <= 0)
                    continue loop;

                try
                {
                    Thread.sleep(nanosToWait / 1000000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

Edit: I fixed the issue now! The issue was that I was saving the lastFPS/lastUPS after the scene was updated/drawn, and when I set both lastUPS/lastFPS before the scene is drawn/updated, we get the desired fps!Another neat thing about this code is that it doesn't consume a whole cpu core(I measured the difference, your code was consuming 100%, whilest my code only consumed about 10%. If you want to measure it yourself, please note that for some reason, the core on which the code is executed regularly switches(at least this was the case when I measured the code))By the way if you use LWJGL (or have direct access to a windowing library like GLFW) you can activate V-Sync, which would cut your fps down to 60 fps.


text:
Q: why my jQuery is not working when i am uploading on the website When I write the code on console, its working. When I upload on the website it is not working.
I want to do a stripe card details fields validation. When the details are filled and while filling the border color of the box should be green same as card details
Code that I tried:
if (jQuery('.input-text.wc-credit-card-form-card-expiry').val() == '') {
    jQuery('.input-text.wc-credit-card-form-card-expiry').css('border-color', 'red');
}
else {
    jQuery('.input-text.wc-credit-card-form-card-expiry').css('border-color', 'green');
}

Webpage URL:
https://www.preprod.swett.se/checkout-2/
If you check on the website. Card number field is working correct. I want the expiration date and cvv field date should also work same as card details
Could you please help me with this jQuery.

A: Try this and see if it works, please make sure to include jQuery:
jQuery('#stripe-card-expiry').on('keyup', function(){
  var $input = jQuery(this);
  $input.css('border-color', !$input.val() ? 'red' : 'green');

});

A: Card number field is working correct because of this code
    jQuery('#stripe-card-number').on('keyup', function ($) {
    if (jQuery(this).val().length > 0) {
        jQuery('#stripe-card-number').css('border', '2px solid #69bf29');
            }
    });

So, similaraly you need to trigger your code on keyup event for expiration date and cvv
jQuery('.wc-credit-card-form-card-expiry').on('keyup', function ($) {

   if (jQuery('.input-text.wc-credit-card-form-card-expiry').val() == '') {
       jQuery('.input-text.wc-credit-card-form-card-expiry').css('border-color', 'red');
   }
   else {
       jQuery('.input-text.wc-credit-card-form-card-expiry').css('border-color', 'green');
   }

});


text:
Q: Do default commands in Kendo UI's grid trigger events? I have a standard delete command button in a grid.
I would like to subscribe to the event click for some check.
Can I do this? Or do I have to create a custom command?

A: The standard delete command triggers the remove event, so you can bind to that:
grid.bind("remove", function (e) {
    if (e.model.text === "Item 1") {
        console.log("well, I'm doing something else for you");
    }
});

If you want custom behavior (e.g. create some logic to decide whether you want to allow this delete), then you'll probably have to create a custom command (you can style it in the same way if you want).


text:
Q: How to connect to VPN through Proxy Server How do I connect to a VPN going through a proxy?
I am currently at a client and they are using a Proxy to connect the users to the internet. I want to VPN back into my company to retrieve some files.
I tried applications like Proxifier, but for some odd reason when I try and configure the Proxy server on it, it always fails to connect to it, but using the proxy directly through Firefox and IE works...
So, how can I do this, or is it not possible?

A: It's not possible. Proxies (in companies) are basically meant to funnel all outgoing traffic through, for several reasons (policy enforcing, content caching, monitoring, etc.). Mostly, outgoing requests are only allowed via HTTP, HTTPS and maybe FTP, and even that, only on specific ports.
VPN on the other hand uses a tunneled connection, much like SSH (or SFTP, for that matter). These also use a different port than the typical ones you find for HTTP (80) and HTTPS (443).
It won't work for various reasons:

*

*It's very likely that the company network you are in does not allow outgoing connections on any port other than predefined ones (i.e., 80, 443), or anything that is not requested via the proxy server

*Protocols other than HTTP(S) or FTP may be forbidden

*The proxy may just be a simple HTTP proxy, with no means of forwarding any other traffic (which is what a SOCKS proxy could do)

Your only option is to get an exception rule in the company firewall to allow an outgoing connection to your VPN endpoint, using a specific port.

A: I found myself in a very similar situation more than once. If you follow IANA port assignment rules, it is as slhck says: you cannot do it without asking the administrator to allow an outgoing connection to your VPN (e.g. port 1194 UDP is the default for OpenVPN).
However, I managed to solve that problem by breaking the rules and assigning TCP port number 443 (HTTPS) to my VPN server. This worked for me because the network that I connected from did not actually proxy TCP port 443: they simply forwarded TCP:443 packets transparently -- probably to avoid the hassle of configuring an HTTPS proxy. This post here discusses HTTPS proxies, which might prevent this solution from working.
Recently I also learned that OpenVPN supports proxies, as shown in this OpenVPN howto page. I haven't tested that, but it might work.
It all depends on how strict is network security at the place you are... In the end it might just be easier (and more ethical) to just ask your client's IT folks to help you.
Please notice that using TCP for a VPN is not advised, as it introduces an extra layer of TCP overhead, as discussed in this post.

A: Please specify which VPN software you are using.
Most VPNs with own client software (IPSec, PPTP, L2TP) cannot connect through proxy server. If you are using SSL-VPN, you can configure the browser to use the proxy.


text:
Q: Do matrices $\mathbf{A A}^H$ and $\mathbf{A}^H \mathbf{A}$ have the same eigenvalues? Let $\mathbf{A}$ be any complex matrix. Do matrices $\mathbf{A A}^H$ and $\mathbf{A}^H \mathbf{A}$ have the same eigenvalues?
Note: The matrix $\mathbf{A}^H$ is the conjugate transpose of the matrix $\mathbf{A}$.

Here is my trial:
Let $\lambda_1$ be an eigenvalue of the matrix $\mathbf{AA}^H$. Let the vector $\mathbf{x}_1$ be the corresponding eigenvector. Then
$$
\mathbf{A A}^H \mathbf{x}_1 = \lambda_1 \mathbf{x}_1. \tag{1}
$$
Multiplying (1) by matrix $\mathbf{A}^H$ from the left, we have
$$
\mathbf{A}^H (\mathbf{A A}^H \mathbf{x}_1) = \mathbf{A}^H (\lambda_1 \mathbf{x}_1). \tag{2}
$$
Equation (2) can be rewritten as
$$
(\mathbf{A}^H \mathbf{A}) (\mathbf{A}^H \mathbf{x}_1) = \lambda_1 (\mathbf{A}^H \mathbf{x}_1). \tag{3}
$$
Therefore, $\lambda_1$ is also an eigenvalue of the matrix $\mathbf{A}^H \mathbf{A}$. The corresponding eigenvector is $\mathbf{A}^H \mathbf{x}_1$.
Similarly, let $\lambda_2$ be an eigenvalue of the matrix  $\mathbf{A}^H \mathbf{A}$. Let the vector $\mathbf{x}_2$ be the corresponding eigenvector. Then
$$
\mathbf{A}^H \mathbf{A} \mathbf{x}_2 = \lambda_2 \mathbf{x}_2. \tag{4}
$$
Multiplying (4) by the matrix $\mathbf{A}$ from the left, we have
$$
\mathbf{A} (\mathbf{A}^H \mathbf{A} \mathbf{x}_2) = \mathbf{A} (\lambda_2 \mathbf{x}_2). \tag{5}
$$
Equation (5) can be written as
$$
(\mathbf{A} \mathbf{A}^H) (\mathbf{A} \mathbf{x}_2) = \lambda_2 (\mathbf{A} \mathbf{x}_2). \tag{6}
$$
Therefore, $\lambda_2$ is also an eigenvalue of the matrix $\mathbf{A} \mathbf{A}^H$. The corresponding eigenvector is $\mathbf{A} \mathbf{x}_2$.
Thus, we can conclude that matrices $\mathbf{A A}^H$ and $\mathbf{A}^H \mathbf{A}$ have the same eigenvalues.
Am I right?

A: Actually the eigenvalues of such form is explained by singular value decomposition. The square of a singular value of $A$ is just the eigenvalue of $A^HA$ or $AA^H$, which are all positive semi-definite forms.


text:
Q: What is the largest subcategory $C$ of a module category over an Artin algebra, such that $C$ is Krull-Schmidt (and abelian)? Does $C$ exist? Let $A$ be an Artin algebra, $\text{Mod}\,A$ the category of $A$-modules and $\text{mod}\,A$ the category of finitely generated $A$-modules. It is well-known that $\text{mod}\,A$ is a Krull-Schmidt category. Can we find a larger full subcategory $\mathcal{C}$ of $\text{Mod}\,A$, such that it remains a Krull-Schmidt category? Is there a largest $\mathcal{C}$ and if yes, how does $\mathcal{C}$ look like? What happens if we additionally demand $\mathcal{C}$ to be an abelian category?

A: To answer the first question, there is a larger Krull-Schmidt category than $\text{mod}\,A$ unless $A$ has finite representation type.
Every indecomposable pure-injective module has local endomorphism ring, and an Artin algebra of infinite representation type has an infinitely generated indecomposable pure-injective module.
So you could take $\mathcal{C}$ to be the full subcategory of finite direct sums of pure-injective modules.
[The claims above about pure-injective modules can be found, for example, as Theorem 4.3.43 and Theorem 5.3.40 of
Prest, Mike, Purity, spectra and localisation., Encyclopedia of Mathematics and its Applications 121. Cambridge: Cambridge University Press (ISBN 978-0-521-87308-6/hbk). xxviii, 769 p. (2009). ZBL1205.16002.]
I doubt this is often maximal. As Uriya First pointed out in comments, the maximal Krull-Schmidt subcategory of $\text{Mod}\,A$ will consist of all finite direct sums of modules with local endomorphism ring.
I also doubt that it will often (or ever, maybe) be abelian, for the following reason.
If $\mathcal{C}$ is a subcategory of $\text{Mod}\,A$ containing $\text{mod}\,A$ that is abelian, then since $\mathcal{C}$ contains $A$ and $DA$ it follows that exact sequences in $\mathcal{C}$ are exact in $\text{Mod}\,A$, so $\mathcal{C}$ is closed under kernels and cokernels in $\text{Mod}\,A$.
Often this can be used to show that if $\mathcal{C}$ contains an infinitely generated module then it contains an infinite direct sum of simple modules, and so cannot be Krull-Schmidt. I don't know if this is always the case, but here's one illustrative case:
Suppose $A$ is local, and $\mathcal{C}$ is an abelian subcategory of $\text{Mod}\,A$ that contains an infinitely generated module $X$. Then if $\operatorname{rad}^iX$ is the last nonzero power of the radical, there is a map $X\to X$ whose cokernel is $X/\operatorname{rad}^iX$. By induction, $\mathcal{C}$ contains $X/\operatorname{rad}X$, which is an infinite direct sum of simple modules.


text:
Q: FCM onMessageReceived not calling Android I am facing one problem while implementing FCM in Android application.
Everything works fine, my service onMessageReceived() is not calling. But I am getting following logs when I send a message from my Java Server.
    08-25 12:14:53.216 20482-20482/com.cognisun.sas D/ActivityThread: BDC-Calling onReceive: intent=Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000010 pkg=com.cognisun.sas cmp=com.cognisun.sas/com.google.firebase.iid.FirebaseInstanceIdReceiver (has extras) }, receiver=com.google.firebase.iid.FirebaseInstanceIdReceiver@ac9047a
08-25 12:14:53.222 20482-20482/com.cognisun.sas D/ActivityThread: BDC-Calling onReceive end receiver=class com.google.firebase.iid.FirebaseInstanceIdReceiver
08-25 12:14:53.223 20482-20482/com.cognisun.sas D/ActivityThread: BDC-RECEIVER handled : 0 / ReceiverData{intent=Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000010 pkg=com.cognisun.sas (has extras) } packageName=com.cognisun.sas resultCode=-1 resultData=null resultExtras=null}
08-25 12:14:53.223 20482-20482/com.cognisun.sas D/ActivityThread: SVC-Creating service: CreateServiceData{token=android.os.BinderProxy@750442b className=com.cognisun.sas.services.firebase.MyFirebaseMessagingService packageName=com.cognisun.sas intent=null}
08-25 12:14:53.223 20482-20482/com.cognisun.sas D/ActivityThread: SVC-CREATE_SERVICE handled : 0 / CreateServiceData{token=android.os.BinderProxy@750442b className=com.cognisun.sas.services.firebase.MyFirebaseMessagingService packageName=com.cognisun.sas intent=null}
08-25 12:14:53.224 20482-20482/com.cognisun.sas D/ActivityThread: SVC-Calling onStartCommand: com.cognisun.sas.services.firebase.MyFirebaseMessagingService@6345088, flags=0, startId=1
08-25 12:14:53.225 20482-20482/com.cognisun.sas D/ActivityThread: SVC-SERVICE_ARGS handled : 0 / ServiceArgsData{token=android.os.BinderProxy@750442b startId=1 args=Intent { act=com.google.firebase.MESSAGING_EVENT pkg=com.cognisun.sas cmp=com.cognisun.sas/.services.firebase.MyFirebaseMessagingService (has extras) }}
08-25 12:14:53.227 20482-21308/com.cognisun.sas D/SettingsInterface:  from settings cache , name = cover_app_component , value = disable
08-25 12:14:53.227 20482-21308/com.cognisun.sas D/SettingsInterface:  from settings cache , name = cover_app_lock , value = 0
08-25 12:14:53.232 20482-20482/com.cognisun.sas D/ActivityThread: SVC-Destroying service: com.cognisun.sas.services.firebase.MyFirebaseMessagingService@6345088
08-25 12:14:53.233 20482-20482/com.cognisun.sas D/ActivityThread: SVC-STOP_SERVICE handled : 0 / android.os.BinderProxy@750442b

Any suggestions ????
This is my service class,
class MyFirebaseMessagingService : FirebaseMessagingService() {
    internal var TAG = "FCM Message"
    override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        Log.e(TAG, "From: " + remoteMessage!!.getFrom())

        // Check if message contains a data payload.
        if (remoteMessage.getData().size > 0) {
            Log.e(TAG, "Message data payload: " + remoteMessage.getData())
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()!!)
        }
    }
}

AndroidManifest.xml file,
<service android:name=".fcm.MyFirebaseInstanceIDService"
        android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

<service android:name=".fcm.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

I am getting the Notifications while the app is in the background. Problem occurs if application comes in foreground

A: First, follow instructions from this guide, they are very clear and easy, or you can clone sample code from here and see for yourself what is wrong.
Secondly have you read these comments regarding onMessageReceived()
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]

Look for following comment in this class
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.

For more see: https://firebase.google.com/docs/cloud-messaging/concept-options

A: Firebase will not call your onMessageReceived() when your app is in the background or killed, and you can't customise your notification. It will show notifications managed by Firebase it self.
to make Firebase library to call your onMessageReceived() in every case

a) Foreground
b) Background
c) Killed

Do not put JSON key "notification" in your request to Firebase API, use "data" instead, see below.
For example, following message will not call onMessageReceived()
{
  "to": "/topics/test",
  "notification": {
    "title" : "title",
    "message": "data!"
   }
}

but this will work
{
  "to": "/topics/test",
   "data": {
       "title":"title",
       "message":"data!"
   }
}

see this it has a detailed description of firebase message type For example:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        sendNotification(remoteMessage.getData().get("message").toString(),
             remoteMessage.getData().get("title").toString());
    }
}

private void sendNotification(String message, String title) {
    int requestID = (int) System.currentTimeMillis();
    Intent intent = new Intent(this, activityCompat);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.small_logo)
            .setContentTitle(title)
            .setContentText(message).setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(messageBody))
            .setTicker(messageBody);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
    Notification notification = notificationBuilder.build();

    notificationManager.notify(requestID, notification);
}


text:
Q: MVC Object Reference not set to an instance of an object on launch I used to do standard MVC3/EF4, and took a few years out... and it seems so much has changed.
I created a new app using MVC5 - it started fast and works, I then added my EF models and I got a warning that the schema had changed and I need to use Migrations (looks exciting!).... I am a little confused as I hadn't launched a controller so I don't understand when/how it built the EF model.
Anyway, I figured out that the new MVC5 authentication uses EF out the box, and I figured it was related to that (so much to learn now!) - as I only had one test user, I thought I would just drop the database and allow the application to rebuild everything.
So, I deleted it and relaunched...
In my main Chrome session, I had the logged in cookie, and it is now coming up with a "Object reference not set to an instance of an object."
The moment I clear my cookies or use incognito, it clears it - and I can create users again/the models get created as expected.
My debugger isn't firing and I can't figure out what is actually breaking here...
Can anyone shed any light on this?


text:
Q: What is a 'prayer mission'? It's actually a religious or cultural question but still I don't know what it is so I decided to post it here. I searched it online including on Wikipedia but I couldn't find a straight answer to it probably because I'm not really familiar with Christianity. In Family Guy, the grandpa as the answer to the question, "where's grandma?" says, "she's on her prayer mission in Las Vegas."
Is it something all people can do? And what do they do exactly on this mission?
Thanks

A: Typically, a "mission" in the Christian faith is a trip one takes to help others and/or spread the gospel. An example would be a group of Christians from a church going to Haiti to help build or repair a school or orphanage.
The quote from Family Guy was making a joke about Grandma going to Las Vegas on a mission, not to help someone else, but to gamble. She's specifically on a "prayer mission" to pray she wins.


text:
Q: Handling complex and large dependencies Problem
I've been developing a game in C++ in my spare time and I've opted to use Bazel as my build tool since I have never had a ton of luck (or fun) working with make or cmake. I also have dependencies in other languages (python for some of the high level scripting). I'm using glfw for basic window handling and high level graphics support and that works well enough but now comes the problem. I'm uncertain on how I should handle dependencies like glfw in a Bazel world.
For some of my dependencies (like gtest and fruit) I can just reference them in my WORKSPACE file and Bazel handles them automagically but glfw hasn't adopted Bazel. So all of this leads me to ask, what should I do about dependencies that don't use Bazel inside a Bazel project?
Current approach
For many of the simpler dependencies I have, I simply created a new_git_repository entry in my WORKSPACE file and created a BUILD file for the library. This works great until you get to really complicated libraries like glfw that have a number of dependencies on their own.
When building glfw for a Linux machine running X11 you now have a dependency on X11 which would mean adding X11 to my Bazel setup. X11 Comes with its own set of dependencies (the X11 libraries like X11Cursor) and so on.
glfw also tries to provide basic joystick support which is provided by default in Linux which is great! Except that this is provided by the kernel which means that the kernel is also a dependency of my project. Now I shouldn't need anything more than the kernel headers this still seems like a lot to bring in.
Alternative Options
The reason I took the approach I've taken so far is to make the dependencies required to spin up a machine that can successfully build my game very minimal. In theory they just need a C/C++ compiler, Java 8, and Bazel and they're off to the races. This is great since it also means I can create a Docker container that has Bazel installed and do CI/CD really easily.
I could sacrifice this ease and just say that you need to have libraries like glfw installed before attempting to compile the game but that brings the whole which version is installed and how is it all configured problem back up that Bazel is supposed to help solve.
Surely there is a simpler solution and I'm overthinking this?

A: If the glfw project has no BUILD files, then you have the following options:

*

*Build glfw inside a genrule.
If glfw supports some other build system like make, you could create a genrule that runs the tool. This approach has obvious drawbacks, like the not-to-be-underestimated impracticality of having to declare all inputs of that genrule, but it'd be the simplest way of Bazel'izing glfw.

*Pre-build glfw.o and check it into your source tree.
You can create a cc_library rule for it, and put the .o file in the srcs. Even though this solution is the least flexible of all because you not only restrict the target platform to whatever the .o was built for, but also make it harder to reproduce the whole build, the benefits are sometimes worth the costs.
I view this approach as a last resort. Even in Bazel's own source code there's one cc_library.srcs that includes a raw object file, because it was worth it, as the commit message of 92caf38 explains.

*Require that glfw be installed.
You already considered this option. Some people may prefer this to the other approaches.


text:
Q: Linux setfacl options (-b,-x) differences What is the exact difference between  -b and -x option in the Setfacl command? are they the same? if not what is the difference?

A: The -x option is short for --remove and it removes the specified ACL entries. For example:
setfacl -x u:httpd /home/Fred

The -b option is short for --remove-all which removes all ACL entries (leaving just the base "owner/group/other" which are non-removable).
setfacl -b /home/Fred


text:
Q: Making a progressbar with "dialog" from rsync output I'm looking for a way to filter/redirect rsync output in a manner where it can be fed to the "dialog --gauge" command, so I can get a nice looking progressbar during file sync.
Currently I have only tested it directly at the prompt, but I'm planning to do this in a (bash) shell script.
I have looked around the internet and found bits and pieces, but I'm still missing something to make it work
(Disclaimer: This might be a totally wrong approach, and is a redirect/piping monstrosity)
What I have currently put together:
rsync -avz --progress -e "ssh" user@server:/home/user/data/ /home/user/data | awk -f /home/user/rsync.awk | sed 's/\([0-9]*\).*/\1/' | dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

First I have the actual rsync command with the --progress option
Output from rsync is piped into awk and uses the followng awk filter:
{
   if (index($0, "to-check=") > 0)
   {
        split($0, pieces, "to-check=")
        split(pieces[2], term, ")");
        split(term[1], division, "/");
        print (1-(division[1]/division[2]))*100
}
#   else
#   {
#       print "#"$0;
#   }
   fflush();
}

This filters out rsync output and provides the percentage in the following format:
53.7037
55.5556
57.4074
59.2593
61.1111
62.963

So to get rid of the decimal numbers, I feed the output to sed:
sed 's/\([0-9]*\).*/\1/'

Which gives the following output:
64
66
68
70
72
74
75
77

Those numbers are piped into dialog like this:
dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

As far as I know, "dialog --gauge" etc. should accept this, but it just displays progress to be 0% until it suddenly reaches 100%
Can someone point me in the right direction here?
Am I far away from a working progressbar?
Is there a better way to achieve this?
Regards,
Christer
EDIT: After taking @lynxlynxlynx' answer into account, the correct command line is:
rsync -avz --progress -e "ssh" user@server:/home/user/data/ /home/user/data \
 | awk -f /home/user/rsync.awk \
 | sed --unbuffered 's/([0-9]*).*/\1/' \
 | dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

A: for i in 10 20 30; do echo $i; sleep 1; done | dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

works fine, so @Shadur is right and there is buffering at play.
Adding the sed stripper into the mix shows it is the culprit (only shows 0 and 30):
for i in 10 20 30; do echo $i; sleep 1; done | sed 's/\([0-9]*\).*/\1/' | dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

Now that the problem is known, you have multiple options. The cleanest would be to round/cut the percentage in awk with either math or string manipulation, but since you have GNU sed, just adding -u or --unbuffered should do the trick.
However for completeness' sake, a simple test case shows awk also does buffering:
for i in 10 20 30; do echo $i; sleep 1; done | awk '{print $0}' | sed -u 's/\([0-9]*\).*/\1/' | dialog --title "My Gauge" --gauge "Hi, this is a gauge widget" 20 70

But you already handle that with fflush, so I don't expect problems.


text:
Q: Rails initializers folder I'm having a little trouble understanding how the files inside the intializers folder is used. Are all the files within this directory loaded automatically? Or do we need to specify which ones in some location?
The above question came into play because I wanted to setup action mailer. I created a file called smtp_gmail.rb inside this folder an defined ActionMailer::Base.smtp_settings = { ... }. Is this sufficient to let action mailer know to use these settings?
My guess is that all files in the initializers folders are loaded, and if a configuration for something specific was set, then it will be used.

A: Yes, files in config/initializers are loaded automatically.
Here's a detailed article on the subject. See section 2.7.27.


text:
Q: Markov processes: Hitting times for a point form an i.i.d. sequence Say that I have a recurrent time-homogenous diffusion process X (continuous strong markov process) and two points $x,y$. If $X_t$ goes from $y$, to $x$ and then back to $y$ again we denote it as a "bump".
Define the stopping times iteratively:
$t_1$ First time a bump finishes
$t_2$ The time it takes from the first bump finished till the 2nd bump finishes
and so on...
(So $t_1+...+t_n$ is the total time for the n'th bump to finish ). Is it true that they form an i.i.d sequence? It seems obvious to me, and proving independence is trivial since $X_{t_n}=y$ is constant , but somehow the stationarity keeps eluding me.

A: Yes the variables $t_i$ are independent and identically distributed.  The independence follows directly from the Strong Markov property. That gives that $t_i$ is independent of $t_j$ for all $j < i$.  The Strong Markov property and time-homogeneity together imply that
$$P[X_{s + t_i} \in A | t_i] = E[X_s \in A| X_0 = y]$$
for all $s \geq 0$.
That yields that the $t_i$ are identically distributed.


text:
Q: jQuery.proxy() usage I was reading the api about jQuery.proxy(). It looks promising but I was wondering in what situation is this best use. Can anyone enlighten me?

A: It's just a shorthand method of setting the context for a closure, for example:
$(".myClass").click(function() {
  setTimeout(function() {
    alert(this); //window
  }, 1000);
});

However often we want this to remain the same as the method we were in, which $.proxy() is used for, like this:
$("button").click(function() {
  setTimeout($.proxy(function() {
    alert(this); //button
  }, this), 1000);
});

It's usually used for delayed calls, or anywhere you don't want to do a longhand method of declaring a closure.  The string method of pointing the context to an object...well I haven't come across a practical use in every day code yet, but I'm sure there are applications, just depends what your object/event structure is.

A: When you want a function that has the this value bound to a specific object. For example, in callbacks such as event handlers, AJAX callbacks, timeouts, intervals, custom objects, etc.
This is just a manufactured example of a situation where it might be useful. Assuming there is a Person object which has a property name. It is also linked to a text input element, and whenever the input value changes, the name in this person object gets updated too.
function Person(el) {
    this.name = '';

    $(el).change(function(event) {
        // Want to update this.name of the Person object,
        // but can't because this here refers to the element
        // that triggered the change event.
    });
}

One solution that we often use is to store the this context in a variable and use that inside the callback function such as:
function Person(el) {
    this.name = '';

    var self = this; // store reference to this

    $(el).change(function(event) {
        self.name = this.value; // captures self in a closure
    });
}

Alternatively, we could have used jQuery.proxy here so the reference to this refers to the object of Person instead of the element that triggered the event.
function Person(el) {
    this.name = '';

    $(el).change(jQuery.proxy(function(event) {
        this.name = event.target.value;
    }, this));
}

Note that this feature has been standardized into ECMAScript 5 which now includes the bind method borrowed from prototypejs and is already available on some browsers.
function Person(el) {
    this.name = '';

    $(el).change(function(event) {
        this.name = event.target.value;
    }.bind(this)); // we're binding the function to the object of person
}

A: For example if you want to create callbacks. Instead of:
var that = this;

$('button').click(function() {
    that.someMethod();
});

you can do:
$('button').click($.proxy(this.someMethod, this));

Or if you create a plugin that accepts callbacks and you have to set a specific context for the callback.


text:
Q: Make PHP send an email with an inline image attachment WITHOUT using PHPMailer, Swiftmailer, PEAR, Zend_mail, or any other libraries at all, I want to send an email with an image attachment inline.
The important part here is attaching it inline: I already am able to do everything else.
Inline meaning that it is able to be used by the HTML in the email in an image tag.
I really don't want to use PHPMailer or anything like that--I am not the only one who has tried to figure out how to do this on stackoverflow, and so far all the questions I've seen get nothing but arguments about why they should be using PEAR or Zend_mail or something. I don't want to do that, and I don't want to argue about it.

A: is this what you are looking for??
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!

This is something with HTML formatting.

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

A: I don't know if this is what you want, but is easy to send an email with mail() function in PHP, in HTML format:
http://php.net/manual/en/function.mail.php
In the examples, there's one with HTML


text: Q: Python txt Notepad file cannot be saved as a ipynb and cannot be run on Visual Studio I have a Python code correction received in text form. I am unable to save the file as ipynb. Please note my background is finance and I am not experienced with coding so the solution might be very easy.


text:
Q: Kunena forum shortcut not displayed correctly in joomla horizontal menu I try to add a kunena (a popular joomla forum extension) shortcut in joomla horizontal menu (protostar template/position-1).
Kunena automatically created a menu entry during installation.

Kunena top url is <host>/index.php/forum. And this url seems fishy to me already (the index.php part).
I have 2 items in main menu (the horizontal menu) : "accueil" (home in french) and "forum".

When I select "accueil", the menu item is highlighted.

But when I select "forum", the menu item is not hightlighted

My questions:

*

*What did I do wrong to have my menu item not highlighted? (if I add a random internal link in horizontal menu, <host>/index.php/2014-07-24-14-11-04 for example, it is highlighted correctly)

*Is it a normal behavior to  get an "index.php" in the middle of the url?

A: The highlight issue seem to be more css problem and not joomla.
If you move the kunena button from the subcategory to the top menu does it get highlighted?
As for index.php you have to rename htaccess.txt to .htaccess to your ftp directory and enable sef url from joomla global configuration:

System -> Global configuration -> Search Engine Friendly URLs
System -> Global configuration -> Use URL rewriting


text:
Q: SCSS / SASS - Dynamic generation of CSS classes I just came upon a situation where I wanted to automatically generate a series of css classes with help of a mixin. So I was wondering if there is a way to make this dynamically.
Basically I have classes like
.tile-1, .tile-2, .tile-3, .tile-4 ...

Where tile-2 is double the height of tile-1, tile-3 three times the height of tile-1, and so on
I also created a very simple mixin to be able to set the base-height in a scss variable and calculate it from there:
@mixin tile-height($size) {
    height: $size * $tile-height;
}

Where $tile-height is being loaded from another scss file.
Is there a way to generate my tile-x classes dynamically in the stylesheet, using the number from the classname as a mixin parameter?

A: Is this what you are looking @for?
$tile-height: 20;

@mixin tile-height($size) {
  height: $size * $tile-height + px;
}

@for $i from 1 through 5 {
  .tile-#{$i} { @include tile-height($i); }
}


text:
Q: When to use fragment backstack vs. individual activities? I've been developing for Android for a couple of years now, and I still find myself going back and forth on this issue: when should I be using fragments on a backstack versus putting each fragment into its own activity?
In the Android Fragment documentation, they show this diagram:

I understand the tablet use case perfectly, but for the Handset use case, I don't get why you would put each fragment into its own activity. I typically create one activity and add the fragments to the backstack (via FragmentManager). Is either one of these approaches considered the 'right' way to do it? If both are okay, what is a good rule of thumb to use for picking which approach to use?
This question is closely related, but I'm not totally satisfied with it. If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?

A: I doubt there is a right way to do it. There are likely some ways that are better than others in some circumstances, but for the most part, the answer will be "it depends."
I have noticed in the latest version (22.x) of the SDK with Eclipse that every Activity that is generated is nothing more than a placeholder for a Fragment. The Fragment is auto generated and contains the view logic. It seems like they want to make Activities nothing more than a placeholder/controller for Fragments. I don't think I agree with that.  While I definitely see the use case for Tablets, I feel like this pattern should be used more on an as needed basis than as a general rule. This is just my opinion, but I think moving ALL of the logic into the Fragment sacrifices some of the benefits you get from using an Activity, so it is only a useful pattern if you need to re-use that fragment specifically.

If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?

Good question. I personally prefer to use many Activities and only use Fragments where I need to re-use the logic/views in multiple places. I think the flow of using startActivity and startActivityForResult and allowing the system to manage your activity stack is just a little easier than trying to manage a huge Fragment back stack and one Activity (again, just my opinion).
So when would I ever use the Fragment back stack? There was actually a very good situation for me to use it recently.  I had an Activity that needed to build a very complex object.  The Object needed many fields input to the user, so I created a Workflow that walked the user through this process one step at a time.  I created a single Activity to handle the creation of this logic. Each step of the UI was a Fragment that took input from the user, reported back to the Activity, then the Activity loaded the next Fragment. The Fragments were added to the back stack so the user could go back to previous steps in the workflow.
Object1CreationActivity
FragmentA --> FragmentB --> FragmentC --> FragmentD

Communication between the Fragments and the Activity should be done with interfaces. This is important if we want to re-use these anywhere else. Because of this, I could re-use much of this code to create another Object.
Object2CreationActivity
FragmentB --> FragmentD --> FragmentE

To summarize, Fragments, Activities, the back stack, these are all powerful tools you can use to make Android applications. There may not be a great rule of thumb for when and how to use them, but as long as you are well versed in how they work together, you can use them as appropriate for your application.

A: fragments are light weight alternatives to activities....that is one way to look at it. e.g. i have my our app which has about 10-13 screens. Either

*

*I create a new activity for each one of them. OR

*I create only a few activities that are logically distinct in functional aspects ad swap view screens in them OR

*I create 1 activity and delegate actual screen functional to fragments.

I find the third way much better and manageable. Its kinda saying that fragments allow reuse of view using the framelayout options. Further more you can devise an easy way to share data between fragments as against the heavy weight way of using a Parceable to share stuff between activities.
Also Android API folks are going to focus more on fragment based designs instead of activities so its better to stick with standards. Using fragments i a just a tad more complicated than using activities but is well worth the effort to learn them. Helps create scalable and quiet reusable screen views IMHO.


text:
Q: Beamer presentation with Pandoc and Markdown - Headers don't work properly I'm trying to show how different headers are shown in markdown. This is part of the pres.md:
# Headers

# H1
## H2
### H3
#### H4
##### H5
###### H6

And I compile it using this command:
pandoc pres.md -t beamer -o pres.pdf

But the result is this:

There are two problems here.
1- # H1 is considered as the page header.
2- All other headers are the same size.
I understand why the first problem happens, because Pandoc treats h1 headers as the header of the page. And I can change that by changing the implicit --slide-level=1 of Pandoc command. But changing that option to any other value (between 1 and 6) will result in Pandoc treating that header as the the page header, which is not what I'm trying to do. I'm trying to have all the headers appear as they would on, for example, GitHub, while having # H1 headers taken as page header (--slide-level=1) for the rest of the presentation.
The desired output is something like this, for a single slide of the presentation:

How can I do that?


text:
Q: How to optimize transactions costs from testing existence of keys? I'm designing an application using Azure Storage Blobs/Table/Queue, handling massive amount of data.
One important aspect of the application, is that work will be done if a given key don't exist, and determining the existence of a key is a frequent and intensive task.
I need to optimize as much possible billable transactions from existence checks of keys.
It could be either against blobs or tables.
I looked at this document Understanding Windows Azure Storage Billing – Bandwidth, Transactions, and Capacity It seems that 404 errors are not counted only from anonymous requests.
I was also thinking of using a BatchTableOperation to check 100 keys at once, maybe using a Replace or Merge, and determine in the results if the key indeed existed (haven't tried, actualy I got the idea while writing)
Any good hack are welcomed.

A: You should use Windows Azure Caching:

*

*Load all existing keys in the cache

*Each time you add a record to Table Storage, also add it to cache

Once you've done that, have your application check cache first. If the item is not present there, check Table Storage just to be sure (to cover edge cases). But 99% of the time, if the item has already been processed the key will be available in the cache and you won't need to query Table Storage (this will drastically reduce transactions to Table Storage).
If using Windows Azure Caching is not an option there are alternatives, like using MemoryCache, save all keys in a file, ...


text:
Q: can't compile code using struct tms #if defined(HAVE_TIMES)
#include <unistd.h>
static double cycles_diff(struct tms *a,struct tms *b)
{

      clock_t aa = a->tms_utime  +
                   a->tms_stime  +
                   a->tms_cutime +
                   a->tms_cstime;

      clock_t bb = b->tmstms_utime
            +      b->tms_stime
            +      b->tms_cutime
            +      b->tms_cstime;

      return (aa-bb)/(double)sysconf(_SC_CLK_TCK);
  }
}

This gives errors

incomplete type declaration of struc tms

and

sysconf was not declared

A: According to the manual you need to #include <sys/times.h>