text:
Q: Long and Double comparison (==) behaves differently When executing the following code snippet it behaves differently for Double.
Long v1 = 1L;
Long v2 = 1L;
Double d1 = 1.0;
Double d2 = 1.0;

System.out.println(v1 == v2); // Prints true
System.out.println(d1 == d2); // Prints false

System.out.println(v1.equals(v2)); // Prints true
System.out.println(d1.equals(d2)); // Prints true

Why Double == behaves differently from Long?

A: Long v1 = 1L;
Long v2 = 1L;
Double d1 = 1.0;
Double d2 = 1.0;

You are creating two references to objects here, and instantiating two objects with autoboxing behaviour of Java.
Java re-uses the same Long object instance from a pool for v1 and v2, The Doubles do not use a pool for remembering values, as can be read in this informative blog entry https://gerardnico.com/code/type/autoboxing

Here are some rules as with Java 5 :
autoboxing to Boolean and Byte always returns an object from the pool
  autoboxing to Char, Short, Integer and Long returns an object from the
  pool when the autoboxed value is between -128 and 127 (inclusive)
autoboxing of Float and Double does not use the pool and always
  returns a new object

Your code becomes then with autoboxing(some pool is a visualisation of the pool java uses to cache certain values):
class SomePoolJavaUses {
   static Long _l1 = new Long(1L);
   static Long _l2 = new Long(2L);
   static Long _l3 = new Long(3L);
   ...
}

Long v1 = SomePoolJavaUses._l1;
Long v2 = SomePoolJavaUses._l1;
Double d1 = new Double(1.0);
Double d2 = new Double(1.0);

This means that d1 and d2 are not equal instances, so they are not equal in ==
This means that v1 and v2 are equal instance, so they are equal in ==
the v1.equals returns true, because there is being looked at the actual value there instead of a quick check if the memory addresses are the same.


text:
Q: configer hot letters in Eclipse plugin menu (& does not work) As Eclipse plugin developer, how to specify what letter in menu item would be hot.
For example, when user open File -> New (e.g. with Alt+Shift+N),
then
make n to select _N_ode.js project
make p to select _P_hantomJS project
etc
I think I just need to add special simbol before the letter
into name="Node.js Express Project"
but & does not work.

(source: nodeclipse.org)

A: You can use the mnemonic attribute of the command and menu elements in the org.eclipse.ui.menus extension point:
<extension
     point="org.eclipse.ui.menus">
  <menuContribution
        locationURI="popup:org.eclipse.ui.ide.MarkersView">
      <command
            commandId="org.eclipse.ui.navigate.goToResource"
            mnemonic="X"
            style="push">
      </command>
  </menuContribution>

  <menuContribution
        locationURI="popup:org.eclipse.ui.ide.MarkersView">

     <menu
           commandId="org.eclipse.ui.navigate.showInQuickMenu"
           id="org.eclipse.ui.ide.markers.showInMenu"
           label="Show In"
           mnemonic="Y">

A: Just add & as &
        name="&Node.js Project"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add fontColor, fontBackgroundColor, fontSize to ckeditor5 in React import React, { Component } from "react";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import BalloonEditor from "@ckeditor/ckeditor5-build-balloon";

class MyEditor extends Component {
  render() {
    return (

HEllo world

        <CKEditor
          config={{
            toolbar: {
              items: [
                  'heading', '|',
                  'alignment', '|',
                   'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|',
                  'link', '|',
                  'bulletedList', 'numberedList', 'todoList',
                  '-', // break point
                  'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', '|',
                  'code', 'codeBlock', '|',
                  'insertTable', '|',
                  'outdent', 'indent', '|',
                  'uploadImage', 'blockQuote', '|',
                  'undo', 'redo'
              ],
              shouldNotGroupWhenFull: true
          }
          }}
          editor={BalloonEditor}
          data="
Hello from CKEditor 5!
"
          onChange={ ( event, editor ) => {
            const data = editor.getData();
            console.log( { event, editor, data } );
        } }
        />

    );
  }
}

export default MyEditor;

Nothing complex in the above code I am trying to get familiar with ckeditor5.
My question here is all the options in the items array above is visible in toolbar except
'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor'

I know I am missing something here. I searched for the solution in the ckeditor5 docs but couldn't find the solution specially for React.
I appreciate your help so much. Thanks is advance.

A: Seem @ckeditor/ckeditor5-build-balloon not support Font plugin.
You have to Customize one of the existing builds
import Font from '@ckeditor/ckeditor5-font/src/font';
...

class MyEditor extends Component {
  render() {
    return (

HEllo world

        <CKEditor
          config={{
            plugins: [ Font, ... ],
            toolbar: [ 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', ... ]
            ...
          }}
          // rest props
        } }
        />

    );
  }
}

export default MyEditor;

or Create your own by using CKEditor online builder


text:
Q: Is YOLO a good algorithm for defect detection on images? I wish to train an algorithm to detect defects on images of labels. These may be such things as scratches, tears and voids.
I would like to try to train a YOLO algorithm to do this, but it is very computationally intensive and requires all training images to have the bounding boxes identified.
Has YOLO been used successfully to detect defects?


text:
Q: JavaCC: customizing lexer error messages According to the JavaCC documentation, if I want to customize the messages given by errors in the lexer:

To customize error reporting by the lexer, the lexer class must be subclassed and this method [LexicalError() in TokenMgrError] redefined in the subclass. To help with creating your error reporting scheme, the following variables are available:

However, I see nothing about how to get the generated code to use that subclass, unlike with the TOKEN_FACTORY option.
On the other hand, looking in the TokenMgrError source, some comments indicate that the source file should be directly edited, rather than subclassed.  However, if I do that, the next time I change the .jj file and have Ant regenerate the parser and lexer code, I get this warning:

Warning: TokenMgrError.java: File is obsolete.  Please rename or delete this file so that a new one can be generated for you.

So, how am I supposed to be doing this?

A: You can modify TokenMgrError if you want. There isn't a lot of downside to it.
If you subclass the token manager, then you can subclass TokenMgrError too. You just need to be sure to override all the routines that create TokenMgrError.  To get the parser to use your subclass, you just create the parser like this
MyParser parser = new MyParser( new MySubclassTokenManagr(...) ) ;


text:
Q: How to delete two groups of characters with regex? I have this type of string:
First part: [[archive 726|The Archive]] is a great start
And I want to print:
First part: The Archive is a great start
Here is what I've come to far:
input.gsub!(/\[\[(.*?)\|/,"")
print input
> "First part: The Archive]] is a great start"

How can I also match the ]]?

A: You may use
input.gsub!(/\[\[[^\]\[]*\|(.*?)\]\]/, '\1')

See the Rubular demo and a Ruby demo.
Details

*

*\[\[  - a [[ substring

*[^\]\[]* - any 0 or more chars other than [ and ], as many as possible (if there are multiple | chars inside [[...]], replace * with *? to match as few as possible)

*\| - a | char

*(.*?) - Group 1 (the group value is referred to with \1 from the replacement pattern, mind the single quotes around \1): any 0 or more chars other than line break chars, as few as possible

*\]\] - a ]] substring.


text:
Q: Sinch detect SINCall crash Is there a way to detect when the user on the other end of a SINCall crashes? There seems to be no change in state on SINCall.details.endState or SINCall.state.
I'm currently using a hack to listen for a specific message in
client(client: SINClient!, logMessage message: String!, area: String!, severity: SINLogSeverity, timestamp: NSDate!)
to accomplish this.

A: You are right, currently there is no callback triggered when the SINCall crashes on the other end.


text:
Q: How to get selected value from dropdown item in blazor I have write a below code to show dropdown menu using bootstrap class.I would like to know how to get selected value from dropdown item using blazor.

                    English

                    Tamil

A: The Dropdown as you've shown it is not a "Select" type control.  It's just a list of links that navigate somewhere when one is selected.  You need to use a select input control if you actually want to select and item and then read what you've selected.


text:
Q: How to check what part of a page a person is looking at I'm trying to make a site with a fixed navbar. The navbar will have a transparent background. I want to make the color of the text in the navbar to change based on the section of the site the user is looking at.
Let's say that the site starts by loading into a white page. The text in the navbar should start off by being black so that the user is able to read the text.
The user then scrolls to the next part of the webpage. Let's say that this part of the page is black. The text in the navbar should be white so that the user is able to read the text.
How do I do this? Do I need to use an event listener?

A:

(function($) {
  $(window).on('scroll', function() {
    if ($(this).scrollTop() > 200) {
      $('#stick').addClass('black-text');
    } else {
      $('#stick').removeClass('black-text');
    }
  });
})(jQuery);
body {
  margin: 0;
  padding: 0;
}
#stick {
  position: fixed;
  top: 2px;
  left: 2px;
  color: #fff;
}
#stick.black-text {
  color: #000;
}
#black {
  width:100%;
  height: 200px;
  background-color: #333;
}
#white {
  width:100%;
  height: 800px;
  background-color: #eee;
}

Sticked Menu

Assuming the height of each part is not dynamic, you may try this solution and see if this is what you need...


