text:
Q: Setting a static final variable in constructor what i basicly want is this:
public class Test
{
   private static final Integer a;

   public Test(Integer a)
   {
      this.a = a;
   }

}
This obviously doesn't work, cause the 2nd created instance would try to override the final variable.
So is there a way to give all the instances the same immutable value via the constructor?

A:
So is there a way to give all the instances the same immutable value via the constructor?

I assume you want a value to be assigned to a the first time an object of type Test is created but not when any subsequent instance is created. In that case you cannot declare it final. a will be null initially, the constructor has to check if it is null and assign it a value in that case.
But I urge you to look at the design, especially why the caller have to provide the value. Isn't it counter-intuitive that after the second Test object is created Test.a does not change in the following case?
// assume this is the first `Test` object created:
Test t = new Test(5); // Test.a is 5
Test t = new Test(6); // Test.a is *still* 5

A: Static final values should be initialized in a static context, not by instances.
One options is to set the value in the declaration:
private static final Integer a=FileConfig.getInstance().getA();

Each class can have a static {} block where code is called to initialize the static parts of the class.
static {
    a = FileConfig.getInstance().getA();
}

Finally, you can set the value from a static method
private static int getA() {
    return FileConfig.getInstance().getA();
}

private static final Integer a=getA();

In closure, static instance initialization does not belong in instance constructors.
If the configuration values change sometimes, there is simply no reason to store the value a in a static final variable. If you want to create each instance with the constant a in the constructor, what is the purpose of a static field in the first place? Somehow, when you call the constructor for the first time, you are passing in a value from somewhere. If the value deserves to be static and final, you can acquire it from within the static initializer. If the configuration is not a singleton, but every instance always produces the same value of a, you could easily do a = new FileConfig().getA();.
Other than that, you could make the value non-final, and rest assured that since you always put in the same value of a, the static variable will not change.
Still, you could make a a final instance variable of the class, set in the constructor.


text:
Q: Update $scope in an $interval function I have a login page designed using angular-material. Along with this I also have a password manager chrome extension which works well on many other websites.
What I am trying to achieve is to make the login page compatible with my password manager extension. The extension is provided with the id of the fields, next it fetches the data to be inserted into it and in the last it fills the input with the fetched value. This is done using pure JS like below:
var inputBox = document.getElementById(fieldId);
if (typeof inputBox !== "undefined" && inputBox !== null) {
    inputBox.click();
    inputBox.focus();
    inputBox.value = fetchedValue;
}

However, on the login page, I have a dialog that displays the form fields. The extension is able to find the fields using the id and also able to insert the value. But even after that the form validation error for required condition is shown.
I tried to replicate the behaviour in angular using the below code:
$scope.user = {
    username: '',
    password: ''
};

$interval(function() {
    var inputBox = document.getElementById("username");
    console.log(inputBox);
    if (typeof inputBox !== "undefined" && inputBox !== null) {
        inputBox.click();
        inputBox.focus();
        inputBox.value = "test";
    }
}, 2000, 1);

The username field is bound to $scope.user.username but still upon insertion, the scope is not modified.
Here's the JSFiddle where the issue is replicated: https://jsfiddle.net/prerak6962/fxwmda5w/2/

A: Why not just:
$interval(function() {
            var inputBox = document.getElementById("username");
            console.log(inputBox);
            if (typeof inputBox !== "undefined" && inputBox !== null) {
                inputBox.focus();
                $scope.user.username = "test";
            }
        }, 2000, 1);

Angular do not watch values in inputs, instead it listen to DOM-events to track changes, when you change element content manually - angular will never know that something changed.
P.S. Angular is PLAIN JS. There is no 'magic'. For example, this strange code will work:
var user = {
            username: '',
            password: ''
        };
var rootScope;

(function() {
    'use strict';
    angular.module('chipsDemo', [])
        .controller('BasicDemoCtrl', DemoCtrl);

    function DemoCtrl($scope, $rootScope) {
        $scope.user = user;
        rootScope = $rootScope;
    }
})();

setInterval(function() {
  user.password = new Date().getTime();
  rootScope.$apply();
}, 1000);

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does [rm -rf /] do? This is basically recursively remove everything from root right?
Would this really delete everything on the device?
Do any operating systems have protections against running this – like a confirmation or something?
Seemed like a better idea to ask than to try.

A: The rm command means it is applied for removing file-folders based on the file path but as you have specified rm -rf / it tells to remove the files which are part of the root directory in the Linux or Unix based system, but again it will not do anything until and unless you apply the command with sudo access or super user do access with your system password.

A: Yes this would delete recursively.
Actually their is also a protection:

rm: it is dangerous to operate recursively on '/'
rm: use --no-preserve-root to override this failsafe

A: rm -rf is a dangerouse command in linux.if rm -rf run with root privilage it force to delete all files and folders even hidden file and you must install os again. this command has not confirmation question.
As a security measure, you can set rm to always get you approved for the delete operation, it uses the "-i" option whenever you want to delete a file or directory. To make this command permanent, add the following alias to the $ HOME / .bashrc file.
When you run the rm command, it will run with the "-i" option by default. (If you use the "-f" option, these settings will be overwrite)

A: rm -rf

this code deletes all files on linux (system ,root files include)
this is very dangerous code


text:
Q: Skein theory: How axiomatizing a 2-box space? Let $(A,+,\times, *)$ with an adjoint operation compatible with $+$, $\times$ and $*$, such that $(A,+,\times)$ and $(A,+,*)$ are finite dimensional ${\rm C}^{*}$-algebras.
What are the axioms on $A$ so that $(A,+,\times) \simeq P_{2,+}$, $(A,+,*) \simeq P_{2,-}$, with $P$ a subfactor planar algebra?
Remark: I expect axioms more simple than those of a subfactor planar algebra $P$ together with the assumption that $P$ is generated by its $2$-box space.


text:
Q: Azure subscription tied to a directory? I have a MSDN subscription from my work account, when I login, I can see there is already an azure active directory associated (which is company's one I have read only access). I need to provision another AAD directory for development purpose, however when I 'switch' the directory I can see it has no Azure subscription, which I need the credit for.
Question, how to change this behavior, I am thinking either a) change the default directory for my msdn subscription or b) transfer the subscription over to the new directory?
Please help!

A: Based on the current implementation, an Azure Subscription only trusts users from a single Azure AD.
From How Azure subscriptions are associated with Azure Active Directory:

Every Azure subscription has a trust relationship with an Azure AD
  instance. This means that it trusts that directory to authenticate
  users, services, and devices. Multiple subscriptions can trust the
  same directory, but a subscription trusts only one directory. You can
  see which directory is trusted by your subscription under the Settings
  tab. You can edit the subscription settings to change which directory
  it trusts.

To answer your questions specifically, please see this link on how you can change the trust relationship between an Azure AD and an Azure Subscription.


text:
Q: Create new Tooltip on not JavaFX Application Thread is there a way how to create javafx.scene.control.Tooltip in thread which is not "JavaFX Application Thread"?
Because of performance I prepare some visual elements in one thread and keep them in memory. And when I need them I use Application Thread for showing them. But new Tooltip() seems to require Application Thread only.

A:
is there a way how to create javafx.scene.control.Tooltip in thread which is not "JavaFX Application Thread"?

For JavaFX 2.2 - No.
See this JavaFX issue tracker tiecket: Tooltip of Tab (and other controls) cannot be set of FXApplicationThread.
There is a suggested workaround in the ticket to create the Tooltip in a Platform.runLater call.
package fxthread_25127_wrongthread;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;
/**
 *
 * @author mickf
 */
public class Main extends Application {
    Tooltip tooltip;

    public static void main(String[] args) {
        Application.launch(args);
    }
    @Override public void init() throws Exception {
        Platform.runLater(new Runnable() {
            @Override public void run() {
                tooltip = new Tooltip("Top tip : use runLater()");
            }
        });
        /*
         * this will cause an ISE
         */
        //tooltip = new Tooltip("flip");
    }
    @Override public void start(Stage s) {
        System.exit(0);
    }
}

A description of how Platform.runLater works from it's javadoc:

Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater.


text:
Q: Google Play Games Services with Unity3D, can we run/test game within editor? i'm trying to build a multiplayer game using GPGS in Unity. Been following this tutorial so far: https://github.com/playgameservices/play-games-plugin-for-unity/blob/master/README.md
Here's what i've done so far:
- Made a game service in my google account
- linked my game to the game service
- added the tester emails
- loaded the project 'Minimal' from the GitHub samples of GPGS for Unity in Unity editor
- configured my app id and package name
- setup the JAVA_HOME, Path variables as suggested in the github tutorial of GPGS Unity
Now when i click play in the editor and click Authenticate button, i get "authentication failed" message. But when i build the project for android and load the apk in my android device, i am able to authenticate (i can see the Google play signin page and go from there). Does this mean that we cannot develop/test a game inside the unity editor which uses the Google Play Game Services plugin for Unity? or am i missing something important here. I really would like to test my multiplayer game from within the editor or if possible on a real device. I've used Photon Pun in the past for another multiplayer but this time around the requirement is to use GPGS so i'm stuck here. I'm using the free version of Unity4.5.2f1
I'd appreciate any help in this! thanks

A: No, the PlayGamesServices plugin does not run in the editor. All instructions in the readme require you to build an apk or xcode build.
Source :

See Link


text:
Q: AWS loadbalancer per packet - only iptables? Need a design advice. Need to run in AWS loadbalancer per packet (not per flow).
It's for unidirectional UDP based streaming.
That means that each packet received by the loadbalancer should be send to another target - so that all targets receive the same amount of packets.
I do not see any ready solution and considering using EC2 with iptables and "-m statistic --mode random" PREROUTING chain. Any comments on the performance of that module at 1 up to 10Gbit/s scale ? (how strong EC2 instance would i need?)
Any other advices / hints how to achieve it ?
Thanks,