text:
Q: SSRS Chart Group by Dataset I have a chart in SSRS where I use data from two different datasets. Currently I have 2 values from dataset 1 and 2 values from dataset 2 but they are all grouped up into 1 category. Is there a way to group the data by datasets so I can display the data seperately?
Below is the table. The first row is data set 1 and the second row is data set 2

This is the chart I already have. I want to bring the dataset 2 values 3.45% and 29.27% in its own group and separate it from dataset 1 data on the same axis.

A: You will see some visual differences because I'm using 2016, but the theory of the chart building is the same.
[]
1[]2
Can you confirm if this is the chart that you are trying to build?
Here is a picture of how I setup the chart properties:


text:
Q: What is toLocaleString()? According to this MDN page, toLocaleString is about converting dates. However, Chrome exposes the function on more than strings. For example:
a = function () {};
a.toLocaleString();  // "function () {}"

What is the toLocaleString? Why is it exposed, for example, on the empty function?

A: It's also available on Object.prototype, so indirectly on pretty much anything.
For Chrome, you can look at V8's implementation, which doesn't do anything fancy:
function ObjectToLocaleString() {
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Object.prototype.toLocaleString"]);
  }
  return this.toString();  // <-- just calls toString
}


text:
Q: Algo question: iterating over multiple time series "as of" This question is not language specific.
Suppose I have N time-series named S_1, S_2, ... S_N. What I mean by time series is something like (schematically)
struct timeseries{T}
    values::Vector{T}
    timestamps::Vector{Timestamp}
end

where the two vectors have same length for each time-series.
You cannot assume that the time-series have the same number of elements. For a day worth of data, some of the time-seres might have millions of elements where others might have a couple of elements, but you can assume they all fit in memory simultaneously. You can assume all time-series are sorted in timestamps.
I would like to obtain another time-series which:

*

*has as many timestamps as the union of the timestamps of the N time-series

*for each timestamp t its value is a tuple of the values of the N time-series at a time less or equal t, when they exist and NaN otherwise
So for example, imagine we have two time-series which I represent as a list of tuples (timestamp,values):
S_1 = [(1,43),(4,20),(5,21),(10,10)]
S_2 = [(2,31),(4,-5),(6,-1),(11,100)]

The result would be:
[(1,43,NaN),(2,43,31),(4,20,-5),(5,21,-5),(6,21,-1),(10,10,-1),(11,10,100)]

A: This is easy if you have one useful data structure.
That data structure is a priority queue.  You stick things into a priority queue, and they come out in order of the priority.  So we can make our n time series into n tuples of (timestamp, queue, position, timeseries).  They will come out sorted first by timestamp, and then by queue.  There are no other ties.
For priority queues implemented with a heap data structure, inserting is O(log(n)), removing the head is O(log(n)) and merely reading the head is O(1).
And now we have an algorithm as follows:
# Initialize
Take our n timeseries, make n tuples (timestamp, queue, 0, timeseries)
Put the tuples into a priority queue
set last_timestamp = the timestamp of the first element in the queue.
set answer = [[last_timestamp, NaN, NaN, ..., NaN]]
set current_vector = answer[0]

# Work
while priority queue is not empty:
    (timestamp, queue, position, timeseries) = pop off of queue
    if timestamp = last_timestamp:
        current_vector = copy of current_vector
        current_vector[0] = timestamp
        answer.append(current_vector)
        last_timestamp = timestamp

    # Update for this record
    current_vector[queue] = timeseries[position][1]
    position = position + 1
    if position < len(timeseries):
        append to queue (timeseries[position][0], queue, position, timeseries)

If you have n timeseries, m timestamps, and k total entries, this algorithm will take O(n*m + k*log(n)).  (The first term is from creating new entries for the answer, the second is processing each timeseries entry.)

A: Here is how the solution looks for me (assuming that we include closest two timestamps from series1 and series2):

*

*prepare two binary search trees, one for series1, one for series2. let's call them bst1 and bst2. (bst entry consists of timestamp and value)

*scan through the timestamps of both series and put timestamps into the hashset. then sort the hashset values. in your example, the sorted keys will be [ 1, 2, 4, 5, 6, 10, 11 ]

*iterate through the sorted list of timestamps, and do following:

*

*check the timestamp for presence in bst1. if it is in bst1, then include it into the new tuple for the new series. if it is not in bst1, find its immediate predecessor in bst1. if there is no predecessor, include NaN into the new tuple.

*check the timestamp for presence in bst2. if it is in bst2, then include it into the new tuple for the new series. if it is not in bst2, find its immediate predecessor in bst2. if there is no predecessor, include NaN into the new tuple.

*add new tuple into the new series

A: This looks like a fairly straightforward merge operation. You start off with a tuple containing all NaN values, for as many timeseries as you have:
{NaN,NaN,NaN,NaN}

Put an iterator at the start of each sorted timeseries, and look at the elements they point to to find the first timestamp among them:
TS1: {(2,a),(3,b),(7,c)}
       ^
TS2: {(6,d),(12,e)}
       ^
TS3: {(1,f),(3,g),(5,h)}
       ^
TS4: {(4,i),(5,j),(8,k),(10,l),(12,m),(14n)}
       ^

The first timestamp at the iterators is 1 in timeseries 3, so we update its value in the tuple:
{NaN,NaN,f,NaN}

and add the tuple to the total timeseries with the current timestamp:
TS: {(1, {NaN,NaN,f,NaN})}

and we increment the iterator for timeseries 3 and move on:
TS1: {(2,a),(3,b),(7,c)}
       ^
TS2: {(6,d),(12,e)}
       ^
TS3: {(1,f),(3,g),(5,h)}
             ^
TS4: {(4,i),(5,j),(8,k),(10,l),(12,m),(14n)}
       ^

The first timestamp is now 2 in timeseries 1, so we update its value in the tuple:
{a,NaN,f,NaN}

and add the tuple to the total timeseries with the current timestamp:
TS: {(1, {NaN,NaN,f,NaN}), (2, {a,NaN,f,NaN})}

In the next step we see that there are two identical first timestamps at the location of the iterators:
TS1: {(2,a),(3,b),(7,c)}
             ^
TS2: {(6,d),(12,e)}
       ^
TS3: {(1,f),(3,g),(5,h)}
             ^
TS4: {(4,i),(5,j),(8,k),(10,l),(12,m),(14n)}
       ^

so we update the value of both timeseries 1 and 3 in the tuple:
{b,NaN,g,NaN}

and add the tuple to the total timeseries with the current timestamp:
TS: {(1, {NaN,NaN,f,NaN}), (2, {a,NaN,f,NaN}), (3, {b,NaN,g,NaN})}

and increment both iterators:
TS1: {(2,a),(3,b),(7,c)}
                   ^
TS2: {(6,d),(12,e)}
       ^
TS3: {(1,f),(3,g),(5,h)}
                   ^
TS4: {(4,i),(5,j),(8,k),(10,l),(12,m),(14n)}
       ^

And so on...
The advantage of this method is that it doesn't use additional data structures, just iterators over the timeseries. If creating an additional data structure is no problem, then use btilly's answer. If you have a large number of dataseries, you'd have to use something like a priority queue to find the first timestamp anyway, so then you basically have btilly's answer.


text:
Q: Multiplicative structure on solution space of a linear PDE Given a differential operator, $L$, on $\mathbb{R}^n$. I want to show that if $L$ satisfies the following properties
$$
Lf = Lg = 0 \implies L(f + g) = 0, \qquad L(fg) = 0
$$
then
$$
L = \sum_{i = 1}^n c_i \frac{d}{dx^i}, \qquad c_i \in \mathbb{R}
$$
I'm not sure how to rule out that higher order differential operators could have this nice multiplicative structure on the solution space.


text:
Q: How to use an object, save the value into an arrayList, and reuse the same object to keep getting user input I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.
I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).
I am new to Java, and this is homework, I have posted my code below that I have so far.  I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.
The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered.  So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.
I would welcome any guidance or advice, thank you for taking the time to read my post.
   package bankingSystem;

/**
 *
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;

    /**
     * Constructor to create a new savings account object that takes in a new
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The
    account name is " + accountName + " The account balance is " +
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) {
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit
Program\n");
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number
            }
            System.out.println("Please enter starting account balance e.g.
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new
    }
}

}

A: You don't need the last line:
SavingsAccount createSavingsAccount = new SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
because you initialize a new instance just remove it and then any new operation will overwrite the object old values just it.

A: Have you thought about just creating  an array of SavingAccounts with a fixed number of accounts?
SavingAccounts[] savingArray;
savingsArray = new SavingAccounts[10];

A: Since the value stored into the ArrayList is a reference(to the memory location of the object), you must create a new object or all the instances of that referenced object in the ArrayList will be of the same value.
I changed my code to create a new object each time a new account was created and then store the value of the newly created object.
Thank you everyone for your assistance.


text:
Q: InetAddress.getByName not working  I am looking for a computer named "Base" on the LAN
However, I cannot find it and what comes back is an address from my ISP (so Net access is definitely working). The return is "Base/81.200.64.50". Basically, it cannot find the name.
I'm using the emulator.
The code I am using is a copy of Java code that runs on Windows, and that works fine - returns my LAN address. What am I missing???
The code is:
InetAddress address = InetAddress.getByName(Constants.serverNameStr);

OK - the problem seems to be DNS lookup.
If I replace "Base" with "www.google.com" I get 74.125.230.145, which is google.
Seems the emulator cannot resolve the name using local router DNS.
I have tried tweaking Settings on the emulator but no luck.
Any ideas?

Also tried entering the DNS of the LAN router in the debug config of the emulator.
No luck

A: I am having a similar problem with not being able to get any useful information from InetAddress.getByName(), but I did figure out a couple things that might be of use:

*

*If you are using the DNS from your ISP (which you probably are) then your ISP may be giving you an IP address for one of its web sites when it cannot find the host that you requested.  For example, Comcast returns an IP address of a real web page when it can't find the host.  Most people who realize this do not want this behavior and you can fix it by changing the DNS addresses in your home router to point to Google's DNS servers.  Use 8.8.8.8 and 8.8.4.4 (for the primary and secondary DNS servers.)  Google's DNS servers are also generally faster and more secure.  After you change the DNS servers in your router, then InetAddress.getByName() will throw an UnknownHostException when you ask for a host that it cannot find.

*If you see a local machine name in the list of attached devices on your home router, you may need to add ".local" to the host name as the argument to InetAddress.getByName().  For example, Mac laptops will often have a hostname ending in ".local" but the router tables do not display that to the user.  (At least, my NetGear router does not show the ".local" part of a hostname.)

A: This method fails on Android apps when run on the main thread. You need to create a runnable thread similar to:-
public static class GetIPAddresses extends java.lang.Thread {
    public void run() {
        int i = 0;
        byte[][] addresses = new byte[20][];
        try {
            InetAddress[] machines = InetAddress.getAllByName("www.bing.com");
            for (InetAddress address : machines) {
                addresses[i++] = address.getAddress();
            }
        } catch (Exception e) { }
    }
}


text:
Q: Mac lag terribly when restarted from chosen Startup Disk My Mac has Filevault from quite some time ago.  Just now, I restarted it and went into recovery mode using cmd+R.
From there, I select Startup Disk from the menu, unlocked, and clicked restart.
After that, it restarted to the login screen and the computer started lagging really terribly at the startup screen. Even when I make furthur restarts by clicking on the Restart button at the login screen, the lag does not go away.
Does anyone know what is causing the lag?
(The lag went away when I clicked shutdown and turned on the computer.)

A: did you check for disk errors in Disk Utility?  Verify the disk, and repair if it finds anything.
If this is a sudden change, you could have either:

*

*a full disk

*a failing drive

*corruption


text:
Q: change global variable on given date I guess, this is a very simple question. I want my wordpress theme to automatically change some global variables on a given date.
My Theme changes color and some other things every two months. From now on, I want to type in the needed variables before that date and let Wordpress do the changes. I could do that from within the loop, so that the first person who enters the site on that date initiates the change. But that would mean extra code, everytime the loop is called. Is it possible to perform that task automatically?

A: I haven't used WP in ages, but I think this will work, change time_to_change_theme to the forward date you want. I have no idea where to put this, I am sure you will work it out though.
<?php

$time_to_change_theme    =   strtotime("2012-12-31 12:12:12"); // the time in the future you want to change the theme
$time_now = strtotime(now);

if($time_to_change_theme > $time_now)
{
   echo "Use current theme";
}else{
    echo "Change theme";
    update_option('current_theme', '[theme name]'); // this should update the current theme
}

?>

Uses code from this post by harmen


text:
Q: Android JSON Parsing "JSONException; Value Im trying to the use the following code below to parse JSON data, The website requires a API key, which for now is stored as a string in my strings.xml.
public class JSONParser {

static InputStream is = null;
static JSONArray jarray = null;
static String json = "";

// constructor
public JSONParser() {
}

public JSONArray getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {

        JSONObject jObj = new JSONObject(json);
        jarray = jObj.getJSONArray("systems");
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jarray;
}
}

MainActivity.
 public class MainActivity extends ListActivity {
private Context context;
private static String url = "https://api.company.com/api/systems";

private static final String TAG_SYSTEM = "systems";
private static final String TAG_SYSTEM_ID = "system_id";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;

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

    new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    private ListActivity activity;

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
        R.layout.list_item, new String[] { TAG_SYSTEM, TAG_SYSTEM_ID
                 }, new int[] {
                R.id.vehicleType, R.id.vehicleColor });

        setListAdapter(adapter);
        // selecting single ListView item
         lv = getListView();
    }
    protected Boolean doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();
        //Using APIKEY from strings.xml
        String apikey = getString(R.string.apikey);
        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);

        for (int i = 0; i < json.length(); i++) {

            try {
                JSONObject c = json.getJSONObject(i);

                String vcolor = c.getString(TAG_SYSTEM_ID);

                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_SYSTEM_ID, vcolor);
                jsonlist.add(map);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

}
Here is my current LogCat
  04-30 15:39:53.775: E/JSON Parser(9814): Error parsing data org.json.JSONException: Value   <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
04-30 15:39:53.780: E/AndroidRuntime(9814): FATAL EXCEPTION: AsyncTask #1
04-30 15:39:53.780: E/AndroidRuntime(9814): java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.lang.Thread.run(Thread.java:856)
04-30 15:39:53.780: E/AndroidRuntime(9814): Caused by: java.lang.NullPointerException
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:102)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-30 15:39:53.780: E/AndroidRuntime(9814):     ... 5 more
04-30 15:40:03.035: E/WindowManager(9814): Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814): android.view.WindowLeaked: Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:402)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Dialog.show(Dialog.java:277)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity$ProgressTask.onPreExecute(MainActivity.java:69)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.execute(AsyncTask.java:534)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity.onCreate(MainActivity.java:47)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Activity.performCreate(Activity.java:5206)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.access$600(ActivityThread.java:140)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Looper.loop(Looper.java:137)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.main(ActivityThread.java:4898)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invokeNative(Native Method)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invoke(Method.java:511)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
04-30 15:40:03.035: E/WindowManager(9814):  at dalvik.system.NativeStart.main(Native Method)

Can someone please help me fix these issues im having. Thank you in advance if you take the time to read and help.

A: The service obviously returns a server error. Try to either call the service with the same parameters from a client where you can see the response, or log the String response before you try to parse it to JSON. The exact server response will most certainly tell you what's wrong with your query.

A: It is an error from your server. You want to check status code
by calling httpResponse.getStatusLine().getStatusCode()
If the status code is 200, then you can start parsing your result. Otherwise, it is an error, you have to handle the error gracefully.


text:
Q: How to get title of content from the db by it's id I need to get title of category from db but I have id of this category. Categories and content have different tables but content are connected by field category with categories table. How can I load title of the category but not id????
The code that creates content are follows:
 <form action="create_content.php" method="POST" id="content_form" enctype="multipart/form-data" >

Title:

                <input type="text" name="title" value="">

Text

                <textarea name="text" id="text" cols="30" rows="20" form="content_form">
                </textarea>

Add image

<input type="file" name="content_pic">

        <select name="category">
            <?php foreach ($result as $item) {?>
                <option value="<?php print $item['id'] ?>"><?php print $item['cat_title'] ?>
                </option> <?php }?>
        </select>

            <input type="submit" value="Send">

 </form>

create_content($_POST['title'], $_POST['text'], $_FILES['content_pic'], $_POST['category']);

function create_content($title, $text, $content_pic, $category) {

      $title = trim($title);
      $text = trim($text);
      $category= $category;

      if (!empty($content_pic)) {
        if ($content_pic ["error"] == UPLOAD_ERR_OK) {
          $uploads_dir = __DIR__ . '/files';
              $tmp_name = $content_pic ["tmp_name"];
              $name = $content_pic ["name"];
              if (move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}")) {
                $content_pic = "files/{$name}";
              }
        }
      }

      $db = database_connect();
      /*if ($id) {
      $stmt = $db->prepare("UPDATE INTO content (id, title,text) VALUES (?, ?, ?)");
      $stmt -> execute(array($title ,$text, $id ));
      }
      else {*/

      $stmt = $db->prepare("INSERT INTO content (`title`,
              `text`,`content_pic`, `category`, `author`, `time`)
              VALUES (?, ?, ?, ?, ?, ?)");
      $stmt -> execute(array($title, $text, $content_pic, $category, $_SESSION['user_id'], time()));

      header("Location: review.php?id=" . $insertId=$db->lastInsertId());
      exit();

    }

Code that renders view:
    $id = $_GET['id'];
    $select_query = "SELECT `c`.`title`,`c`.`content_pic`,`c`.`text`,
                            `c`.`status`,`c`.`category`, `u`.`login`,
                            `u`.`id` AS `user_id`, `c`.`time`
                       FROM content c
                  LEFT JOIN users u ON c.author= u.id
                      WHERE c.id = ?";

      $db = database_connect();
      $stmt = $db->prepare($select_query);
      $stmt->execute(array($id));
      $result = $stmt->fetch(PDO::FETCH_ASSOC);

      if ($result) {
        $row = $result;
        $title = $row['title'];
        $content_pic =  $row['content_pic'];
        $text =  $row['text'];
        $category= $row['category'];
        $created = !empty($row['time']) ? date('d.m.Y H:i', $row['time']) : '';
        $author = 'Anonymous';
        if (!empty($row['login'])) {
          $author = '' . $row['login'] . '';
          }
      }

    ?>