A: AWS Network Loadbalancer can be configured to send to "random" Targets in the TargetGroup, but this behaviour is not documented and just stated (to be exact, it's not defined how this distribution is done). It's the general ELB behaviour that targets are chosen by some hidden algorithm. Maybe it's worth an experiment? Make sure that Stickiness is turned off, as this is enabled the exact opposite of your use case.
I couldn't find a hard definition of how many GBit/s a NLB will support. But there is the concept of LCU (Load Balancer Capacity Units) that determines also billing and needs to be taken into account. LCUs are exposed in CloudWatch
Custom EC2 Instances will work and also cost a lot as CPU scales (roughly) with network. Here is a general list of EC2 Instances that you can filter for your network requirements and also see the pricing for it.
Maybe you should generally go for Devices with Enhanced Networking and Nitro, as later have special hardware for fast networking.


text:
Q: remove gtk2-packages on centos server I recently discovered that gtk2 is installed on my centos server.
because I only connect to the server through PuTTY it's a waste of disk space.
so i just wanted to know what packages should be removed.

A: GTK2 was installed as dependency of the development tools-group. Since I need the build-tools quite frequently I did not remove them.


text:
Q: C# Drag and Drop delete I was just wondering how I would go about Dragging an item from a list box and dropping it into an image that will then delete the value from the list box.
This is the code I have so far;
private void Form1_Load(object sender, EventArgs e)

{
textBox1.AllowDrop = true;
pictureBox1.AllowDrop = true;
}

private void listBox1_MouseDown(object sender, MouseEventArgs e)

{
if ( listBox1.Items.Count > 0 )
    listBox1.DoDragDrop(    /* ? */      , DragDropEffects.Move);    //This
statement is incomplete!
}

private void textBox1_DragEnter(object sender, DragEventArgs e)

{
e.Effect = DragDropEffects.Move;
}

private void textBox1_DragDrop(object sender, DragEventArgs e)

{
//Code to copy selected List Box entry to Text Box and remove original entry
}

private void pictureBox1_DragEnter(object sender, DragEventArgs e)

{
e.Effect = DragDropEffects.Move;
}

private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
//Code to remove selected entry from List Box
}

Any help will be appreciated,
Many thanks


text:
Q: Will adding salt to already boiling water made it stop boiling when under new boiling point elevation? There is a so common understanding (IMHO misunderstanding) that you don't add salt to water on the beginning but later to make cooking faster. Ignoring the fact that the difference of boiling points and time needed to reach that higher is very minimal I would like to approach this problem theoretically. So there are two cases - first one when salt is added before boiling - then the boiling point increases but with same ammount of energy it should't affect final time of boiling.
Regarding second case and following this example https://chem.libretexts.org/Courses/Valley_City_State_University/Chem_122/Chapter_3%3A_Solutions_and_Solubility/3.5%3A_Freezing_Point_Depression_and_Boiling_Point_Elevation
boiling point of water+salt is elevated from 100 to 101.78 by adding 10g NaCl to water, how about adding same amount of NaCl to already boiling water but when temperature is under 101.78 ?

A: Dissolving a solute in water raises its equilibrium boiling point.
(The reason is that impure water is less than 100% water, but the vapor phase above it is still 100% water. Since mass tends to move to areas of lower concentration—strictly, lower chemical potential, but this doesn't affect the reasoning here—the liquid phase is favored, so a higher temperature is required to reattain equilibrium with the gas phase.)
As you note, the boiling point elevation for a palatable amount of salt is minimal for cooking purposes but still detectable by a suitably sensitive thermometer.
One way to demonstrate the effect is to place the water (with inert boiling chips to ensure plenty of heterogeneous nucleation sites) in a container of controllable temperature; the water and surrounding air should be well stirred to ensure temperature uniformity. Upon boiling at slight overheating above 100°C, one adds salt that has been stored in the same container to avoid temperature differences. The boiling is then expected to stop, both because the dissolution of sodium chloride in water is endothermic and because the equilibrium boiling temperature is now higher. (A momentary froth of bubbles might be seen as the undissolved salt provides nucleation sites for pure-water boiling and as any attached air bubbles detach and float up.) The endothermic effect can be decoupled by bringing the solution to the original boiling temperature, where no boiling is expected. Boiling is expected to resume only upon additional heating to achieve slight overheating over the new equilibrium boiling temperature.
Does this get at what you're asking about?


text:
Q: why cannot add foreign key in mysql I have a table named "label" with 2 columns:
_LABEL_ID (varchar)
_LENGTH   (varchar)

This table already has data in it!
And I have several other Tables "a", "b", "c", etc.
these tables have the column _LABEL_ID (varchar). These table are not empty
On delete of any row from tables a, b, c, ...etc., then delete its label from the "label" table. I tried to add foreign key to "label" referenced to table "a" for doing this (just to test it), but getting the same error like in this question:
can't add foreign key in mysql?
In my case I have InnoDB engine for all tables, unique names FK's, same data types.
Now I exported label rows, then emptied the label table, adding foreign key to it referenced to "a" table  works just fine. If i import the rows again to the label table, I get the same error which I got when try to add foreign key.
the rows in label table belong to different tables (a, b, c, ..etc). is this the cause of the error?
i do this using MySQL Workbench
EDIT: the real SQL Statement and the Error Message:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
  ADD CONSTRAINT `fk_dbo_pub_label_treenode`
  FOREIGN KEY (`_LABEL_ID` )
  REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
  ON DELETE CASCADE
  ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC) ;

Error Message:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`cal_view_db`.`#sql-10cc_4a`, CONSTRAINT `fk_dbo_pub_label_treenode` FOREIGN KEY (`_LABEL_ID`) REFERENCES `dbo_system_treenode` (`_NAME_ID`) ON DELETE CASCADE ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
  ADD CONSTRAINT `fk_dbo_pub_label_treenode`
  FOREIGN KEY (`_LABEL_ID` )
  REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
  ON DELETE CASCADE
  ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC)