<?php if ($result) {?>

                        <?php print $title ?>

                        <img src="<?php print $content_pic ?>" alt="">

                <?php print $text ?>

              <?php print $created?>

             <?php print $category ?>

<?php }?>

A: Why don't you join category table as well to get category title. Since you have mapped content table with category table.(I assumed your category table name is "category"). How do you get that $row['cat_title'], i don't see any cat_title in the select query ?
$select_query = "SELECT `c`.`title`,`c`.`content_pic`,`c`.`text`,`c`.`status`,`c`.`category`, `u`.`login`, `u`.`id` AS `user_id`, `c`.`time`, cat.title as cat_title
FROM content c
LEFT JOIN users u ON c.author= u.id
INNER JOIN categories cat ON c.category= cat.id
WHERE c.id =."(int)$id;


text:
Q: Need to implement nested try statements with one exception I am trying to copy a files from different folders under a path to my usb drive.
So my source directory structure looks like this
/user/arun/Music/Songs/
under this I have different sub directories
Songs_1
Songs_2
Songs_3
the target folder is under anyone of these Songs directory
Songs_1/Kid Rock/All summer long.mp3
Songs_2/Linkin Park/In the end.mp3
Now I am constructing my src_dir in a try/except way like this.
for album,song in song_database.iteritems():
    for s in song:
        try:
            src_dir_1 = src_dir + "/" + "Songs_1" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_2" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_3" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_4" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass

Is there a better way to do this ?

A: Seems like a loop would be better:
for album,song in song_database.iteritems():
    for s in song:
        for sdir in 'Songs_1', 'Songs_2', 'Songs_3':
            try:
                src_dir_1 = src_dir + "/" + sdir + "/" + album + "/" + s + ".mp3"
                shutil.copy2(src_dir_1,dest_dir)
                print src_dir_1
            except IOError:
                pass

And, perhaps you would want to add a break statement if you succeed in copying the source to the destination...
As a side note, you might want to use os.path.join instead:
src_dir_1 = os.path.join(src_dir, sdir, album, s + ".mp3")


text:
Q: Displaying pins around a point in google maps Is there a way to translate into javascript a piece of code that will allow me to show map pins around a point taking in consideration a radius ?
var data=[
  {long:3,lat:2},
  {long:5,lat:2},
  {long:2,lat:3}
];

aCoord={long:1,lat:2};

for(var i=0;i<data.length;i++){
  if (data[i] is 30 kms far from aCoord)
    myMap.addPin(data[i]);
}

myMap.autozoom();

Thank you,
Regards

A: I came up with this example so you have an idea on how to calculate the points. You'll need to figure out how to do any necessary conversions for lat/lon.
/**
* Returns coordinates for N points around a circle with a given radius from
* the center.
*
* center: array [x, y]
* radius: int
* num_points: int
*/
function get_points_on_circle(center, radius, num_points) {
    if (!num_points) num_points = 10;

    var interval = Math.PI * 2 / num_points;
        points = [];

    i = -1;
    while (++i < num_points) {
        var theta = interval * i,
            point = [Math.cos(theta) * radius + center[0], Math.sin(theta) * radius + center[1]];
        points.push(point);
    }

    return points;
}

// Sample usage
var center = [250, 250],
    radius = 100,
    num_points = 10;

var points = get_points_on_circle(center, radius, num_points);
Test it out (uses Raphael for plotting)
If you are interested in learning a little about the logic:

*

*A radian is a unit of measure for angles. There are a total of 2*PI radians in a circle. Using that fact, you can calculate the angle interval of any number of points on a circle by performing 2*PI/num_points.

*When you know the angle interval, you can calculate the angle (theta) of a point on a circle. Once you have theta (the angle), you have polar coordinates (radius,angle). For that to be of any use to us in this problem, you need to convert the polar coordinates into Cartesian coordinates (x,y). You can do that by using the following formulas:
x = cos(theta) * radius
y = sin(theta) * radius
That's pretty much it in a nutshell.


text:
Q: Calculate best dimensions for image based on height and width of container If I have a container which has a fixed width of 500px and height of 500px and an image with a width of 600px and height of 1200px whats the best way to calculate the dimensions I need to have the image 'fit' within the container while preserving the aspect ratio of the image?
If the image were smaller, by both width and height of the container; do nothing.
Based on the example dimensions above I know the best dimensions for the image are:
Width = 250
Height = 500
But what is the calculation I need to perform to achieve this?

A: If you want to display the image,
use max-height:100%; width:auto if your images are always vertical.
What this will do is make sure that your Image will always have the biggest height it can have (i.e. the same as the container it's in) while retaining it's width (= same AR, but a flexible size)

A: You have to first determine if it's the height or the width of the image is causing the shrinking of the image.  Then based on that you determine aspect ratio of the w/h of the image.  Then set the max value either height or width to 500 and multiply that by the aspect ratio to get the other number of the image.
In your example the aspect ration is 1/2, w/h and since you're shrinking the height to 500 the width should be 1/2 * 500 = 250 as the width.

A: JS:

$('.myimg').css('max-height', '100%');
$('.myimg').css('max-width', '100%');
.container {
  height: 500px;
  widtH: 500px;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bggreen{
  background: green;
}

It is much simple to use CSS Solution:
set img to max-height: 100%; and max-width: 100%;:

.container {
  height: 500px;
  widtH: 500px;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
}

.myimg {
  max-height: 100%;
  max-width: 100%;
}

.bggreen {
  background: green;
}

A: You can use image as the background of container div with background size fit to cover, that will help you to achieve it automatically.

.container {
  height: 500px;
  width: 500px;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}


text:
Q: WebStorm watcher output path I'm trying to set up a Typescript project in WebStorm where the files are transpiled to a dist-folder.
My project folder structure:
projectroot/src/subfolder/subfolder/index.ts

and I want the files to be placed like this:
projectroot/dist/subfolder/subfolder/index.js

My output path in WebStorm:
$FileDir$/../dist/

But the files doesn't retain the subfolder structure and the files land in
projectroot/dist/index.js

How can I get make it add the subfolder structure?

A: To access the project root, use $ProjectFileDir$ and $FileDirPathFromParent$
$ProjectFileDir$/dist/$FileDirPathFromParent(less)$/$FileNameWithoutExtension$.js

You need to test it though, couldn't test it on this computer.


text:
Q: Combine multiple MTKView/CAMetalLayer display I am using multiple MTKViews to display different contents on the screen along with normal UIView's (for displaying UI). I want to synchronize presentation of these MTKViews together with the same clock. Is there a way to synchronize the presentation of these MTKViews? In principal, I can combine the layouts of these views to a single MTKView but that would kill modularity of the code and not sure if I would achieve anything on the performance with so much of overwork.

A: A simple approach that should work in most cases would be to compute the time at which you'd like the frame to draw and use the present(_:atTime:) method of MTLCommandBuffer instead of the present(_:) method.

To exert greater control, it helps to understand what a command buffer's present... methods do and don't do. They do not encode any command into the buffer. As documented, they basically just add a scheduled handler to themselves that calls present on the drawable.
If you're careful about it, you can arrange to present the drawable in a way that doesn't much involve the command buffer.
But, does the command buffer using a scheduled handler make sense? Shouldn't it use a completed handler? After all, you want to display the completed rendering, right?
Well, drawables are smart about presenting themselves. The present method doesn't present immediately. A drawable tracks which scheduled commands might render or write to its texture. When present is called, that arranges for the drawable to draw itself on the screen as soon as possible after all such commands have completed. (Note that this does not imply that the command buffer itself has completed. There may be additional commands that don't involve the drawable's texture that aren't yet completed.)
This provides both challenges and opportunities for syncing the presentation of multiple drawables. The challenge is that, while you can control when you call present on each drawable, that doesn't necessarily sync their actual display, because each will display as soon it can after present is called and all commands involving its texture are completed, and that last part can occur at different times for different drawables.
One possible approach to solving this is to add a presented handler to the master drawable. The handler would call present on the other 3 drawables. After all of the command buffers are scheduled, call present on the master drawable. You can use a dispatch group to determine when all of the command buffers are scheduled. Enter the group once for each command buffer and add a scheduled handler to each that leaves the group. Then set a notify block on the group that does the master present. This technique probably won't achieve perfect synchronization because there's latency between when the master drawable has actually presented and when the presented handler is called, and then latency in presenting the other drawables.
Another possible approach is to set the presentsWithTransaction property of all of your CAMetalLayers to true. Then, when it's time to present, call waitUntilScheduled on each command buffer followed by present on each drawable. (Do not use a present... method of the command buffer.) This will guarantee that all of the drawables will present during the same Core Animation transaction – that is, synchronized.

A: You can use presentsWithTransaction

*

*Set presentsWithTransaction = true in MTKView

*Change commandBuffer commit style
 public func draw(in view: MTKView) {

 ...

 commandBuffer?.commit()
 commandBuffer?.waitUntilScheduled()
 view.currentDrawable?.present() }

Now all the metal views will be displayed synchronously.
It works for me.


text:
Q: How to use Blocks.Count() in a WPF RichTextBox? In a WPF RichTextBox I need to count all blocks of type Paragraph. Intellisense offers the Count<TSource>() method.

But using it this way:
int paragraphNumber = this.Document.Blocks.Count<Paragraph>();

I get the compile error CS1929 which states that BlockCollection does not contain any definition for "count".
Where am I wrong?

A: The type Count() expects is the type of your source collection items. In your case this would be the type Block as you are dealing with a BlockCollection. This type can usually be inferred from usage and be omitted, but you can't use that as a filtering method.
You can do it like this:
int paragraphNumber = this.Document.Blocks.OfType<Paragraph>().Count();

Or with a lambda expression:
int paragraphNumber = this.Document.Blocks.Count(x => x is Paragraph);


text: Q: Problem of loading data for csv format if following example from tensorflow keras This is the main problem I encounter, How can I load the data, if my data is from csv format? If I am using 'data.load_data(num_words=max_features)' will come out with erro ''DataFrame' object has no attribute 'load_data'. How to solve the problem ? Can you show me or teach me how ?


text:
Q: Right-click to select DataGrid Row not working I've read a few questions asking how to achieve DataGridRow selection when there's a right-click on the grid. The answers show a few different ways to achieve it and, for most part, they've worked for me except for this weird bug.
The row appears to be selected but unless the row is left-clicked first, the first row is always the row selected when the action is chosen. i.e. When I click edit on row 3, row 1's data will be passed to the edit form (unless I left click row 3 before right-clicking it)
This is the right-click menu showing the apparent selection:

Notice the little indicator is still on the first row.
If I dismiss the context menu, the row looks selected but is not:

If I left-click the same row it is now selected

Here's the code for the right-click event:
Designer code:
MyDataGrid.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);

Form code:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = MyDataGrid.HitTest(e.X, e.Y);
        MyDataGrid.CurrentCell = MyDataGrid.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
    }
}

What am I missing to actually select the row?

A: Replace your code in the MouseDown event call back with this:
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = dataGridView1.HitTest(e.X, e.Y);

        if (hti.RowIndex != -1)
        {
            dataGridView1.ClearSelection();
            dataGridView1.Rows[hti.RowIndex].Selected = true;
            dataGridView1.CurrentCell = dataGridView1.Rows[hti.RowIndex].Cells[0];
        }
    }
}

Here's a demonstration of it working:

A: You can make the right clicked row the focused row in the CellMouseDown event like this
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
     DataGridView1.CurrentCell = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
}

A: This is because right-click does not actually select the cell you've right-clicked on, only the left-click does this. You need to add a handler for the cell mouse down event, add this to your form's designer:
MyDataGridView.CellMouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);

And add this to your form's class:
private void MyDataGridView_MouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    MyDataGridView.CurrentCell = MyDataGridView(e.ColumnIndex, e.RowIndex);
}

This will set the CurrentCell a.k.a. The cell that's currently selected to whichever cell the cursor was over when the MouseDown event was called.


text:
Q: Making sense of the stress tensor for elastic deformations I've seen this kind of formula a number of times, in the context of elastic deformations.
$$ -\nabla \sigma = f $$
whete $\sigma$ is "the stress tensor" and $f$ is force. I never understood it even though I've coded finite element simulations several times. To me, it all comes down to defining an elastic energy in terms of positions $E(x)$ and then thinking about the body trying to minimize it and that's it, I can use the computer to take care of all the other details. However, I'm trying to understand the terms used in classical mechanics textbooks. First of all, what is $\sigma$ ? It seems to me, from the descriptions I've read that it's just a matrix. If that's true, then why call it a tensor? And also, what's the best way to interpret $\nabla$? Is it a function acting on a matrix? I guess it's some kind of derivative, but it's not clear to me what it computes exactly. Sometimes it appears as $\nabla.\sigma$ (with a dot in between), is it the same thing as $\nabla \sigma$?

A: This equation is just the Cauchy momentum equation under conditions of zero material derivative. It's the condition that arises when all motion has ceased and the body has reached equilibrium.
The nabla is an operator and it  should be with a dot in this case, $\nabla\cdot\sigma$, since it's the divergence operator (which decreases the tensor order by 1), whereas without a dot it denotes a gradient (which increases the tensor order by 1). See here for more about tensor derivatives.
Regarding the nature of $\sigma$ it is both a matrix and a tensor. A matrix is just a rectangular array of numbers; a tensor exhibits certain transformation properties. So if a matrix exhibits those same transformation properties then it is also a tensor (of rank 2). The difference between a matrix and a tensor has been discussed here many times before, e.g. see here.

A: The equation you have written (with the dot properly present) is just a differential force balance on a tiny volume of material within the body.  The left hand side of the equation (divergence of the stress tensor) is just the sum of the external forces (imposed by adjacent parcels of material) on the differential volume of material.  The right hand side of the equation is just the body force per unit volume (typically, gravity).  The stress tensor describes the state of stress at each location within a body, and is thus a function of position within the body.  To get an understanding of the stress tensor, why it can be represented by a matrix, the gradient vector operator (nabla), and how the divergence of the stress tensor leads to the sum of the forces on the tiny volume, you need to take a course in strength of materials or theory of elasticity.


text:
Q: Commutative operator + overloading causes infinite recursion #include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        s = "";
        for (int i=1; i<=n; i++) s += "x";
    }

    operator int () {
        return s.length();
    }

    StringNum operator + (StringNum v) {
        cout << "operator + is called\n";
        int len = s.length() + v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    template <class T>
    StringNum operator + (T value) {
        return (*this) + StringNum(value);
    }
};

template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // infinite recursion, despite StringNum + <class T> is defined
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // correct, output 6
}

int main()
{
    StringNum x(4);
    cout << (x + 2.5) << "\n"; // StringNum + <class T>, output 6
    int res = (2 + x);
    cout << res;
    return 0;
}

Class StringNum represents an integer number > 0, where length of the string is the number.
StringNum + StringNum are member functions and work correctly.
StringNum + <class T> is also a member function and works correctly.
However, for <class T> + StringNum, it requires a external function. However,  the behavior of operator + is confusing and doesn't make any sense:
template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // StringNum + <class T>, infinite recursion. Why??
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // StringNum + <class T> -> this time it's correct, output 6
}

How is it that num + StringNum(value) causes infinite recursion, while it should call StringNum + StringNum ? Also, why does num + value cause infinite recursion, while it should call StringNum + <class T> ? Finally, how does StringNum(num) + value solve the problem when num is a StringNum in the first place?
How can I correctly implement commutative operator + in this case ? Thank you.

A: Use correct constness:
StringNum operator + (const StringNum& v) const {
    cout << "operator + is called\n";
    int len = s.length() + v.s.length();
    StringNum res;
    for (int i=1;i<=len;i++) res.s += "x";
    return res;
}

template <class T>
StringNum operator + (T value) const {
    return (*this) + StringNum(value);
}

Demo
As In your template,
You call operator+ with const StringNum& and StringNum
And candidates are:

*

*StringNum StringNum::operator + (StringNum v) Doesn't match, apply only to non const lhs

*template <class T> StringNum StringNum::operator + (T value) Doesn't match, same reason as above

*template<class T> StringNum operator + (T value, const StringNum& num) Matches, so leading to infinite recursion.


text:
Q: Create a linear trend line in Excel graphs with logarithmic scale I I have an Excel scatter chart with x and y values.
I set the logarithmic scale in x-axis and y-axis.
When I add a linear trend line to the graph, the line is not linear but appears like a curve.
How can I make a linear trend line on a logarithmic-scaled chart?
Sample data:
x:
18449
22829
25395
36869
101419
125498
208144
2001508
14359478
17301785

y:
269,09
273,89
239,50
239,50
175,13
176,73
151,94
135,15
131,55
121,55

A: Adding a Power Trendline seems to have worked. tusham has kindly saved me the trouble of explaining why:

The power trendline is given by y=c*x^b. Believe it or not, you can use LINEST to calculate the parameters. Here's how.
Take the log of the above equation to get ln(y)=ln(c)+b*ln(x). This is a linear equation!

and

A log-log display of the data doesn't change the underlying analysis. If you plot a bunch of X,Y pairs and ask for a power trendline, you will get the same result irrespective of whether the plot shows either or both of the axes on a log scale.