ERROR: Error when running failback script. Details follow.

ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `dbo_pub_label` (
  `_LABEL_ID` varchar(45) NOT NULL,
  `_LENGTH` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`_LABEL_ID`),
  KEY `fk_dbo_pub_label_1_idx` (`_LABEL_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

many thanks
p.s: sorry for my bad english!

A: Yes, it does seem that your problem is that the data in label belongs to multiple tables.
If I am not mistaken then a FK tells the DB to check in the referenced table for every value in the FK Table.
Here, you have labels from a and b and c and d. When the DB goes to verify the FK it will not find the data in label that corresponds to the data in b,c,d,etc. It will only find  the ones that are in a.
This is why your error comes up both when you try and create the table and when you try to reload the data to the table. All records in a FK column must have a match in the referenced table. (Here that is label -> FK -> a)


text:
Q: Object reference not set to an instance of an object textBox Hello i need a help with my code here
Im really confused about this error,  i want to pass the value from textBox1 (form 1) to textBox7 (form 2).
and it said NullReferenceException was unhandled
Form 1
private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            textBox1.Text = setIDtruk.getText;
            this.Close();
        }
        catch(Exception)
        {

            MessageBox.Show("Wrong");

        }
    }

Form 2
public string getText
    {

        get
        {
            return textBox7.Text; // error in this statement
        }

    }

can anybody help me out ?
thanks

A: If you get a NullReferenceException on the line you indicate then the only reason that I can see is that testBox7 is null.  We can't really tell you why it's null from the information that you've provided.

A: If it says NullReferenceException was unhandled it's probably because your TextBox7 is null.
You might need to go through your code and see where you missed a declaration.
If having a null TextBox is part of your code logic, in that case instead of returning the textBox7.Text directly, test it for null and if it is (null) return the appropriate value instead (like an empty string).


text:
Q: Satisfying the Definition of a Metric Let $S$ be any set. Let $X$ be the collection of all finite subsets of $S$. Show that
$d: X \times X \to [0,\infty), \quad (A,B) \mapsto |(A \setminus B) \cup (B \setminus A)|$ defines a metric on $X$.
My book gives the following definition of a metric in terms of a mapping.
A metric on a set $\Omega$ is a function $d: \Omega \times \Omega \to \mathbb{R}_+$ satisfying three properties:

*

*$d(f,g)=0$ if and only if $f=g$.

*$d(f,g) = d(g,f)$

*$d(f,g) \leq d(f,h) + d(h,g)$.

Here is what I have worked out:
$d(A,B) = |(A \setminus B) \cup (B \setminus A)| = 0 \Leftrightarrow A \setminus B = B \setminus A$. This means that $x \in A$ and $x \notin B$ or $x \in B$ and $ x \notin A$.
$d(A,B) = |(A \setminus B) \cup (B \setminus A)| = |(B \setminus A) \cup (A \setminus B)| = d(B,A).$
$d(A,B) = |(A \setminus C) \cup (C \setminus A)| + |(B \setminus C) \cup (C \setminus B)| = d(A,C) + d(C,B)$.
I do not think this is convincing enough and would like some feedback on how to properly show this is indeed a metric on $X$.
Thanks in advance.

A: $d(A,B)=0$:
Remember, you are trying to show that $A=B$. Your $\iff$ is false, and your concluded a different statement entirely.
Instead, observe that for a union of two sets to be empty, each of the sets has to be empty. Thus $A\setminus B=\varnothing$ and also $B\setminus A=\varnothing$. Hence $A\subset B$ and $B\subset A$, whereupon $A=B$ as desired.
$d(A,B)=d(B,A)$:
Your proof is fine.
$d(A,B)\leq d(A,C)+d(C,B)$:
This is actually the "meat" of what you're trying to prove. It is called the triangle inequality and is usually the hardest property of a metric space to check. In this case, you're going to need to do some set theory to show it. The key fact you will use is that $(B\setminus C)\cup (C\setminus A)=B\setminus A$.

A: Well,the first big problem with the first part of the "proof" is that you seem to assume what you're trying to prove. It assumes axiom (1) is true when that's what we're trying to show. Consider the union of the relative complements and d(A,B) =0. $|(A \setminus B) \cup (B \setminus A)| = 0$ implies $(A \setminus B) \cup (B \setminus A)$ = $\emptyset$
Consider $(A \setminus B) \cup (B \setminus A)$ refers to the union of the set of all elements that is in B,but not in A and the set of all elements in A.but not in B. Therefore the set is asking for the set of all elements which is both in A and B and not in A or B. Clearly, such as set is empty! More importantly, this is a set where the complements of each A and B with respect to the other set are the same set. This can only be if A=B.
Since the unions are symmetric-it doesn't matter what order you write the sets in-the second part of your proof is fine.
The third part is the triangle inequality and it's going to a little tricky to prove. The key fact you're going to need from set theory is the following: $(B \setminus C) \cup (C \setminus A) = B \setminus A$ . The proof will be somewhat tedious, but it's worth doing in detail.
Good luck!


text:
Q: read character array with cin.get I try to write a program that get max to 20 characters and index them as character array then print out the array. The program compiles but the output are random words and symbols in place of the variable. Any idea why?
# include <iostream>

using namespace std;

int main ()
{
const int MAX = 20;
char str[MAX];
int index = 0;

while (index < MAX -1 &&
        (str[index++]==cin.get()) != '\n');

str[index]='\0';

cout<<"What i typed is _"<<str<<endl;

return 0;
}

A: The condition un the while statement is invalid. There is a typo
while (index < MAX -1 &&
        (str[index++]==cin.get()) != '\n');
                     ^^^

Write
while (index < MAX -1 &&
        (str[index++] = cin.get()) != '\n');

Take into account that the new line character '\n' can be stored in the result string.


text:
Q: React router v4 replace param with  My DashBoard component renders a shared component called PostComments that renders a list wrapped with <Link/>, When a list is click the page navigates to Profile component and on this component i also have the PostCOmments
Now, if i click one of the list on my Profile component the url param just stacks up Like this, http://localhost:8080/#/dashboard/5b6c5223514959110c492086/49182d98319138e31da42356
<Link replace to={`${match.url}/${i.comment_from._id}`}>
     <div className="comment-user-image" style={{backgroundImage: `url(${i.comment_from.photo_url})`}}>
     </div>
</Link>

A: You'll need to manually replace the last part of your url because you re-use it.
const splitUrl = match.url.split('/'); // Split into array
splitUrl.splice(-1, 1, i.comment_from_id); // Replace the last part with the new id
return (
  <Link replace to={splitUrl.join('/')}> // Recreate the correct url
  // ...


text:
Q: You get 5 prizes by picking random boxes one at a time, without replacement. Find the PMF of how much your most valuable prize is worth. This is Blitzstein's Introduction to Probability (2019 2 ed) Ch 3, Exercise 8, p 141.

There are 100 prizes, with one worth $1, one worth $2, . . . , and one worth $100. There are 100 boxes, each of which contains one of the prizes. You get 5 prizes by picking random boxes one at a time, without replacement. Find the PMF of how much your most valuable prize is worth (as a simple expression in terms of binomial coefficients).

From my point of view the probability is equal to:
$P(X=k)$=$\binom{5}{1}$/$\binom{100}{5}$ for $k=1,2,...100$.
Because there are in total $C(100,5)$ ways of choosing the box and $C(5,1)$ of choosing the most valuable prize. What's wrong with my reasoning?

A: You are searching for probability that $k$ is the most valuable prize you chose. That is probability that all prizes you chose are less valuable than $k+1$ and that you chose $k$, which means that not all prizes are less than $k$.
Denote by $Y_i$ event that all 5 prizes you chose are less than $i$.
Then:
$$P(Y_i)=\frac{i \choose 5}{100 \choose 5}$$
and:
$$P(X=k)=P(Y_{k+1}\cap \neg Y_k)=P(Y_{k+1})-P(Y_{k+1} \cap Y_k)=P(Y_{k+1})-P(Y_k)=\frac{{{k}\choose{5}}-{{k-1}\choose{5}}}{{100}\choose{5}}$$


text:
Q: Responsive global font size on Foundation 6 The global font size in foundation-6 is 16px and can be altered in _settings.scss. Is there a way to make this size varies depending on the screen width? I want to decrease this size to 13px for small screens. I know there is something like that for the headers but I am asking here for the global size. Thank you!

A: I would probably look to add a set of media queries to your app.scss file to set the font size for each breakpoint. This make sense?

A: I would do something like this (feel free to use Foundation's function to convert the value in px to rem or em):
body{
 font-size:13px;
 @include breakpoint(medium) {
   font-size:$global-font-size;
 }
}


text:
Q: iOS static library for ad hoc distribution I have 2 separate iOS projects in xcode 4. One is APP which is main application, and in second project I have static library LIB, that is used in APP.
No I am preparing Ad Hoc distribution of my APP. I wondering how I supposed to compile LIB, to use it in my APP ad hoc version. Should I use Product->Archive and then Share my static library and use it in APP, or I need just normal build for iOS Device?

A: A static library is not signed (never is), hence no need to setup any specific in its compile settings on that end  -  in other words, no need to select a specific signing identity or even add Entitlements.
When building a static library for distribution, you may however make sure it is compiled in release-mode to remove possibly unwanted debugging code. To achieve that, you may build any scheme that is not bound to your debug configuration. That would, by default be the "Profile" or "Archive" scheme.


text:
Q: Apply Formatting to TotalsRow using EPPlus Using EPPlus I can create the XSLX file and I can apply formatting to the data, but if I use a TotalsRow function, like SUM, then the formatting is not applied.
Does anyone know how to apply that formatting?
Update:
To load the data into a sheet and get the table I do the following (dtMain being a DataTable):
FileInfo newFile = new FileInfo(@"C:\Temp.xslx");

using (ExcelPackage package = new ExcelPackage(newFile))
{
    //Create the Worksheet
    var sheet = package.Workbook.Worksheets.Add("Sheet1");
    //Read the table into a sheet
    var range = sheet.Cells["A1"].LoadFromDataTable(dtMain, true);

    sheet.Tables.Add(range, "data");
    //Now format the table...
    var tbl = sheet.Tables[0];
    tbl.ShowTotal = true;

    //create a custom style
    string stylename = "StyleName";
    var style = package.Workbook.Styles.CreateNamedStyle(stylename);

    tbl.Columns[SomeName].TotalsRowFunction = RowFunctions.Sum;

    style.Style.Numberformat.Format = "#,###.00";

    //assign the style to the column
    tbl.Columns[SomeName].DataCellStyleName = stylename;
}

range.AutoFitColumns();

// save our new workbook and we are done!
package.Save();

A: When you say "TotalsRow" do you mean a SUM column at the end of a row?  If so, you might be mixing up terms since the TotalsRow refers to a row at the BOTTOM of the table.  In order to show it you have to set ShowTotal to true as well.
If you actually want to sum up the columns into the last column you should apply a formula.
See if this helps:
[TestMethod]
public void TotalRows_Format_Test()
{
    //Throw in some data
    const string SomeName = "Totals";
    var dtMain = new DataTable("tblData");
    dtMain.Columns.Add(new DataColumn("Col1", typeof(int)));
    dtMain.Columns.Add(new DataColumn("Col2", typeof(int)));
    dtMain.Columns.Add(new DataColumn("Col3", typeof(int)));
    dtMain.Columns.Add(new DataColumn(SomeName, typeof(int)));

    for (var i = 0; i < 20; i++)
    {
        var row = dtMain.NewRow();
        row["Col1"] = i;
        row["Col2"] = i * 10;
        row["Col3"] = i * 100;
        dtMain.Rows.Add(row);
    }

    FileInfo newFile = new FileInfo(@"C:\Temp\Temp.xlsx");
    if (newFile.Exists)
        newFile.Delete();

    using (ExcelPackage package = new ExcelPackage(newFile))
    {
        //Create the Worksheet
        var sheet = package.Workbook.Worksheets.Add("Sheet1");
        //Read the table into a sheet
        var range = sheet.Cells["A1"].LoadFromDataTable(dtMain, true);

        sheet.Tables.Add(range, "data");
        //Now format the table...
        var tbl = sheet.Tables[0];

        //create a custom style
        string stylename = "StyleName";
        var style = package.Workbook.Styles.CreateNamedStyle(stylename);

        //Add formula for row total in COLUMN
        for (var i = 2; i <= dtMain.Rows.Count + 1; i++)
            sheet.Cells[i, 4].Formula = String.Format("SUM(A{0}:C{0})", i);

        //The totals row at the BOTTOM of the table
        tbl.Columns[SomeName].TotalsRowFunction = RowFunctions.Sum;
        tbl.ShowTotal = true;

        style.Style.Numberformat.Format = "#,###.00";

        //assign the style to the column
        tbl.Columns[SomeName].DataCellStyleName = stylename;

    range.AutoFitColumns();

    // save our new workbook and we are done!
    package.Save();
    }
}

UPDATE (in response to comments)
I see what you mean now.  How about this:
tbl.TotalsRowCellStyle = stylename;

A: Add this to the code:
sheet.Cells[sheet.Dimension.End.Row, colcount].Style.Numberformat.Format = c.Format;
Full version:
FileInfo newFile = new FileInfo(@"C:\Temp.xslx");

using (ExcelPackage package = new ExcelPackage(newFile))
{
    //Create the Worksheet
    var sheet = package.Workbook.Worksheets.Add("Sheet1");
    //Read the table into a sheet
    var range = sheet.Cells["A1"].LoadFromDataTable(dtMain, true);

    sheet.Tables.Add(range, "data");
    //Now format the table...
    var tbl = sheet.Tables[0];
    tbl.ShowTotal = true;

    //create a custom style
    string stylename = "StyleName";
    var style = package.Workbook.Styles.CreateNamedStyle(stylename);

    tbl.Columns[SomeName].TotalsRowFunction = RowFunctions.Sum;

    style.Style.Numberformat.Format = "#,###.00";
    //apply style to totals row
    sheet.Cells[sheet.Dimension.End.Row, colcount].Style.Numberformat.Format = c.Format;

    //assign the style to the column
    tbl.Columns[SomeName].DataCellStyleName = stylename;
}

range.AutoFitColumns();

// save our new workbook and we are done!
package.Save();


text:
Q: Unable to access storage in Android Q Although having read and write permissions I am unable to access sdcard in Android 10. This was my approach to list all directory.
        File root = new File("/mnt/sdcard/");

        File[] subFiles = root.listFiles();

        for(File file : subFiles)    {
            if(file.isDirectory())  {
                String str = text.getText().toString() + "\n";
                str+=file.getAbsolutePath();
                text.setText(str);
            }
        }

If I use /mnt/ instead of /mnt/sdcard/ I can see sdcard directory is listed in there but when I use /mnt/sdcard/ , subFiles is null. I don't know if this is something regarding new android 10 version or it is a problem with emulator. I was using android studio's default emulator for debuging.

A:
This is a temporary solution. From Android 11 Scoped Storage have to be used.

The problem was requestLegacyExternalStorage was not set to true in the manifest file. Because of scoped access on external storage by default it is set to false in Android 10 or higher. Adding this line in the AndroidManifest.xml solved my problem.
<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
  <application
       android:requestLegacyExternalStorage="true" ........ >
    ......
  </application>
</manifest>


text:
Q: How to watch around 100 folders in parallel? FileSystemWatcher or other more efficient options?
*

*I have a base folder under a drive Data and under this I have around 100 folders.

*

*In each folder Folder1.....100, one of the 3rd part application pushing zip file (zip contains 1 or more files).

*I have to write a window service which will watch all 100 folders for file arrival.

*Once file is available I need to extract the zip file and placing all the extracted files into a second folder and this I need to do for each folder (Folder 1 .. 100) as soon as files available.

*Below code suggest me that through C# FileSystemWatcher, I can watch one folder at a time and act on that.
Question is, how to do watch for 100 folders in parallel?
 class ExampleAttributesChangedFiringTwice
{
    public ExampleAttributesChangedFiringTwice(string demoFolderPath)
    {
        var watcher = new FileSystemWatcher()
        {
            Path = demoFolderPath,
            NotifyFilter = NotifyFilters.LastWrite,
            Filter = "*.txt"
        };

        watcher.Changed += OnChanged;
        watcher.EnableRaisingEvents = true;
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // extract zip file, do the validation, copy file into other destination
    }
}

The target folder, is it the same folder regardless of the source folder of the zip? That is, it doesn't matter if it's from Folder1 or Folder2, both will be extracted to FolderX?
Target folder is common for all "C:\ExtractedData".
So every folder under Data will be watched? No "blacklisted" folder? What about if a zip appears in Data itself instead of its subfolder? What if a new subfolder is created, should it be watched too?
"zip" always comes inside "subfolders", it will never create inside Data folder.
Yes, there is a chance in future, more subfolders will come and need watch.
And does the extracted files goes into a separate subfolder inside the target folder based on their zip filename, or do they just get extracted on the target folder, eg, if it's A.zip, does the content goes to Target\A or just Target.
For example, if A.zip contains 2 files, "1.txt" and "2.txt", then both files goes to "C:\ExtractedData". This will be common for each zip files arrives at different subfolders.

A: The "100 folders in parallel" part turn out to be a red herring. Since all the new zip files are treated the same regardless of where they show up, just adding IncludeSubdirectories=true is enough. Note the following codes are prone to exceptions, read the comments
class WatchAndExtract
{
    string inputPath, targetPath;
    public WatchAndExtract(string inputPath, string targetPath)
    {
        this.inputPath = inputPath;
        this.targetPath = targetPath;
        var watcher = new FileSystemWatcher()
        {
            Path = inputPath,
            NotifyFilter = NotifyFilters.FileName,
            //add other filters if your 3rd party app don't immediately copy a new file, but instead create and write
            Filter = "*.zip",
            IncludeSubdirectories = true
        };
        watcher.Created += OnCreated; //use Changed if the file isn't immediately copied
        watcher.EnableRaisingEvents = true;
    }

    private void OnCreated(object source, FileSystemEventArgs e)
    {
        //add filters if you're using Changed instead
        //https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
        ZipFile.OpenRead(e.FullPath).ExtractToDirectory(targetPath);
        //this will throw exception if the zip file is being written.
        //Catch and add delay before retry, or watch for LastWrite event that already passed for a few seconds
    }
}

If it skipped some files, you either have too many files created at once and/or too big zip to process. Either increase the buffer size or start them in new thread. On HDD with busy IO or extremely large zip files, the events might exceed the storage capability and skipped files after a prolonged busy period, you'll have to consider writing to a different physical (not just a different partition in the same device) drive instead. Always verify with your predicted usage pattern.


text:
Q: WPF and Powershell - Handling events Can anyone point me in the right direction for some documentation about handling WPF UI events in Powershell?
I want to know how to, for example, call a function when a CheckBox or Radio Button is changed.
Cheers!
Ben

A: Considering WPF and PowerShell, have a look at WPF Linkcollection for PowerShell from Bernd. You will find many interesting links that will help you.
Considering your problem, just use pattern
$control.Add_<someevent>({ what to do })

For example, someevent could be Click for a Button:
$button.Add_Click({ $global:clicked = $true })

You pass in a scriptblock that handles the event.

A: Late to the party (by over 4 years). Specifically addressing jpierson's comment.
But in case anyone finds this post, as I did, via Googling PowerShell WPF event handling, wanting to obtain the Sender control (sender) & Event Args (e), here's how...
C# version (non-specific template)
private void Handler(object sender, SomeEventArgs e)
{
  //do something with sender and/or e...
}

PowerShell version
$WPFControl.Add_Handler({
  $sender = $args[0]
  $e      = $args[1]
  #do something with sender and/or e...
})

And onto a specific MouseWheelHandler event handler
C# version (where the MouseWheelHandler event has been bound to a control)
private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
  ScrollViewer scv = (ScrollViewer)sender;
  //do something with sender and/or e...
}

PowerShell version
$ScrollViewer.Add_PreviewMouseWheel({
  $sender = [System.Windows.Controls.ScrollViewer]$args[0]
  $e      = [System.Windows.Input.MouseWheelEventArgs]$args[1]
  #do something with sender and/or e...
})

In PowerShell, to get the types of sender and event args, use the following
$ScrollViewer.Add_PreviewMouseWheel({
  Write-Host $args[0]
  Write-Host $args[1]
})

which (in the above example) will give you...
System.Windows.Controls.ScrollViewer
System.Windows.Input.MouseWheelEventArgs

A: ok, it's a long shot because this post is from 2015, but i tried and it's not working for me.
It doesn't rise an error but i don't have access to sender properties
Get-Variable -Name Ctrl_* -ValueOnly | Where-Object {$_.Name -match '^btn_[^_]+_Nav_(Previous|Next)$'} | ForEach-Object {
    $_.Add_Click({
        $sender = [System.Windows.Controls.Button]$args[0]
        $sender.Name
    })
}

I try to make a generic navigation system for an hmi
Best Regards,
Richard


text:
Q: can't ping with one iface after bonding Since i've bonded (active-backup) eth0 & wlan0 on debian stretch i'm no able to ping a specific device on my LAN with ETH0 anymore.
Every device in my LAN is able to ping in both ways
Problem persist even after changing IP address of the device
All protocols affected (not only ICMP)
Works perfectly with WLAN0
Allows all incoming/outgoing connections with IPTables
Targeted device IP is 192.168.1.XX
/etc/network/interfaces

auto lo
iface lo inet loopback

auto eth0
allow-hotplug eth0
iface eth0 inet manual
    bond-master     bond0
    bond-mode       active-backup

auto wlan0
allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
    bond-master     bond0
    bond-mode       active-backup

auto bond0
iface bond0 inet static
    address 192.168.1.39
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.1.255
    gateway 192.168.1.254
    dns-nameservers 9.9.9.9 192.168.1.254
    bond-mode active-backup
    bond-miimon 200
    bond-downdelay 200
    bond-updelay 200
    bond-slaves none
    bond-primary eth0
    bond-fail_over_mac none
    hw-address b8:27:eb:ff:12:34

route
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         192.168.1.254   0.0.0.0         UG    0      0        0 bond0
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 bond0

A: Changing bonding mode to load-balancing "fixed" the issue.


text:
Q: In mysql how do I find rows repeating with respect to all fields? +------------+------------+
| student    | department |
+------------+------------+
| 1234567890 | CS         |
| 1234567890 | ME         |
| 1234567890 | CS         |
| 000000001  | ME         |
+------------+------------+

How can I get rows that are repeating with respect to both fields?
Thanks in advance.

A: It should be something like
SELECT  student,
    department
FROM    Table
GROUP BY student, department
HAVING COUNT(*) > 1

A: SELECT student, department, count(*) as 'count'
FROM students
GROUP BY student, department
HAVING count > 1

+------------+------------+-------+
| student    | department | count |
+------------+------------+-------+
| 1234567890 | CS         | 2     |
+------------+------------+-------+

A: SELECT *
FROM mytable
GROUP BY student, department
HAVING COUNT( * ) > 1;


text:
Q: Getting 'this.model is undefined' after event in Backbone app only in Firefox I'm trying to get my head around Backbone and it's concepts. I've made a simple app so that I can learn how to learn more about Backbone.Router and how to integrate Backbone with Require.js.
The app works great in Chrome, IE9 and Safari, however in the latest version of Firefox it throws a "TypeError: this.model is undefined" error after the click event is triggered and consumed. Thanks very much for any help!
I've attached a link to the entire app below for convenience.
https://dl.dropbox.com/u/19138757/Backbone_Example.zip
I'll comment on the method where the error is occuring:
document.js
    define([
        'jquery',
        'underscore',
        'backbone',
        'app'
    ], function ($, _, Backbone, app) {

        var DocumentListView = Backbone.View.extend({
            tagName: 'li',

            events: {
                'click': function () {
                    app.aggregator.trigger('document:selected', this.model);
                }
            },

            render: function () {
                this.$el.html(this.model.get('title'));
                return this;
            }
        });

        return DocumentListView;

    });

documents.js
    define([
        'jquery',
        'underscore',
        'backbone',
        'data/documents',
        'app',
        'text!templates/documents.html'
    ], function ($, _, Backbone, documents, app, documentTemplate) {

        app.aggregator.on('document:selected', function (document) {

            var urlPath = 'view/' + document.get('title');

            app.router.navigate(urlPath, { trigger: true });

        });

        DocumentView = Backbone.View.extend({
            el: $('#my-container'),

            template: _.template(documentTemplate),

            events: {
                'click h1': 'sayHello'
            },

            // This is the method where the error is occuring.
            // this.model is undefined...but ONLY in Firefox
            render: function () {
                this.$el.empty().append(this.template(this.model.toJSON()));
                return this;
            },

            sayHello: function () {
                this.input = this.$('.message');
                alert(this.input.val());
            }

        });

        return DocumentView;

    });

router.js
        define([
        'jquery',
        'underscore',
        'backbone',
        'data/documents',
        'views/contents',
        'views/document'

    ], function( $, _, Backbone, documents, ContentsView, DocumentView ){

        var DocumentRouter = Backbone.Router.extend({
            routes: {
                'contents': 'contents',
                'view/:title': 'viewDocument'
            },

            contents: function(){
                $('body').html(new ContentsView({collection: documents}).render().el);
            },

            viewDocument: function(title){

                //get a single document instance by title and then pass into DocumentView
                var selectedDocument = _(documents).find(function(document){
                    return document.get('title') === title;
                });

                $('body').empty().append(new DocumentView({model: selectedDocument}).render().el);
            }
        });

        return DocumentRouter;

    });

A: Your problem is related to how different browsers handle spaces in the URL. Change your viewDocument function inside router.js to the following:
    viewDocument: function(title){
        // ADD THIS LINE
        title = decodeURIComponent(title);

        //get a single document instance by title and then pass into DocumentView
        var selectedDocument = _(documents).find(function(document){
            return document.get('title') === title;
        });

        $('body').empty().append(new DocumentView({model: selectedDocument}).render().el);
    }


text:
Q: Reducing noise in AC clamp meter
I am currently using one of these AC clamp meters to read an 25Hz square wave signal along a wire attached to a wall. Unfortunately, there seems to be a lot of noise of other frequencies around this wire. I want to somehow attach a low pass filter to this AC clamp. Is that possible?

A: To reduce the impact of high frequencies simply place a capacitor between the positive and negative terminal of the AC clamp.


text:
Q: Nonconvergent convolution integral I have a convolution integral where $F(\tau) = F_0$ and $g(t - \tau) = \sin(\omega_n(t-\tau))$ so
$$
F_0\int_{t_0}^{\infty}\sin(\omega_n(t-\tau))d\tau
$$
which doesn't converge.  Can I do the following:
$$
Im\Bigg\{F_0\int_{t_0}^{\infty}e^{i\omega_n(t - \tau)}d\tau\Bigg\} =
Im\bigg\{\frac{e^{i\omega_n(t-\tau)}}{-i\omega_n}\bigg|_{t_0}^{\infty}\bigg\} = \frac{-\cos(\omega_n(t-t_0))}{\omega_n}
$$

A: i would suggest to add a small imaginary part like
$e^{i((\omega_n +i \delta)(t-\tau))}$ and take the limit of the $\delta->0$ in the end. This has the advantage that your integral converges for every finite delta and you don't have to deal with expressions like $e^{i\infty}$ which are not well defined. The price you pay is that your integral is still divergent in the above limit and has to be interpreted in the sense of distributions.
So:
\begin{align}
\Im \left[\lim_{\delta \rightarrow0}\int_{t_0}^{\infty} dt e^{i((\omega_n +i \delta)(t-\tau))}\right]=\Im \left(i\lim_{\delta \rightarrow0}\left[e^{-i((\omega_n +i \delta)(t_0-\tau)}\frac{1}{\omega_n+i\delta}\right]\right)
\end{align}
using Euler's identity and $\lim_{\delta \rightarrow0}\frac{1}{\omega_n+i\delta}=-i\pi \delta(\omega_n)+P\frac{1}{\omega_n}$. See here.
you should arrive at a result. Please note that $P$ denotes the Cauchy principal value and $\delta(x)$ is Dirac's Delta function.
Can you take it from here?
Edit:
I think the final result will be the one you posted, but this time well justified :)


text:
Q: MX Backup service What suppliers can you recommend, that provide an MX backup service?

A: it used to be the case that having a backup MX was a Good Thing.  the internet was unreliable, email was unreliable, smtp was not so common, bang-path addressing and other forms of manually-specified mail routing was common, and uucp was the mail protocol of choice.
That was a long, long time ago.  It's not true today.  sending MTAs will queue up undelivered mail and keep on trying to deliver it for several days (default is usually 4 or 5 days), so if your mail server is down or unreachable for a few days, your mail will eventually get delivered to you.
Today, except in very specialised circumstances, you do not need a backup MX and, in fact, it will cause you far more problems than you imagine that it might solve (in reality it solves almost no problems).
Unless your backup MX has a list of valid recipients for the domain(s) that it is supposed to receive mail for, it WILL instantly become a source of back-scatter (spam bounces to forged sender addresses).  it will also be a potential route for spam to bypass some of your spam filters (because you necessarily trust your MX more than you trust random smtp servers on the net).  Many spammers still target backup MX machines in preference to primary MXs for this reason (and also because secondary MXs often have weaker anti-spam filters).
NOTE: when i write "spam", i mean spam AND viruses.  from my POV, they're the same thing and are generally sent by the same scumbags anyway (most viruses are spambots of one kind or another).
1st Rule of thumb: unless you know exactly why you need a backup MX and exactly what problems it may cause and exactly how you're going to prevent them, then DO NOT HAVE A BACKUP MX.
2nd Rule of thumb: unless you have complete control over the backup MX and can ensure that it has an up-to-date list of valid recipients, and roughly equivalent spam-filters as your primary MX, DO NOT HAVE A BACKUP MX.
3rd Rule of Thumb: see Rules 1 & 2.  If in doubt, DO NOT HAVE A BACKUP MX.
starting to see the pattern?
BTW, you can take advantage of spammers targetting secondary MXs.  e.g. i block a lot of spam by running a bogus least-priority MX that responds with 450 tempfail to every delivery attempt.  many spambots target that and don't even try the primary MX, so the load on my real mail servers is greatly reduced.  Legitimate senders never try it because my mail servers are always on (and if by some chance they aren't, the sender gets a 450 temporary failure code and tries again later)


text:
Q: Difficulty with tile background for a windows phone 7 app I am trying to set a background for my app's tile using these instructions. However, it still shows the default spiky circle image. (I think it's "ApplicationIcon.png".)
Here is my WMAppManifest.xml:
<Tokens>
  <PrimaryToken TokenID="MyAppToken" TaskName="_default">
    <TemplateType5>
      <BackgroundImageURI IsRelative="true" IsResource="false">s.png</BackgroundImageURI>
      <Count>0</Count>
      <Title>My App Title</Title>
    </TemplateType5>
  </PrimaryToken>
</Tokens>

What could I be doing wrong? s.png is set to build action "Content".

A: There are two icon files. They default to ApplicationIcon.png and Background.png
ApplicationIcon is 62x62, can't be transparent and is used it the list view of applications.
Background, which is what you are setting here should be 173x173, can be transparent, and it used when you pin the application to the start screen.
So my first suggestion would be to check you are actually setting the image you think you are and are looking at the start screen not the list view.
My second would be to check the image sizes are correct. I do not know what the phone does if they are not.
My third would be to check the image you are referencing is in the top level of the project, not in a folder, and is actually making it into your xap. Go into the bin\debug or bin\release then open the .xap file with a zip client and make sure it is there.

A: Sometimes WP7 seems to cache the old image - so my advice would be:

*

*if you are using the phone, then remove your app (using press and hold to bring up the menu)

*if you are using the emulator, then reboot it to ensure the app is completely removed


text:
Q: Rebuilt index remains fragmented When the rebuild  script has run I still have a fair share of index fragmented. It is very hard to find any information on this.
I have done a lot of testing and I think I have two issues.
Rebuild does not work well on tables heavily used in DDL/DML operations. It works 90% better on a disconnected database.
Can this be addressed without a service window?
I think the remaining 10% is due to fragmentation on disk level.
Should I separate the SQL application logs (error logs etc) from the data files? I can't find any info on this due to the 10 000 hits on trans logs.
My provider puts the data files on the main instance disk (separate from tempdb, trans & OS)

A: be as it it may with disk level fragmentation, it can't be addressed on a SSD SAN.
The best solution I can find is to only include index_level=0. This is what Hallengren's script does and I guess that is good enough for me then.
        SELECT
            CASE WHEN MAX(ps.avg_fragmentation_in_percent) > 30 THEN
                'ALTER INDEX [' + i.name + '] ON [' + sc.NAME + '].[' + so.NAME + '] REBUILD  With (maxdop = 1);'
            ELSE
                'ALTER INDEX [' + i.name + '] ON [' + sc.NAME + '].[' + so.NAME + '] REORGANIZE ;'
            END AS [query], max( ps.avg_fragmentation_in_percent)
        FROM
            sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'DETAILED') AS ps
            INNER JOIN sys.indexes i
                ON ps.OBJECT_ID = i.OBJECT_ID
                    AND ps.index_id = i.index_id
                    AND ps.database_id = DB_ID()
                    AND i.name is not NULL
                    AND ps.avg_fragmentation_in_percent > 5 -- min % to return
                    AND ps.page_count > 1000 -- otherwise table is to smal.
                    AND ps.index_level = 0
            INNER JOIN sys.objects so
                ON i.OBJECT_ID = so.OBJECT_ID
            INNER JOIN sys.schemas sc
                ON sc.SCHEMA_ID = so.SCHEMA_ID
        GROUP BY sc.NAME, so.NAME, ps.index_id, i.name
        ORDER BY sc.NAME, so.NAME, ps.index_id DESC;


text:
Q: Template argument deduction in partial specialization #include <iostream>

using namespace std;

template <typename T> class A{
public:
    void test() { cout << "normal" << endl;}

};

//template <typename T> class A<T&>{
//public:
//    void test() { cout << "&" << endl;}

//};

template <typename T> class A<T&&>{
public:
    void test() { cout << "&&" << endl;}

};

int main(){
    A<int&> a;
    a.test();
}

The output is normal suggesting the ordinary (non-specialised) template was chosen. This may be seem obvious straight away since int & is supplied as a template argument and the only available specialisation is one that takes an rvalue reference. But why is it that the second template specialisation cannot be selected by choosing T = int& in which case reference collapsing causes T&& to become int&?


text:
Q: Trying to get property of non-object (View: /var/sites/b/domain.com/app/views/viewbuild.blade.php) trying to move my site to my live host and cant figure this error out. I have been updating all table and column names etc but cant get my head around this error. Doesnt give much information (to me).
The complete error is:
Trying to get property of non-object (View: /var/sites/b/domain.com/app/views/viewbuild.blade.php)

Open: /var/sites/b/domain.com/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php
    // an exception is thrown. This prevents any partial views from leaking.
    try
    {
        include $__path;
    }
    catch (\Exception $e)
    {
        $this->handleViewException($e, $obLevel);
    }

The route for this URL is so:
Route::get('viewbuild/{build_id?}/{build_title?}', function($build_id = null, $build_title = null)
{
  $build = Blog::find($build_id);
  if (!is_null($build)) {
    return View::make('viewbuild', compact('build'));
  } else {
    return "Build does not exist";
  }
});

Thanks for any help.


text:
Q: Make a WPF ListBox comma separate values I have a ListBox that looks like this:
<ListBox ItemsSource="{Binding Fruits}">
    <!--Make the items wrap-->
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel></WrapPanel>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name, StringFormat=' {0},'}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This gives me a list like this:

Oranges, Grapes, Bananas,

But what I want is:

Oranges, Grapes, Bananas

(no trailing comma)
Any one have an idea on how to remove the trailing comma?

A: This can be achieved using IValueConverter to determine whether its last item in a listBox and there by updating StringFormat on your binding using data trigger in XAML.
Create a converter to determine if value is last item in listbox -
public class IsLastItemInContainerConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                          CultureInfo culture)
    {
        DependencyObject item = (DependencyObject)value;
        ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);

        return ic.ItemContainerGenerator.IndexFromContainer(item) ==
                                                        ic.Items.Count - 1;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Now modify your XAML and add trigger on DataTemplate to remove comma from StringFormat on your TextBlock -
<ListBox ItemsSource="{Binding Fruits}">
   <ListBox.Resources>
      <local:IsLastItemInContainerConverter
             x:Key="IsLastItemInContainerConverter"/>
   </ListBox.Resources>
   <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
         <WrapPanel/>
      </ItemsPanelTemplate>
   </ListBox.ItemsPanel>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock x:Name="textBlock"
                    Text="{Binding Name, StringFormat=' {0},'}" />
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource
                                               Mode=FindAncestor,
                                               AncestorType=ListBoxItem},
                                               Converter={StaticResource IsLastItemInContainerConverter}}"
                             Value="True">
                    <Setter Property="Text" TargetName="textBlock"
                            Value="{Binding Name, StringFormat=' {0}'}"/>
                 </DataTrigger>
            </DataTemplate.Triggers>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

A: If you refactor your code, you can make a string that has your desired result very easily:
string.Join(", ", Fruits) // e.g. Oranges, Grapes, Bananas

E.g. you could have:
// on your binding object
public string FruitString { get { return string.Join(", ", Fruits); } }
// in your XAML
<TextBlock Text="{Binding FruitString}" />

(or, if the Fruits property was of a class you defined, you could override its ToString(), which would be a good place to put the Join code)


text: Q: Can't manage cookies in custom 404 or 500 actions I've got custom 404 and 500 pages set up for my app via routing of '400' and '500'. There is a certain before filter that runs before them and also a couple of other actions. I've noticed that when before filter runs before those actions, it can delete cookies, but not if the action is 404 or 500 action. I've experimented and put cookie deleting code into the actions themselves, rather than in the filter, but the same thing happens. Any ideas?


text:
Q: tiinymce dropdown item cashes polymer dialog when clicked I am using tinymce wysiwyg html editor and polymer. The editor is shown in a paper-dialog popup. When an item in a tinymce dropdown menu is clicked, the dialog closes and it will not reopen. No errors appear in console. How can I catch the click events to stop it from affecting the polymer dialog?
I tried adding a stopPropogation in the tinymce setup field but that doesn't seem to help.
    tinymce.init({
      selector: '#' + this.textareaId,
      setup: function (ed) {
            ed.on('click', function(e) {
              console.log("clicked");
              e.preventDefault();
              e.stopPropagation();
            });
        }
    });
  },

A: Just came across the same problem. It looks like paper-dialog thinks that when you select certain items from TinyMCE drop-down menu, the click happens outside of paper-dialog, so it decides it needs to close.
The quick workaround here would be to set no-cancel-on-outside-click property for dialog (or make it modal). More involved solution would require capturing all click events on TinyMCE element, which I haven't attempted.


text:
Q: Find longest sequence of characters in stack Hi I was solving a problem:

Given a base-10 integer, n, convert it to binary (base-2). Then find and
  print the base-10 integer denoting the maximum number of consecutive 1's
  in n's binary representation. For e.g. for n=5, base-2 = 101 so the output should be 1, for n = 439, base-2 = 110110111 so the output should be 3.

Below is my code solution for the same:
class Solution {

    static int CalcBinary (int n) {
        Stack<int> binRep = new Stack<int>();
        while (n > 0) {
            int i = n%2;
            binRep.Push (i);
            n = n/2;
        }
        int oldCount = 0, newCount = 0;
        while (binRep.Count > 0){
            int val = binRep.Pop();
            if (val == 1) {
                newCount++;
            } else {
                if (newCount > oldCount) {
                    oldCount = newCount;
                }
                newCount = 0;
            }
        }
        return (newCount > oldCount) ? newCount : oldCount;
    }

    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine (CalcBinary(n));
    }
}

The code runs fine and passes all the test cases like for n = 5, 6, 439, etc. Only question I have is that if there is any optimized solution to do the same. Someone else has posted the same question here, but all the replies to that question seem to be same with O(n) time complexity. Another thing is I can use array instead of Stack, but would it make any difference??

A: public int CalcBinary(int n)
{
    int result = 0;
    int current = 0;
    for (int i = 0; i + result < 32 && (n >> i) != 0; i++)
    {
        if (((n >> i) & 1) == 1)
            current += 1;
        else
        {
            if (current > result)
                result = current;
            current = 0;
        }
    }

    return result == 0 ? current : result;
}

I'm not so good at big O arithmetic, but I think this solution should be faster since I don't use any other classes but simple bit shifting.
And I stop early if there is no longer solution possible (i + result < 32).
Note that this is only for 32bit integers. For 64bit adjust the mentioned condition. And it works only for positive values (a set sign bit can produce wrong results for example for 111....111101).

Update: added the (n >> i) != 0 condition as suggested by @Scott-Chamberlain (it checks if there are still 1s to come at all).

A: Why don't you calculate maximum_consecutive while converting binary instead of waiting convert done, then calculate maximum_consecutive again from the stack ?
I think you should change to this.
class Solution {

static int CalcBinary (int n) {
    int oldCount = 0, newCount = 0;
    while (n > 0) {
        int i = n%2;
        n = n/2;

        if (i == 1) {
            newCount++;
        }
        else {
            if (newCount > oldCount) {
                oldCount = newCount;
            }
            newCount = 0;
        }

    }
    return (newCount > oldCount) ? newCount : oldCount;
}

static void Main(String[] args) {
    int n = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine (CalcBinary(n));
}
}

A: For bit-fiddling fun and minimal branching:
int[] lookup = new[]
{
  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
int LongestRunOfBits(uint value)
{
    int max = 0;
    while(1 << max < value + 1)
    {
        uint testValue = ~value;
        uint lookupIndex = ((uint)((testValue & -testValue) * 0x077CB531U)) >> 27;
        int trailingZeros = lookup[lookupIndex];
        max = trailingZeros - ((trailingZeros - max) & ((trailingZeros - max) >> 31));
        value >>= 1;
    }
    return max;
}

This combines the following operations:
Compute the maximum of two integers without branching (QuAD version)
Count the consecutive zero bits (trailing) on the right with multiply and lookup (if it counts trailing zero bits on value, then it counts trailing one bits on ~value)
Let's follow this through for value 6, or 110:
Now we have:

             value : 00000000000000000000000000000110
            ~value : 11111111111111111111111111111001
trailing zero bits : 0
   value after rsh : 00000000000000000000000000000011
            ~value : 11111111111111111111111111111100
trailing zero bits : 2
   value after rsh : 00000000000000000000000000000001 //skip this last iteration
            ~value : 11111111111111111111111111111110 //as it will now be impossible
trailing zero bits : 1                                //to find a value > 2

by finding the maximum number of trailing zero bits of ~value we are effectively finding the maximum number of trailing one bits for value. If we carry on right shifting until there are no more bits left, the longest run of set bits is the maximum value of the trailing zero bits operation we performed over ~value. Hooray. Once we've found the value 2 and there are 2 or less bits remaining in the value, we can bail early as we can be sure no larger value than 2 can be found, so the last iteration can be skipped.


text:
Q: Highcharts logarithmic Y-axis exceeding set max I know this has been asked here a lot and there are already answers to this question both here and in the API Reference. However, none of the solutions have solved my issue.
I am attempting to set the max on the y-axis to 490, but am consistently having it max at 1k. So far I have tried setting the max, setting alignTicks to false, setting the endOnTick to false, setting the tickInterval, and setting the minRange.
yAxis: {
        type: 'logarithmic',
        minorTickInterval: 'auto',
        title: {
            text: 'Amounts'
        },
        max: 490,
        alignTicks: false,
        endOntick: false
    }

fiddle
At this point I'm at a complete loss. My sincere apologies if this has already been answered, I have yet to find any that has worked in this specific instance.
Quick unrelated question: Has anybody made a series span all columns horizontally? Any suggestions on better ways to do this than what I presently have would be greatly appreciated. Thanks all!

A: You should use endOnTick not enOntick. However, setting endOnTick to false means you will not receive last label/tick (well, just like the name of options says ;) ).
In that case, use tickPositioner, for example: http://jsfiddle.net/x0bj2rjn/9/
    yAxis: {
        type: 'logarithmic',
        minorTickInterval: 'auto',
        title: {
            text: 'Amounts'
        },
        max: 490,
        alignTicks: false,
        endOnTick: false,
        tickPositioner: function (min, max) {
                this.tickPositions.push(max);
            return this.tickPositions;
        }
    },


text:
Q: Are Containers and Kubernetes IaaS or PaaS? Since we don't need to configure most of the Infrastructure services for Containers and Kubernetes, still we have ability to manage different Infrastructure services.
Does this make them Infrastructure as a Service or Platform as a Service?

A: kubernetes is considered PaaS when the control plane components: the scheduler, the API server, ETCD (key-value metadata)and controller are managed by the provider
some examples are Microsoft  AKS, Google GKE, AWS EKS.
It is considered IaaS if you built and maintain all the components

A: Kubernetes is neither IaaS nor PaaS. It's a container orchestration engine which makes it more like a Container As A Service or CaaS.
You need a IaaS layer below kubernetes to provide it VMs like for example AWS EC2 or bare metal servers.
Kubernetes can be used as a platform for building Platform As a Service on top of it and CloudFoundry on Kubernetes is an example of a PaaS built on kubernetes.

A: I have to dissent a bit with the answer here above.
All technical definitions are quite meticolous, but are often a model to explain what's in place, and so they can change over time or overlap a bit.
A couple of years ago there was no "Container as a Service" or "CaaS" whatsoever. Container platforms, were just called "PaaS", or "Platform as a Service".
At some point "PaaS" became ambiguous because there were many platforms usable by developers that fit "PaaS" definition: amongst these PaaS techonolgies, some were in turn running on Kubernetes platform, which was also defined as PaaS.
Somebody felt the need to distinguish the two concepts in order to better communicate with developers if they had to choose between a more abstract platform, or to directly rely upon container orchestration (most widespread Kubernetes).
So, distinction between PaaS and CaaS was introduced.
This is how it happened that in previous definition Kubernetes and container orchestration in general were defined simply as "PaaS". And nowadays they are called "CaaS".
Instead Infrastructure as a Service, or simply "IaaS", is the infrastructure layer upon which Kubernetes runs: namely the virtual machine instances into which the Kubernetes nodes are implemented, the network connectivity part, and other basic elements.
Beware: happens that these definitions are used in a different manner over time by VENDORS, that tend to mix a bit of commercial pushing (i.e. towards a new product) into what is presented just as a technical overview article. Don't be fooled! ;-)


text:
Q: How to restart failed Chunks - Spring batch I am writing Spring batch for chunk processing.
I have Single Job and Single Step. Within that Step I have Chunks which are dynamically sized.

SingleJob -> SingleStep -> chunk_1..chunk_2..chunk_3...so on

Following is a case I am trying to implement,
If Today I ran a Job and only chunk_2 failed and rest of chunks ran successfully. Now Tomorrow I want to run/restart ONLY failed chunks i.e. in this case chunk_2. (I don't want to run whole Job/Step/Other successfully completed Chunks)
I see Spring batch allow to store metadata and using that it helps to restart Jobs. but I did not get if it is possible to restart specific chunk as discuss above.
Am I missing any concept or if it is possible then any pseudo code/theoretical explanation or reference will help.
I appreciate your response

A: That's how Spring Batch works in a restart scenario, it will continue where it left off in the previous failed run.
So in your example, if the in the first run chunk1 has been correctly processed and chunk2 failed, the next job execution will restart at chunk2.


text:
Q: mvn dependency:tree does not list dependencies of a dependency I have a project that has a dependency, say X.jar, which has its own dependency Y.jar. When I include X.jar as a dependency in my project I expect that all the dependencies of X.jar be available to me in my project.
Indeed this is the case with other dependencies. When I run mvn dependency:tree it lists dependencies and their dependencies as expected but it fails to list any dependencies for X.jar.
X.jar is a custom jar from a project I wrote (I have indeed added X.jar to the local repo) so perhaps the problem lies there. When I run mvn dependency:tree on the X project it lists all dependencies correctly.
I have no idea how to debug this and any help would be appreciated.

A: The problem is probably that the pom.xml of your X.jar is not properly installed in your repository.
When you install a jar "by hand" in your repo :use the option -DpomFile="<path_to_your_pom>" .
If you don't do that : maven will create (and install !!!)  an ultra-simple pom.xml for you (and of course it don't contains any data about dependencies).
More about installing a custom jar here


text:
Q: How to Pass List values as parameters in SQL Java I have one sql query (Copying values from one table to another table in same database ) where it takes multiple values as parameters and values are from list.
Below is which I have tried.Though I am not getting any error, but its not working.I want to insert values into database
    List EmployeeIDList= new ArrayList(Arrays.asList(123,823,456,890));
    List SalaryList= new ArrayList(Arrays.asList(14437,14297,13846,13441));
con1=DriverManager.getConnection(URL1,DB_UserName,DB_Password);
log.info("Data base connection is established");
for (int i=0,j=0;i<EmployeeIDList.size();i++,j++) {
    stmt = con1.prepareStatement("Insert INTO Employee(Name, Year, EmployeeID, Tax, Salary)
            Select Name, Year, EmployeeID, Tax, Salary
             (Employee

                       when EmployeeID= ? then ?   // 1st ? = EmployeeID,2nd ? = Salary
                       when EmployeeID = ? then ?
                       when EmployeeID = ? then ?
                       else ?  // ? = Salary
                       end ) as Employee
                "From Employee2 +
                "Where EmployeeIDin (?)");

        stmt.setInt(1,SalaryList.get(j));
        stmt.setInt(2,EmployeeIDList.get(i));
        System.out.println("first salry is " +SalaryList.get(j))    ;
        System.out.println("first Employeeid is " +EmployeeIDList.get(i))   ;
        rs = stmt.execute();

When I execute "select * from Employee " in sql ,its not returning any values.
Note:If I execute above Insert query in sql,it works fine.Only through java I am not able to insert the values.

A: please try these code
String query = " Insert INTO Employee(Name, Year, EmployeeID, Tax, Salary)"
        + " values (?, ?, ?, ?, ?)";
and then apply select query

A: I have got the solution.There was wrong in Numbering the position in setInt.Thank you everyone


text:
Q: website not displaying at all, only in chrome I have just moved my site to a friend's server, he has taken care of everything and the website looks great in all browsers according to him.
But he is in Spain, where i used to be too, but now im in India, and here the website does not display at all when i use chrome, it just shows a white screen. However, if i browse the source code, it shows correctly. In IE and FF it displays just fine.
UPDATE: the error is Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
And a related question can be found here: net::ERR_INCOMPLETE_CHUNKED_ENCODING in Chrome only
What could be causing this strange behaviour?
This is the site, http://culturadigital.cc
UPDATE 2: if i comment out this line FallbackResource /es/index.php in my .htaccess file it works again, but i need this line!


text:
Q: How to process a vintage/retro filter on image by API I am trying to apply image filtering to images, like retro/vintage/B&W, etc.
Is there any ready-to-use libraries implementing image filtering that I could use? My app will be a web-app so maybe a PHP or javascript lib/API ?
I already ran into http://pixlr.com/ but they just give the opportunity to use their image editor, and no image processing script that could be automated. Geez!
Thanks for your answers ;)

A: http://camanjs.com is a js lib that can manipulate image on client side


text:
Q: Show active navigation for current page with php I'm trying to use use $current_url = basename($_SERVER['PHP_SELF']); to determine which page I am on, considering my navigation (html) is stored in a php file and is included in every page. This is the code I use to determine which navigation option should be active:
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/no-background.css">

<?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active\"";
?>
<?php if ($current_url == "globaluser.php") { ?>
    <li <?php echo $active;?> > <?php } ?> <a href="globaluser.php?Agent=<?php echo $Agent;?>">Overview

<?php if ($current_url == "search.php") { ?>
    <li <?php echo $active;?> > <?php } ?> <a href="search.php?Agent=<?php echo $Agent?>">Add new client

<?php if ($current_url == "viewadmins.php") { ?>
    <li <?php echo $active;?> > <?php } ?> <a href="viewadmins.php?Agent=<?php echo $Agent?>">View admins

<a href="emails.php?Agent=<?php echo $Agent?>">E-mails

<?php echo $Agent?>

<a href="earnings.php?Agent=<?php echo $Agent?>">Earnings

Change Password

                        <form action="changepass.php?Agent=<?php echo $Agent?>" method="POST">
                            <input type="password" name="1" placeholder="Enter new password">
                            <input type="password" name="2" placeholder="Repeat new password">

                            <input type="submit" name="changepw" class="button" value="Change">
                        </form>

            <form action="logout.php">
                <input type="submit" class="button" value="Log out">
            </form>

But it doesn't work. It shows the active page as active, however, it shows 2 pages as simple hyperlinks. This is what it looks like:

Does anyone have any clue as to why this happens? It works for 2 but fails for 2, exact same code?
Thanks

A: You should do it like this:
<li <?php echo ($current_url == "globaluser.php") ? $active : ''?> ><a href="globaluser.php?Agent=<?php echo $Agent;?>">Overview

because right now you're conditioning the presence of the opening
 tag

A: You are using <?php } ?> at wrong place.
It should be after
<a href="search.php?Agent=<?php echo $Agent?>">Add new client

Updated code is as follows:
   <link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/no-background.css">

<?php
    $current_url = basename($_SERVER['PHP_SELF']);
    echo $current_url;
    $active = "class=\"active\"";
?>
<?php if ($current_url == "globaluser.php") { ?>
    <li <?php echo $active;?> > <?php } ?> <a href="globaluser.php?Agent=<?php echo $Agent;?>">Overview

<?php if ($current_url == "search.php") { ?>
    <li <?php echo $active;?> > <a href="search.php?Agent=<?php echo $Agent?>">Add new client
 <?php } ?>
<?php if ($current_url == "viewadmins.php") { ?>
    <li <?php echo $active;?> >  <a href="viewadmins.php?Agent=<?php echo $Agent?>">View admins
<?php } ?>

<a href="emails.php?Agent=<?php echo $Agent?>">E-mails

<?php echo $Agent?>

<a href="earnings.php?Agent=<?php echo $Agent?>">Earnings

Change Password

                        <form action="changepass.php?Agent=<?php echo $Agent?>" method="POST">
                            <input type="password" name="1" placeholder="Enter new password">
                            <input type="password" name="2" placeholder="Repeat new password">

                            <input type="submit" name="changepw" class="button" value="Change">
                        </form>

                <form action="logout.php">
                <input type="submit" class="button" value="Log out">
                </form>

A: You could also use preg_replace() to add class="active"
ob_start();
echo '

Page 1

Page 2

';
$output = ob_get_clean();
$pattern = '~
~';
$replacement = '
';
echo preg_replace($pattern, $replacement, $output);


text:
Q: SQL Tree Structure I am new to this topic (i.e tree structure) in SQL. I have gone through different sources but still not clear.
Here in my case, I have a table which I have attached herewith.

Now here first, I have to retrieve a Full Tree for "OFFICE".
Also i have to find all the leaf nodes (those with no Children) in the attached hierarchical data.
Please provide the answers with detail explanation.
Thanks in advance.

A: You didn't specify your DBMS but with standard SQL (supported by all modern DBMS) you can easily do a recursive query to get the full tree:
with recursive full_tree as (
  select id, name, parent, 1 as level
  from departments
  where parent is null
  union all
  select c.id, c.name, c.parent, p.level + 1
  from departments c
    join full_tree p on c.parent = p.id
)
select *
from full_tree;

If you need a sub-tree, just change the starting condition in the common table expression. To get e.g. all "categories":
with recursive all_categories as (
  select id, name, parent, 1 as level
  from departments
  where id = 2 --- << start with a different node
  union all
  select c.id, c.name, c.parent, p.level + 1
  from departments c
    join all_categories p on c.parent = p.id
)
select *
from all_categories;

Getting all leafs is straightforward: it's all nodes where their ID does not appear as a parent:
select *
from departments
where id not in (select parent
                 from departments
                 where parent is not null);

SQLFiddle example: http://sqlfiddle.com/#!15/414c9/1

Edit after DBMS has been specified.
Oracle does support recursive CTEs (although you need 11.2.x for that) you just need to leave out the keyword recursive. But you can also use the CONNECT BY operator:
select id, name, parent, level
from departments
start with parent is null
connect by prior id = parent;

select id, name, parent, level
from departments
start with id = 2
connect by prior id = parent;

SQLFiddle for Oracle: http://sqlfiddle.com/#!4/6774ee/3
See the manual for details: https://docs.oracle.com/database/121/SQLRF/queries003.htm#i2053935

A:
Now here first, I have to retrieve a Full Tree for "OFFICE".

How do you want to represent your tree? What you have posted can already count as a tree.

Also I have to find all the leaf nodes (those with no Children) in the attached hierarchical data.

TSQL:
select *
from table outer
where id not in (select id
                 from table inner
                 where inner.parent = outer.id)

The inner select will give you all ids pointing to a certain parent. The outer select will give you all nodes for which the inner select yields no results.

A: There is a pattern design called "hardcoded trees" that can be usefull for this purpose.

Then you can use this query for finding a parent for each child
SELECT level1ID FROM Level2entity as L2 WHERE level2ID = :aLevel2ID

Or this one for finding the children for each parent:
SELECT level1ID FROM Level2entity as L2 WHERE level2ID = :aLevel2ID

A: If you can afford a little bit of pre-processing time, then a classic solution to this problem would be to use nested sets.
CREATE TABLE node (
    id INTEGER NOT NULL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    parent_id INTEGER DEFAULT NULL,
    seq_min INTEGER NOT NULL,
    seq_max INTEGER NOT NULL
);

Assuming, that you use some kind of in-memory data structure like
class Node:
   def __init__(self, id, name, children=()):
      self.id = id
      self.name = name
      self.children = list(children)

to represent the tree nodes in memory, we can then define
def assign_sequence_numbers(root_node):
    def recurse(counter, node):
        node.seq_min = counter
        node.seq_max = reduce(recurse, node.children, 1 + counter)
        return node.seq_max
    return recurse(1, root_node)

which does a pre-order traversal over the tree, which assignes two additional numbers to each node:
The seq_min value becomes an alternate unique integer key for each node. Also, all direct children (and indirect descendants) of a node will have a seq_min value, which is larger than the value assigned to the node itself.
The seq_max value is simply an upper boundary for the seq_min values of all descendant nodes.
Example: Consider the following tree
Root
 |
 +--- Category1
 |      |
 |      +--- Category1.1
 |      |
 |      `--- Category1.2
 |
 `--- Category2

Using the function defined above, we get
Root [min=1, max=6]
 |
 +--- Category1 [min=2, max=5]
 |      |
 |      +--- Category1.1 [min=3, max=4]
 |      |
 |      `--- Category1.2 [min=4, max=5]
 |
 `--- Category2 [min=5, max=6]

Observe, that for every node, the min value is always <= the min value of all descendants and the max value is always  > the max value of all descendants. So, to find the descendants of Root and that node itself (i.e., get the entire tree), we'd do:
SELECT * FROM node
WHERE seq_min >= 1 /* i.e., seq_min(Root) */
AND seq_min < 6    /* i.e., seq_max(Root) */

To get the descendants of Category1 (and that node itself)
SELECT * FROM node
WHERE seq_min >= 2 /* i.e., seq_min(Category1) */
AND seq_min < 5    /* i.e., seq_max(Category2) */

The drawback of this method is, that in principle, you will have to re-assign the seq_xxx numbers for all nodes, if you make changes to the tree, i.e., insert new nodes or delete old ones. This is often not a problem, at least if changes to the tree structure are infrequent and the tree is sufficiently small.
As ITGenius already linked to that answer: if your database supports it, using common table expressions is another possibility, which avoids the pre-processing step and is also more resilient in the face of changes to the tree structure.
(I did not test any of the code given in this answer. You might need to apply a few fixes here and there; in particular, if your project's language of choice is not python...)


text:
Q: DRMAA and the shared.library.path I try to use the sun grid engine with the DRMAA api by following the tutorial found at: http://gridscheduler.sourceforge.net/howto/drmaa_java.html. For this I need to load the c library located in /srv/sge/lib/lx24-amd64/drmaa.so. Now I execute my command with this code: java -jar scriptName.jar -Dshared.library.path=/srv/sge/lib/lx24-amd64/ as described in https://blogs.oracle.com/templedf/entry/drmaa_and_the_shared_library. But still I get the this exception:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no drmaa in
  java.library.path

This exception is thrown when trying to retrieve the session:
session = SessionFactory.getFactory().getSession();
OS is linux 64 bit, java is 64 bit and SGE is 64 bit, so this is all compatible.
Does anyone know what is going wrong?

A: You will want to change shared.library.path to java.library.path (I believe that is a mistake in the blog post you referenced.
Also, place the -D switch before the -jar switch in your command, otherwise it is interpreted as an argument to the main function in the jar file rather than an argument to the JVM.
So, your example command should now look like this:
java -Djava.library.path=/srv/sge/lib/lx24-amd64/ -jar scriptName.jar

A: The case seems to be that in some distributions the libdrmaa.so has a library version number libdrmaa.so.1.0 while the libdrmaa.so without version number is missing. The drmaa.jar seems to just look for the one without. You can check which of the libdrmaa.so libraries are available in your system using
# ldconfig -p | grep libdrmaa

Which (in my case) either says
libdrmaa.so.1.0 (libc6,x86-64) => /lib64/libdrmaa.so.1.0

or
libdrmaa.so.1.0 (libc6,x86-64) => /lib64/libdrmaa.so.1.0
libdrmaa.so (libc6,x86-64) => /lib64/libdrmaa.so

The second case is the good one!
For Fedora distributions I reported this as a bug and it seems that they fix it in F18 and F19 soon. https://bugzilla.redhat.com/show_bug.cgi?id=671880
It is an easy fix in Fedora to simply install the package "gridengine-devel" where this soft-link is included.
If the libdrmaa.so without version number is not there and you are on another distribution, you can fix it manually as system administrator by typing
# cd /usr/lib64
# sudo ln -sf libdrmaa.so.1.0 libdrmaa.so
# sudo ldconfig

A: None of the previous answers worked for me. I've managed to solve this problem defining in my environment the following variable
export LD_LIBRARY_PATH=<path to the drmaa lib>


text:
Q: IntelliSense suggest only one option In VsCode, whenever I try to use IntelliSense at the end of:

*

*an object to see its methods,

*an structure to see its components or

*a path to see its directories,

IntelliSense only suggests me one result at a time, so I have to hit ↑ and ↓ to navigate through the results until I eventually find what I was looking for.

This is quite not ideal... Is there a way to configure VsCode so that it pops a tap with all options, instead of one at a time?
Thanks!

A: It might be you just need to resize it with the new resize ability.
https://code.visualstudio.com/updates/v1_51#_resizable-suggestions


text:
Q: How to configure many to many relationship using entity framework fluent API I'm trying to set up a many to many relationship in EF code first but the default conventions is getting it wrong.  The following classes describes the relationship:
class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Account
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

One Account can have many Products.
However the EF conventions will create the DB tables as:
Products Table
--------------
Id
Name
Account_Id  <- What is this?

Accounts Table
--------------
Id
Name

This doesn't look like a many-to-many table structure?  How can i get configure the fluent API to reflect the relationship and create an intermediary table:
AccountProducts Table
---------------------
Account_Id
Product_Id

A: What EF has suggested is a one-to-many relationship.
One Account can have many Products, i.e. each Product has an Account_Id
If you want a many to many relationship (and create an intermediary table), the following should work
class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Account> Accounts { get; set; }
}

class Account
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

A: modelBuilder.Entity<Account>()
            .HasMany(a => a.Products)
            .WithMany()
            .Map(x =>
            {
                x.MapLeftKey("Account_Id");
                x.MapRightKey("Product_Id");
                x.ToTable("AccountProducts");
            });

A: Code first is creating tables in right relational way. When

One Account can have many Products.

Products table should store key for its Account, as it actually does now.
What you are trying to see in db, is many-to-many relationship, not one to many. If you want to achieve that with code first, you should redesign your entities
class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Account> Accounts { get; set; }
}

class Account
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

In this case, one product can have many accounts, and one account can have many products.

A:         public AccountProductsMap()
    {
        this.ToTable("AccountProducts");
        this.HasKey(cr => cr.Id);

        this.HasMany(cr => cr.Account)
            .WithMany(c => c.Products)
            .Map(m => m.ToTable("AccountProducts_Mapping"));
    }


text:
Q: Hasse diagram of finite linearly ordered set What form does the Hasse diagram of a finite linearly ordered set take?
I think the linearly order set is nothing but totally ordered set which usually takes lattice form since every element is comparable. However am confused if it is the same or something different. My textbook says it takes linear path form.

A: Your textbook is correct. Linearly ordered set and totally ordered set are the same thing. If a linearly ordered set has $n$ elements, its Hasse diagram is a vertical path with $n$ nodes and $n-1$ edges. For $n=5$, for instance, it looks like this:
                     *
                     |
                     *
                     |
                     *
                     |
                     *
                     |
                     *

The set $\{0,1,2,3,4\}$ with the usual linear order $\le$ is an example of a linearly ordered set for which this is the Hasse diagram. Another example is the set
$$\big\{\varnothing,\{0\},\{0,1\},\{0,1,2\},\{0,1,2,3\}\big\}$$
with the linear order $\subseteq$.


text:
Q: Local property of dimension Let $R$ be a commutative ring with unity. If the Krull dimensions of all the localizations $S^{-1}R$ are zero, where $S$ runs among multiplicative subsets of $R$, is it true that the Krull dimension of $R$ is zero?
If the dimension of a given localization is zero is that of $R$ zero?
For $S$ a multiplicative subset of $R$, it is known that $\dim S^{-1}R \le \dim R$, therefore if the right hand side is zero so is the other side.
Thanks for any suggestion!

A: A chain of prime ideals $p_0\subset p_1\subset\dots \subset p_d$ induces a chain of the same length in $S^{-1}R$ if and only if $S\subset R-p_d$. Therefore, if $R$ is of finite dimension, then $\mathrm{dim}(S^{-1}R)=\mathrm{dim}(R)$ if and only if there is a maximal ideal $m\subset R$ of maximal height such that $S\subset R- m$. In particular, we can just take $S=R-m$.
Thus, there is a non-trivial localisation $S^{-1}R\not= R$ of the same (finite) dimension if and only if $R$ is not local. Namely, if $m$ is any prime ideal of maximal height, then $S:=R-m$ will do the job, whilst it can't consist of units only since otherwise $m$ would be local.
To address the two questions directly:

*

*If $S^{-1}R$ has dimension zero for all multiplicative $S\subset R$, then $R$ has dimension zero too, for the trivial reason that we can take $S=\{1\}$. If we want a non-trivial localisation with this property, we have to assume that $R$ is not local.

*Does $\mathrm{dim}(S^{-1}R)=0$ for some $S$ imply that $\mathrm{dim}(R)=0$? No! Take $S:=R-p$ for any minimal prime. Then $\mathrm{dim}(S^{-1}R)=0$, no matter what the dimension of $R$ is.

A: Yes, it is true since $\{1\}$ is a multiplicative subset and the localization of $R$ by $\{1\}$ is $R$.


text:
Q: Python Script for percent change in NPP ( Net Primary Production) Can you suggest a python script for percent change raster from "begin year"(Inras1) to "end year" (Inras2) Vegetation Net Primary Production rasters? Example: That is a given raster cell increased by 25% compared to "begin year"
`

A:  # Name: Minus_Ex_02.py
 # Description: Modification of ESRI's Subtracts the value of the second                      input raster from the Value of the first input raster on a cell-by-cell basis
  # Requirements: Spatial Analyst Extension
  # Author: ESRI

  # Import system modules
  import arcpy
  from arcpy import env
  from arcpy.sa import *

  # Set environment settings
  env.workspace = "C:/Users/Kaleab/Desktop/MOD17A3/Mosaic/Clip"

  # Set local variables
  inRaster1 = "2000clip.tif"
  inRaster2 = "2010clip.tif"

  # Check out the ArcGIS Spatial Analyst extension license
  arcpy.CheckOutExtension("Spatial")

 # Execute Minus
 outMinus = Minus(inRaster1, inRaster2)
 changeras = outMinus/inRaster1
 # Save the output
 changeras.save("C:/Users/Kaleab/Desktop/MOD17A3/Mosaic/Clip/Change.tif")