text:
Q: SQL Query to place prefix in all records of particular field Second table was misconstructed using an integer instead of a string. Original table used a string. ( field's string is an amalgam of three other numeric IDs compacted into one field )
Turns out that linking to the other table with int-to-string has issues. I want to change the field in 2nd table from integer to a string and prefix "00" ( zero-zero ) in front of the existing integer - which is now a string. That's the only difference between the two.
I can probably match the two with a "LIKE" I guess, but want exact matches, and this should be a one-time fix.
Thanks!
Jolly

A: What about (in MySQL)
SELECT CONCAT('00', CAST(field AS CHAR)) AS newfield

However, what about converting the first table from string to int?

A: First add another columns of string data type with same data as integer data column.
UPDATE table SET column2 = CAST(column1 AS CHAR)
Then you can prefix '00' to the column to using following query.
UPDATE table SET column2 = CONCAT('00',column2)
HOpe this solves your problem

A: Assuming MySql you want to first change your datatype of the column, like this
ALTER TABLE tab MODIFY COLUMN IDBoth VARCHAR(10); -- or what ever size is needed

Then do an update with a concat like this:
UPDATE TAB as t1
JOIN tab as t2
ON t1.id1 = t2.id2 -- Add additionation join criteria if needed to get right join
SET t1.IDBOTH = CONCAT('00', t1.IDBOTH);

See it in action with this SQLFIDDLE


text:
Q: viewdidappear not getting called when canceling UIImagePicker After I cancel the image picker, the viewWillAppear gets called but the viewDidAppear does not get called. And subsequent loading of that view by going up and back down the stack does not help it.
Only if I switch to another Tab and then switch back, do I get the viewdidappear calling.
I use this code to cancel the image picker (iOS 6)
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissViewControllerAnimated:NO completion:^{
        self.imgScrollView.hidden=NO;
    }];
}

A: You are trying to dismiss the viewController which presented the imagePickerController, try using picker instead of self something like this:
-(void) imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
    [picker dismissViewControllerAnimated:NO completion:
    ^{
          self.imgScrollView.hidden=NO;
    }];
}


text:
Q: Forwarding TCP traffic from Traefik to a Docker container I currently have a Traefik instance that's being run using the following. It works fine forwarding HTTP connections to the appropriate backends.
  services_lb:
    image: traefik:v2.2
    cmd: |
      --entrypoints.web.address=:80
      --entrypoints.websecure.address=:443
      --entrypoints.web.http.redirections.entryPoint.to=websecure
      --entrypoints.web.http.redirections.entryPoint.scheme=https
      --entrypoints.web.http.redirections.entrypoint.permanent=true
      --entrypoints.matrixfederation.address=:8448
      --entrypoints.prosodyc2s.address=:5222
      --entrypoints.prosodys2s.address=:5269
      --providers.docker
      --providers.docker.constraints=Label(`lb.net`,`services`)
      --providers.docker.network=am-services
      --certificatesresolvers.lec.acme.email=notify@battlepenguin.com
      --certificatesresolvers.lec.acme.storage=/letsencrypt/acme.json
      --certificatesresolvers.lec.acme.tlschallenge=true
      --entryPoints.web.forwardedHeaders.trustedIPs=172.50.0.1/24
    ports:
      - 80
      - 443
      # Matrix
      - 8448
      # XMPP
      - 5222
      - 5269

My web and Matrix federation connections work fine as they're all HTTP. But for Prosody (XMPP) I need to forward 5222 and 5269 directly without any HTTP routing. I configured the container like so:
  xmpp:
    image: prosody/prosody:0.11
    network:
      - services
      - database
    labels:
      lb.net: services
      traefik.tcp.services.prosodyc2s.loadbalancer.server.port: "5222"
      traefik.tcp.services.prosodys2s.loadbalancer.server.port: "5269"
      traefik.http.routers.am-app-xmpp.entrypoints: "websecure"
      traefik.http.routers.am-app-xmpp.rule: "Host(`xmpp.example.com`)"
      traefik.http.routers.am-app-xmpp.tls.certresolver: "lec"
      traefik.http.services.am-app-xmpp.loadbalancer.server.port: "5280"
    volumes:
      - prosody-config:/etc/prosody:rw
      - services_certs:/certs:ro
      - prosody-logs:/var/log/prosody:rw
      - prosody-modules:/usr/lib/prosody-modules:rw

With the tcp services, I still can't get Traefik to forward the raw TCP connections to this container. I've tried removing the --entrypoints from the Traefik instance and of course, Traefik stopped listening on those ports. I assumed the traefik.tcp.service definition would cause that entrypoint to switch to a TCP passthrough mode, but that isn't the case. I couldn't see anything in the Traefik documentation on putting the entrypoint itself into TCP mode instead of HTTP mode.
How do I pass the raw TCP connection from Traefik to this particular container using labels on the container and CLI options for Traefik?

A: I figured it out. You can't use any standard Traefik TLS offloading due to the differences in how Traefik and Prosidy handle TLS. I had to disable TLS entirely and use the special HostSNI(*) rule below to allow straight pass throughts. I was also missing the routers that connect the Traefik entrypoints to the TCP services.
        labels:
          lb.net: services
          # client to server
          traefik.tcp.routers.prosodyc2s.entrypoints: prosodyc2s
          traefik.tcp.routers.prosodyc2s.rule: HostSNI(`*`)
          traefik.tcp.routers.prosodyc2s.tls: "false"
          traefik.tcp.services.prosodyc2s.loadbalancer.server.port: "5222"
          traefik.tcp.routers.prosodyc2s.service: prosodyc2s
          # server to server
          traefik.tcp.routers.prosodys2s.entrypoints: prosodys2s
          traefik.tcp.routers.prosodys2s.rule: HostSNI(`*`)
          traefik.tcp.routers.prosodys2s.tls: "false"
          traefik.tcp.services.prosodys2s.loadbalancer.server.port: "5269"
          traefik.tcp.routers.prosodys2s.service: prosodys2s
          # web
          traefik.http.routers.am-app-xmpp.entrypoints: "websecure"
          traefik.http.routers.am-app-xmpp.rule: "Host(`xmpp.example.com`)"
          traefik.http.routers.am-app-xmpp.tls.certresolver: "lec"
          traefik.http.services.am-app-xmpp.loadbalancer.server.port: "5280"


text:
Q: Securing Post Comment Like System I have a PHP script that very much like a commenting system, but requires a confirmation of the suggested comment first.
Example:
1) User enters comment.
2) Users is sent to confirm page that displays comment and ask user to confirm it is correct.
3) User confirms and the comment is inserted into a database.
My questions is, which PHP functions are best to secure the display of the the comment on the confirm page, and then to insert it into a database. Do i also need something to secure it after fetching it from a database for display afterwards?

A: I'm a little confused as to what you mean, but I'm assuming that you're trying to ensure against SQL injection? i.e; a user can't type in '; UPDATE users SET password = 'abc' WHERE user = 'admin'; etc?
If so, you're looking for http://www.php.net/manual/en/mysqli.real-escape-string.php . Or mysql_real_escape_string() if you're using the deprecated functions.
Hope this helps - if not, please provide a little more clarification on what exactly you're looking for :)

A: If you talk about code security, one should always stick to the golden rules :

*

*Filter all input ( filter_var() or any framework included class)

*Escape all output ( at least htmlspecialchars() )

There are many levels to secure a form, or an entire application. These two are just primers.


text:
Q: Yii2 - supersized-widget slide show issue I have a problem that needs to be solved. I need to include a full screen slide show in a Yii2 Basic app.
In Yii1.xx I used to use with no problem Supersized slide show extension, but in yii2 I can't install Yii2 Supersized widget via composer.json (I update composer) but it says it can not find the widget. So i download the zip file and place it under vendor vendor/yiisoft/yii2-supersized-widget-master.
The deal is that I don't know how to activate it, I think due to the lack of namespace in the instructions (that are inexistent) it always throws me the error -> Class 'Supersized' not found.
The link to the supersized page is:
https://github.com/xjflyttp/yii2-supersized-widget
Is there someone that knows how to put this widget working in the site/index.php page of Yii2.
Or is there a better and ready working full screen slideshow to use with Yii2?
Many thanks in advance.

A: Try to install it with composer using dev-master.
"xj/yii2-supersized-widget": "dev-master"

Worked for me.


text:
Q: asp.net MVC authentication with Shibboleth Shibboleth is a SSO Authentication that is added to IIS as a "plugin".
After a user has done a Login there are Headers showing the Shibboleth Session:
ShibSessionID
ShibIdentityProvider
eppn
affiliation
entitlement
unscopedaffiliation
...more
So i can extract username and roles from the Headers.
so far so fine.
Question:
How can I implement a handler that does read the headers and set the status that a user is authorized?
Idea is to use the
[Authorize]
Attribute and the Method
Roles.IsUserInRole.
All from the Headers, no Database, no User Management.
Update
Implementation According to the Answer from @Pharylon
In this Update there is nothing new, just a help for the copy&past friends.
Of course you have to adjust the properties and Header fieldnames according to your Shibboleth Setup.
File: ShibbolethPrincipal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal; //GenericPrincipal

namespace Shibboleth
{
    public class ShibbolethPrincipal : GenericPrincipal
    {
        public string username
        {
            get { return this.Identity.Name.Replace("@ksz.ch", ""); }
        }

        public string firstname
        {
            get { return HttpContext.Current.Request.Headers["givenName"]; }
        }

        public string lastname
        {
            get { return HttpContext.Current.Request.Headers["surname"]; }
        }

        public string phone
        {
            get { return HttpContext.Current.Request.Headers["telephoneNumber"]; }
        }

        public string mobile
        {
            get { return HttpContext.Current.Request.Headers["mobile"]; }
        }

        public string entitlement
        {
            get { return HttpContext.Current.Request.Headers["eduzgEntitlement"]; }
        }

        public string homeOrganization
        {
            get { return HttpContext.Current.Request.Headers["homeOrganization"]; }
        }

        public DateTime birthday
        {
            get
            {
                DateTime dtHappy = DateTime.MinValue;
                try
                {
                    dtHappy = DateTime.Parse(HttpContext.Current.Request.Headers["dateOfBirth"]);
                }
                finally
                {

                }

                return dtHappy;
            }
            set {}
        }

        public ShibbolethPrincipal()
            : base(new GenericIdentity(GetUserIdentityFromHeaders()), GetRolesFromHeader())
        {
        }

        public static string GetUserIdentityFromHeaders()
        {
            //return HttpContext.Current.Request.Headers["eppn"];
            return HttpContext.Current.Request.Headers["principalName"];
        }

        public static string[] GetRolesFromHeader()
        {
            string[] roles = null;
            //string rolesheader = HttpContext.Current.Request.Headers["affiliation"];
            string rolesheader = HttpContext.Current.Request.Headers["eduzgEntitlement"];
            if (rolesheader != null)
            {
                roles = rolesheader.Split(';');
            }
            return roles;
        }
    }
}

File: ShibbolethController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Shibboleth
{
    public class ShibbolethController : Controller
    {
        protected new ShibbolethPrincipal User
        {
            get
            {
                return (base.User as ShibbolethPrincipal) ?? null; //CustomPrincipal.GetUnauthorizedPrincipal();
            }
        }
    }
}

File: Global.asax
void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var ctx = HttpContext.Current;

            var principal = new ShibbolethPrincipal();
            HttpContext.Current.User = principal;
        }

Using examples:
 namespace itservices.Controllers
    {
        [Authorize] //examples : [Authorize(Roles="Administrators")], [Authorize(Users="Alice,Bob")]
        public class PasswordMailController : ShibbolethController
        {

    if(User.IsInRole("staff"))
    {

A: You'll want to create a method in Global.asax.cs that has the following signature
protected void Application_PostAuthenticateRequest()
{
    //Your code here.
}

This will be called automatically before almost anything else is done (MVC will call this method if it exists, you don't have to "turn it on" anywhere), and this is where you need to set the Principal. For instance, let's assume you have a header called RolesHeader that has a comma separated value of roles and another header called UserId that has (duh) the user ID.
Your code, without any error handling, might look something like:
protected void Application_PostAuthenticateRequest()
{
    var rolesheader = Context.Request.Headers["RolesHeader"];
    var userId = Context.Request.Headers["UserId"];
    var roles = rolesheader.Split(',');
    var principal = new GenericPrincipal(new GenericIdentity(userId), roles);
    Context.User = principal;
}

It's the Principal/Identity that the [Authorize] attribute uses, so setting it here at the beginning of the request lifecycle means the [Authorize] attribute will work correctly.
The rest of this is optional, but I recommend it:
I like to create my own custom classes that implement IPrincipal and IIdentity instead of using the GenericPrincipal and GenericIdentity, so I can stuff more user information in it. My custom Principal and Identity objects then have much more rich information, such as branch numbers or email addresses or whatever.
Then, I create a Controller called BaseController that has the following
protected new CustomPrincipal User
{
    get
    {
        return (base.User as CustomPrincipal) ?? CustomPrincipal.GetUnauthorizedPrincipal();
    }
}

This allows me to access all my rich, custom Principal data instead of just what's defined in IPrincipal. All of my real controllers then inherit from BaseController instead of directly from Controller.
Obviously, when using a custom Principal like this, in the Application_PostAuthenticateRequest() method, you'd set the Context.User to be your CustomPrincipal instead of a GenericPrincipal.


text:
Q: Bootstrap drop down throwing itself to the right of my menu hoping one of you will be able to help!
I'm currently building a website and having to fumble through code a bit using Bootstrap, im coming to the closing end of finalising it however ive hit an issue where one of my drop down menus fire off to the right when clicked, i've done a bit of googling and trying to mess about with the code but i cant get it to sit right.
HTML is as follows

                <button type="button" class="btn btn-dark btn-xs">About Us</button>
        <button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">
                    Programmes
                </button>

                    Private
                    Veteran
                    Young Adult
                    Sponsor
                    Volunteer
                    Fundraise

                <button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">
                    Media
                </button>

                    Pictures
                    Blog
                    Newsletter

        <button type="button" class="btn btn-dark btn-xs">Donate</button>

Nothing has been changed in the Bootstrap CSS other than the colours of the buttons themselves
Any ideas?
Many thanks!

A: Everything is fine you just need to wrap div having class of btn-group above Programms button tag

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

      <button type="button" class="btn btn-dark btn-xs">About Us</button>

        <button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">
          Programmes
        </button>

          Private
          Veteran
          Young Adult
          Sponsor
          Volunteer
          Fundraise

        <button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">
          Media
        </button>

          Pictures
          Blog
          Newsletter

      <button type="button" class="btn btn-dark btn-xs">Donate</button>


text:
Q: Simple Kendo grid cell Template to display cell data in no wrapped way with ending '...' and a button I would like to display longer text cells in no multiline and word wrapped mode, instead in a form: |Alfred Fu... [mybutton]|
Unfortunatelly I can not solve how to keep the ending '...' and the button in one line within the cell:

My custom working sample can be viewed and edited here in Telerik dojo playground
I know the no word wrap can be achieved by CSS white-space: nowrap; I also know I should use column Template (.ClientTemplate("...") in ASP MVC). I am utilizing kendo templating infrastructure, so my template is not inline.
The column:
columns: [{
    ...
}, {
    field: "CompanyName",
    title: "Company Name",
    width: 100,
    template: "#=getClientViewTemplate(data.CompanyName)#",
}, {
   ....
}]

The kendo template (note: using bootstrap 3, what is referenced in the working sample via maxcdn):

I would like to keep those "...", and at the same time I would like to have the data and the button in one line within the cell. How can I accomplish this?

A: You can solve this, give styles.
Like this css:
.widthStyle
{
     width: 50px;
     overflow: hidden;
     white-space: nowrap;
     text-overflow: ellipsis;
     float:left;
}

and html:

    #=text#

this is working, link

A: I've got the feeling (maybe I am wrong) that the automatic ... rendering comes from the outer td, which have role=gridCell, and measures the text length. So it hopeless to trick out. ...unless we have a dedicated td with role=gridCell for the text. The only way I could figure out is an embedded table with one row and two cells.
Here is what I've ended: see in action
Style:

Template:


text:
Q: Disable automatic embed links Is there a way on current wordpress versions (5.2..), to turn of the automatic embed links(wp-embed.min.js), that will turn an url into an iframe?
I have tried plugins, snippets, functions.php ... it seams that none of them work anymore for wp latest versions.

A: Have you tried this?
function dequeue_embed_script() {
    wp_dequeue_script('wp-embed');
}

add_action( 'wp_enqueue_scripts', 'dequeue_embed_script', 9999 );


text:
Q: "Maximum request length exceeded" error even after setting maxAllowedContentLength I'm using IIS 6.2 and my solution has a file-upload control and trying to upload a bunch of images but i get this error.I have searched the internet and got a lot of solutions but none of them worked.

I have applied  maxAllowedContentLength="1073741824" but still get the same error.

protected void lnkbtnUpload_Click(object sender, EventArgs e)
{
    try
    {
        foreach (HttpPostedFile objHttpPostedFile in fuUpload.PostedFiles)
        {
            string FileName = objHttpPostedFile.FileName;
            string FileType = objHttpPostedFile.ContentType;
            Stream fs = objHttpPostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("uspInsertImage", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("Filename", SqlDbType.NVarChar).Value = FileName;
                cmd.Parameters.Add("FileType", SqlDbType.NVarChar).Value = FileType;
                cmd.Parameters.Add("ImageStream", SqlDbType.VarBinary).Value = bytes;
                cmd.Parameters.Add("DateCreated", SqlDbType.DateTime).Value = DateTime.Now;
                int i = cmd.ExecuteNonQuery();
                con.Close();
            }

            BindImage();
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

My Web.Config File
<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="4073741824" />
    </requestFiltering>
  </security>

A: requestLimits settings have been added since IIS 7.0.
For IIS 6 you need to use:
<system.web>
    <httpRuntime maxRequestLength="1048576" executionTimeout="100000" />
</system.web>

This allows a file upload of 1 GB and it will time out after 100,000 seconds, or 27.8 hours.

A: Maximum request limited is there to protect your website against denial of service attacks so it's best to expand the file-size limit for specific directories rather than your entire application
you can do it with
<location path="Upload">
<system.web>
    <httpRuntime executionTimeout="110" maxRequestLength="1048576" />
</system.web>

and you can use the code below to show a warning to the users when they try to upload something higher than max limit, adding a warning will improve your website UX
    System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
double maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1);
FileSizeLimit.Text = string.Format("Make sure your file is under {0:0.#} MB.", maxFileSize);

Note: maxRequestLength is measured in kilobytes, which is why the values differ in this config example. (equivalent to 1 GB.)


text:
Q: What makes documentation good? I need to write documentation for several projects I worked on. I was wondering what, according to your experience, makes documentation useful and complete. What part should I include, how deep should I go in my explanation, etc?
My target audience is developers. The purpose of the documentation is to make it easy to update or finish projects.

A: I want to know why.
Documentation, whether comments or a Word file, should not make the code redundant. I know what the code does - it's right there for me to read. I want to know why...

*

*It exists. What purpose does it fulfill?

*It was written that way. Was it just the first way that came into your head, or is there a good reason for that ugly try block?

*It was designed that way. If you made a class that allows communication with legacy code, but makes no sense if legacy didn't exist, I want to know that before I go, "What was this idiot thinking?"

A: Since I've seen only one minor mention: Screenshots!
Even for CLI-only tools, it can help to solidify certain concepts.  A method I employ is capturing the whole window with a bit of background.  Then I'll change the background for subsequent shots.  It helps to distinguish the images, especially for people coming back to reference.  See, e.g...
Also, screencasts!  It's great to have reference material in text, but when you're first getting into a tool it's even better to have someone familiar with it step you through the basics of the interface.

A: Step by Step how-to guides.
On a wiki preferably, so they can be changed as soon as something needs updating.

A: I like examples. If you have an API that performs a variety of foo operations on bar objects, include practical examples, not just a single line showing how to call the function.
Also make sure you include somewhere a high-level "big picture" overview of whatever is being documented. It's great to know the different types of foo operations available, but it's also good to know why there are different variations, and some guides as to know when to use which variant.
For some systems, a brief developer-centric user manual is also good. This is important if new developers don't even know to use the existing parts of the project.
A setup guide for building and compiling is also very important if the setup is non-trivial (more than just add files to IDE project and click "compile"). This may include database connections, and server configuration.

A:
The purpose of the documentation is to make it easy [for developers] to update or finish projects

Then good documentation achieves that purpose.
To make good documentation, get some information from people who will be using your documentation.
Question 1.  What can't they do now?  Why are they unable to update or finish a project?
Collect answers to the question from everyone involved.  Stakeholders and non-stakeholders.
Once you have some reasons, you have to find causes for those reasons.
Question 2.  What prevents them from updating or finishing a project?
Collect answers to the question from everyone involved.
Once have have root causes, you have to get some solutions to those problems.
Question 3.  What changes would help update or finish a project?
Ideally, the answer to this question is "more information, specifically..."
If so, that's what your documentation will include, the specific information required.  Question 3 tells you specifically what makes good documentation.
If, on the other hand, information isn't the solution, stop writing documentation.  Keep digging into cause and effect and solve the problem.

A: *

*State the objective (purpose) of the documentation at the beginning.

*Include a table of contents if the documentation spans several pages.

*Be as specific as possible when writing things down.

*Everything in your head should be on paper.

*Include figures and screenshots where appropriate as they visualize what you are writing about.

You will know if the documentation is good if after several months you need to read it again and you can understand everything that you wrote down and that it makes sense.

A: Examples should be must. And from my point of view(as a student), the person who is seeing your document should not search a lot.
Your document should be in good hierarchy , so that getting an information is really easy :)

A: Write tests.
What I most want when I take over a project is a good set of automated tests. By good, I mean:

*

*They all run,

*They are clearly written,

*They convey both they why and the what, and

*They are more or less comprehensive.

I like tests better than regular docs because a computer can verify that they still apply. Basically, tests are executable documentation.
On top of that, I'd like a 1-3 page document on the system architecture, plus a well-organized and well-named code base.

A: Test documentation just like a usability test. Give the document to a user with no explanation and watch over their shoulder to see if they get any value out of it. Hopefully it meets your objective.

A: Use an iterative approach to writing documentation. Once you've written up a basic set of instructions, do the following:

*

*Give the document to a user. Ask them to use it to perform the task.

*Note any questions or problems they encounter.

*Edit the document to address the questions or problems.

*Repeat.

You're done when your user has no more questions or problems.

A: For Java programs there are two things that really make a difference:

*

*Functional unit tests showing how the code is to be used.  For code developed with test-driven design this essentially is the specification in runnable form.

*javadoc - i.e. the embedded HTML snippets which end up in http://download.oracle.com/javase/6/docs/api/ except for your code.

Well done, these two together can account for - IMHO - around 90% of the documentation.

A: To throw in something from the last century which has become almost a dead art:
A good index.  By that I mean key reference emboldened, further (relevant) references and further information / examples sub-listed.  Examples picked out.  Multiple references to varying uses and synonyms.  Accurate page numbers (or links).  Most tech books completely fail on this these days.  (I'm amazed no one has mentioned indexes yet)
Thinking from an API doc perspective, good cross referencing to alternative calls and why you might want them.  "Trying to print a graphic?  You probably need gfxPrint not Print, see pp 888" etc.
Makes learning go so much faster when you're past the worked examples and wanting to fly alone - 10 mins of google every api call isn't helpful.
JFGI or a search box isn't enough as that will get 80% irrelevant references to the API and so often doesn't easily pick up the right reference or the case you're googling the wrong one.


text:
Q: How to only allow alphanumeric using ng-pattern-restrict for first character only? I'm using https://github.com/AlphaGit/ng-pattern-restrict to restrict input.  What I"m trying to do is only allow alphanumeric for the first character ONLY.  The problem is if I use :
ng-pattern-restrict="^[a-zA-Z0-9]+"
it works, but won't allow user to clear the whole string, which I would also like as an option.

A: Update your regex to check for the empty string scenario. Example below:
^$|^[A-Za-z0-9]+

Plunker

A: ng-pattern-restrict="^([A-Za-z0-9]{0,})$"

This will allow only alhpanumeric values.

A: This pattern allows at least one alphabets and one numeric value but does not allows any special characters.
ng-pattern="/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/"

A: This expression will help in clearing the input as well not allow any spcial character in the input at any position :   ng-pattern-restrict="^$|^[A-Za-z0-9]+$"


text:
Q: Haskell Type Level Equality Haskell has a resticted syntax to define type families:
(1)   type family Length (xs :: [*]) where
(2)     Length '[] = 0
(3)     Length (x ': xs) = 1 + Length xs

On the lines (2) and (3) on the left side of the equal sign (=) we only have simple pattern matching.
On the right side of the equal sign we have just type level function application and as a syntactic sugar
there are type operators ((+) in line (3)).
There are no guards, no case expressions, no if-then-else syntax, no let and where's
and there is no partial function application.
This is not a problem, as the missing case expression can be replaced by a specialized type level function,
that pattern matches on the different cases, the missing if-then-else syntax can be replaced by the If
function of the Data.Type.Bool
package.
Looking at some examples we see, that pattern matching syntax on the type level has at least one
additional feature, not available in normal Haskell value level functions:
(1)   type family Contains (lst :: [a]) (elem :: a) where
(2)     Contains (x ': xs) (x) = 'True
(3)     Contains '[]       (x) = 'False
(4)     Contains (x ': xs) (y) = Contains xs (y)

In line (2) we use twice the variable x. Line (2) evaluates to 'True, if the head of the list of the first parameter
is equal as the second parameter.
If we do the same thing on a value level function, GHC answers with a Conflicting definitions for 'x' error.
In value level functions we must add an Eq a => context to compile the function.
Type level pattern matching seems to work similar as unification back in the old times of Prolog.
I unsuccessfully googled for some documentation about the syntax of type level functions.

*

*Why does GHC not require something like an a ~ b type equality constraint in the definition of the Contains type family?

*Is type equality always available?

*Has the type family syntax other additional features, that are unavailable on the value level?

*Where is this documented?

A: Haskell's type-level language is a purely first-order language, in which "application" is just another constructor, rather than a thing which computes. There are binding constructs, like forall, but the notion of equality for type-level stuff is fundamentally mere alpha-equivalence: structural up to renaming of bound variables. Indeed, the whole of our constructor-class machinery, monads, etc relies on being able to take an application m v apart unambiguously.
Type-level functions don't really live in the type-level language as first-class citizens: only their full applications do. We end up with an equational (for the ~ notion of equality) theory of type-level expressions in which constraints are expressed and solved, but the underlying notion of value that these expressions denote is always first-order, and thus always equippable with equality.
Hence it always makes sense to interpret repeated pattern variables by a structural equality test, which is exactly how pattern matching was designed in its original 1969 incarnation, as an extension to another language rooted in a fundamentally first-order notion of value, LISP.


text:
Q: python regular expression dose not match the last end of line I'm just learning python regular expression and I don't understand why it matches the last '\n':
import re

s = 'abc\t'   # no
# s = 'abc\n'   # yes

if re.match('^(\S+)$', s):
    print 'yes'
else:
    print 'no'

As far as I know, '\S' should not match '\t' or '\n', but here '\n' is matched. Any Help?