text:
Q: How to raise a textbox TextChangedEvent programmatically I'm using .net 4.5, in a WPF project. I would like to raise a TextBox TextChangedEvent. This is what I have done so:
tb.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent));

I've done the same sort of RaiseEvent on a Button.ClickEvent before, how can I do this one?
this produces an error as follows:

Exception:Thrown: "Object of type 'System.Windows.RoutedEventArgs'
  cannot be converted to type
  'System.Windows.Controls.TextChangedEventArgs'."
  (System.ArgumentException) A System.ArgumentException was thrown:
  "Object of type 'System.Windows.RoutedEventArgs' cannot be converted
  to type 'System.Windows.Controls.TextChangedEventArgs'."

[EDIT]
The actual textbox text changed is handled by an attached behavior as follows. The place where I want to programmatically raise the event is in another control's attached behavior. In the later behavior I do have the textbox object.
public class textboxTextChangedBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.TextChanged += OnTextChanged;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.TextChanged -= OnTextChanged;
        base.OnDetaching();
    }

    private void OnTextChanged(object sender, TextChangedEventArgs args)
    {
        var textBox = (sender as TextBox);
        if (textBox != null)
        {
            //Populate ObservableCollection
        }
    }
}

Place where I try to raise the event:
public class FindPopupBehavior : Behavior<Popup>
{
    protected override void OnAttached()
    {
        AssociatedObject.Opened += _OpenFindPopup;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Opened -= _OpenFindPopup;
    }

    void _OpenFindPopup(object sender, EventArgs e)
    {
        //Fake a TextBox text changed event
        if (TextBoxObject == null)
            return;

        TextBox tb = TextBoxObject as TextBox;

        if (tb.Text == "")
            return;

        tb.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent));
    }

    public static readonly DependencyProperty TextBoxProperty =
        DependencyProperty.Register("TextBoxObject", typeof(TextBox), typeof(FindPopupBehavior), new UIPropertyMetadata(null));

    public object TextBoxObject
    {
        get { return (object)GetValue(TextBoxProperty); }
        set { SetValue(TextBoxProperty, value); }
    }
}

[EDIT2]
The textbox resides in a popup upon this popup closing an ObservableCollection is cleared, the textbox text remains, although hidden. If the popup is reopened and the textbox has text it needs to repopulate the ObservableCollection. It does this population in the textchanged behavior. This is why I was thinking to fake an event.

A: Manually raising .NET events is unadvisable, even if for no other reason than it is unrequired. Think about it... you don't really want to raise an event. You're not seeking the functionality of the event, so why raise it?
If I understand your situation correctly, then surely, what you actually want to do is to execute a particular section of your code. As such, your problem is caused because that section of code is currently encapsulated within an event handler. However, that doesn't mean that you have to raise that event to execute that code.
Instead, just simply move the relevant code into a method, which you can call from the event handler and from wherever else you want and all without unnecessarily raising any events:
private void OnTextChanged(object sender, TextChangedEventArgs args)
{
    var textBox = (sender as TextBox);
    if (textBox != null)
    {
        PopulateObservableCollection();
    }
}

private void PopulateObservableCollection()
{
    // Populate ObservableCollection
}

If you particularly need to access the TextBox, then please describe your situation further... there is always a way.

UPDATE >>>
Think about this logically... you want to call this method and you need access to the TextBox in the Popup and you need to do it each time the Popup is opened. So why not just handle the Popup.Opened Event?:
private void PopupOpened(object sender, EventArgs e)
{
    // Check TextBox and Populate ObservableCollection
}

A: You can raise event manully like
    MouseButtonEventArgs args = new MouseButtonEventArgs(Mouse.PrimaryDevice,100, MouseButton.Left);
    args.RoutedEvent = UIElement.PreviewMouseLeftButtonUpEvent;
    tb.RaiseEvent(args);

A: One way is that you can do like this..
   EventName.Raise(this, new EventArgs());

A: Why don't you call the method of the event directly?
I have created a small sample application for you:
It does the following:

*

*I have a button and a textbox. On the textbox is a OnTextChanged event, and I want when I click on the button, to execute that textbox event.

First, your WPF application, that in my case, contains just a grid with in it a textbox and a button.
<Grid>
    <TextBox Name="txtTextBox"></TextBox>
    <Button Name="btnDemo" Content="Click me"></Button>
</Grid>

I know that layout wise, this is rubbish, but it's just for demonstrating.
In your code behind, you need to do a few things:
Add an event handler for the button and for the textbox:
public MainWindow()
{
    InitializeComponent();

    btnDemo.Click += BtnDemoOnClick;
    txtTextBox.TextChanged += TxtTextBoxOnTextChanged;
}

Here's the code for your TxtTextBoxOnTextChanged event:
private void TxtTextBoxOnTextChanged(object sender, TextChangedEventArgs textChangedEventArgs)
{
    MessageBox.Show("The textbox event has been fired.");
}

As you see, this just shows an message box.
And then the event of your button:
private void BtnDemoOnClick(object sender, RoutedEventArgs routedEventArgs)
{
    TxtTextBoxOnTextChanged(this, new TextChangedEventArgs(routedEventArgs.RoutedEvent, UndoAction.None));
}

I hope it helped.

A: this could end in an stackoverflow because if recall the Event for your object it will again be catched by your textboxTextChangedBehavior
so instead of creating a loop you can simple change your
private void OnTextChanged(object sender, TextChangedEventArgs args)
    {
        var textBox = (sender as TextBox);
        if (textBox != null)
        {}
    }

to
private void OnTextChanged(object sender, TextChangedEventArgs args)
    {
        var textBox = (sender as TextBox);
        if (textBox != null)
        {}

        // now your textboxTextChangedBehavior does't block your event
        args.Handled = false;
    }

[EDIT]
mhh maybe the problem is more how you try to achieve your goal.
but if i understand you correctly your popup Opened and you try to raise the TextChanged, right?
so you could set the Text in your _OpenFindPopup (add an # or what ever) which will raise your TextChanged and now you can remove the # and populate your ObservableCollection


text:
Q: how to read hindi text from Ms Access database in java using JDBC? I am creating an java application which is used to read Hindi Data from ms access Database.
please suggest me how to read Hindi text in java from ms access database.
code :
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+db_path+";";  // setup the properties
            java.util.Properties prop = new java.util.Properties();
            prop.put("charSet", "UTF-8");
            prop.put("user", "");
            prop.put("password", "");

        Connection conn = DriverManager.getConnection(database, prop);

A: Java's JDBC-ODBC Bridge and the Access ODBC driver will not be able to retrieve the Unicode (Hindi) text from the database. However, the UCanAccess JDBC driver can do it. See:
Manipulating an Access database from Java without ODBC

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript onclick using a class instead of inline I am trying to figure out how to do an onclick event using a class to enable the onclick, for a simple hide show. Yes I have seen similar postings, but none that answer my question specifically. Which is:
How can I toggle an onclick class like 'toggle' to hide and show content based off of an ID? So I can have id='blah' class='toggle' than it would toggle the div using ID 'blah'?
How can I have an anchor link like:
See Our Proclamations

I am using a simple javascript based on using an onclick event, but I want to not use an onclick event.

I tried to use something like this, but it definitely did not work:

Unfortunately I understand PHP far better than I understand javascript.. Thank for any and all help!

A: First, it's not the link that you want to toggle, otherwise once you click it, it would disappear and you'd never be able to click it again. It's the content area that should be shown or hidden.
Second, don't set the style as the opposite of what the style is, when you can just call toggleClass().
See the simple code below:

$(document).ready(function() {
   // Set up a common click event handler for each section's clickable header
   // Note the addition of the callback function's "evt" argument. All event
   // handlers are automatically passed a reference to the event that triggered them.
   $('.sectionHeader').click(function(evt) {

     // Just toggle the CSS class that hides the element on the element that comes
     // just after the one that got clicked. Obviously, setting up the HTML structure
     // correctly is what makes this work.
     $(evt.target.nextElementSibling).toggleClass("toggle");
   });
});
section { margin-bottom:1em; height:20vh; }
.toggle { display:none; }
.sectionHeader { font-weight:bold; }

  Section 1

                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations
                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations

  Section 2

                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations
                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations

  Section 3

                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations
                 Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations Proclamations Proclamations                    Proclamations Proclamations Proclamations Proclamations


text:
Q: Inferring mean(X/Y) from mean(X) and mean(Y) X and Y are linked variables (i.e. they relate to different measurements in the same individuals), I know the value of mean(X) and of mean(Y) but I do not know the individual level values of X and Y.
I would like to infer the value of mean(X/Y), which I can see is not the same as mean(X)/mean(Y) (unless the correlation of X and Y is 1). I would also like to infer the value of SD(X/Y).
If I know the correlation of X and Y is there a way to infer these values?


text:
Q: JavaScript file cannot be loaded and executed in Eclipse web app I have a dynamic web app developed in Eclipse using Tomcat. My web application folder is WebContent which has the following structure:
WebContent
   |_____WEB-INF
   |        |__ web.xml
   |___form.html
   |
   |___send.js

The form.html file references the JavaScript file send.js as follows:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="send.js"></script>

They are both in the same root directory of WebContent. However, when I started the servlet in Eclipse and tried opening form.html in the browser. The send.js is not executed. But if I copy everything in send.js directly to form.html and put them in the <script>...</script> tags, it will execute the JavaScript code correctly. I don't want to put all JS code in the HTML file, so I prefer to have send.js file separate from HTML file. So how to make JS file to be executed?
Also I'm using Jersey as RESTful web service and my web.xml servlet mapping is as follows:
<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.example</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Why can't Jersey's Servlet container find the JavaScript file (send.js) in the web root directory (WebContent)?

A: Jersey only handles RESTful methods.  Jersey does not handle serving other web resources.  That is why http://localhost:8080/myapp/rest/send.js results in a 404 "Not Found".
You will need to define another <servlet> and <servlet-mapping> in your web.xml for handling the other HTML, CSS, JavaScript, image, etc. resources.  An application I work on uses the Faces Servlet for serving not only the JSF/Facelet pages but also, I think, it is the one serving the JS, CSS, etc.
Then, the correct URL to load send.js will look like http://localhost:8080/myapp/send.js


text:
Q: How to pass 'IN' parameter by using Sql Server Managment Studio execute window? This is my sample stored procedure query.
CREATE PROCEDURE EMP_Details
                    @EmpType varchar(6),
                    @Location varchar(55)
AS
BEGIN
    SET NOCOUNT ON;
SELECT EmpName,EmpAge,EmpOrgCode FROM Employee WHERE EmpType = @EmpType AND Locatoin IN (@Location)

END

When I am try to execute it via SSMS.I want to pass 'IN' parameter into SMSS query executor.What is the correct way to pass values into 'IN' parameter('@Location')
 DECLARE    @return_value int
    EXEC    @return_value = EMP_Details
            @EmpType  = N'FUL',
            @Location = N'CY,CA,NY,WA' -- <<this is not work for me

    SELECT  'Return Value' = @return_value

More explanation.

This is my table.

Image - 1.0
This is my real question.(How to add 'IN' values from this window correctly ?)

Image - 2.0
After that SSMS create this query.
USE [test]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[EMP_Details]
        @EmpType = N'A',
        @Location = N'CY,NY'

SELECT  'Return Value' = @return_value

GO

But above query Not working
Then manually run this query (Image - 3.0).

Image - 3.0
I want to pass the parameter like highlight text (Image 3.0) by using SQL server management studio query execute window (above window - Image 2.0)
Any one who try to close this question,that buggers must have to comment with the clear reason.

A: This is how I have done. It may not be most effiect way to acheive the desired result.

*

*It create creates a temp table from CSV.

Script
CREATE FUNCTION [ConvertCSVToTbl] ( @list NVARCHAR(MAX) )
RETURNS @tbl TABLE ( ID INT NOT NULL )
AS
    BEGIN
        DECLARE @pos INT ,
            @nextpos INT ,
            @valuelen INT

        SELECT  @pos = 0 ,
                @nextpos = 1

        WHILE @nextpos > 0
            BEGIN
                SELECT  @nextpos = CHARINDEX(',', @list, @pos + 1)
                SELECT  @valuelen = CASE WHEN @nextpos > 0 THEN @nextpos
                                         ELSE LEN(@list) + 1
                                    END - @pos - 1
                INSERT  @tbl(ID)
                VALUES  (CONVERT(INT, SUBSTRING(@list, @pos + 1, @valuelen)))
                SELECT  @pos = @nextpos
            END
        RETURN
    END
GO

*Following function will return 1 if found else 0
Script
CREATE FUNCTION [SearchIfNotEmpty]
    (
      @list NVARCHAR(MAX) ,
      @ID INT
    )
RETURNS BIT
AS
    BEGIN
        IF ( @list IS NULL )
            RETURN 1

        IF EXISTS ( SELECT  *
                    FROM    [ConvertCSVToTbl](@list)
                    WHERE   id = @ID )
            BEGIN
                RETURN 1
            END

        RETURN 0
    END
GO

Then you can use it like
SELECT * WHERE [Searchifnotempty](@Location, Locatoin) = 1

A: You could create function to split values ant then run subquery:
CREATE FUNCTION dbo.SplitString(@List nvarchar(max), @Delimiter nvarchar(1))
RETURNS @returns TABLE (val nvarchar(max), [level] int, PRIMARY KEY CLUSTERED([level]))
AS
BEGIN
;WITH cte AS
 (
  SELECT SUBSTRING(@List, 0, CHARINDEX(@Delimiter,  @List + @Delimiter)) AS val,
         CAST(STUFF(@List + @Delimiter, 1, CHARINDEX(@Delimiter, @List + @Delimiter), '')
         AS nvarchar(max)) AS stval,
         1 AS [level]
  UNION ALL
  SELECT SUBSTRING(stval, 0, CHARINDEX(@Delimiter, stval)),
         CAST(STUFF(stval, 1, CHARINDEX(@Delimiter, stval), '') AS nvarchar(max)),
         [level] + 1
  FROM cte
  WHERE stval != ''
  )
  INSERT @returns
  SELECT REPLACE(val, ' ','' ) AS val, [level]
  FROM cte
  WHERE val > ''
  RETURN
END;

CREATE PROCEDURE dbo.EMP_Details
                    @EmpType varchar(6),
                    @Location varchar(55)
AS
BEGIN
SELECT EmpName,EmpAge,EmpOrgCode FROM Employee
   WHERE EmpType = @EmpType AND Locatoin IN
   (SELECT val FROM dbo.SplitString(@location, ','))
END;

A: Another approach is using a @Locations xml parameter, this wait you avoid using functions,see below
  EXEC    @return_value = EMP_Details
        @EmpType  = N'FUL',
        @Locations = N'<Locations><Location Name="CY"/><Location Name="CA"/><Location Name="CN"/></Locations>'

 -----Store Procedure--------------
 CREATE PROCEDURE EMP_Details(
                @EmpType varchar(6),
                @Locations xml
                )
AS
  BEGIN
   SET NOCOUNT ON;
   SELECT EmpName,EmpAge,EmpOrgCode FROM Employee WHERE EmpType = @EmpType
   AND Locatoin IN (SELECT Locations.Node.value('@Name', 'VARCHAR(50)')
   FROM @Locations.nodes('/Locations/Location') Locations(Node))
END


text:
Q: The lines on my scatterplot for ANCOVA results doesn't look right, personal error or model error? I ran an ANCOVA model, to test the effect of treatment on the relationship between two continuous variables (elephant number and plant density) - please see more details in my last question (What statistical model can incorporate my categorical variable (2 levels) and 2 continuous variables?) but when visualizing my results on a scatterplot something isn't quite right.
Here are my ANCOVA summary results:
lm(formula = eledens ~ treat * plants, data = elemice)

Residuals:
   Min     1Q Median     3Q    Max
-7.102 -2.715  0.264  1.814  9.235

Coefficients:
                       Estimate Std. Error t value    Pr(>|t|)
(Intercept)              8.3028     1.8952   4.381 0.000097820 ***
treatMice added         -0.7066     2.7105  -0.261    0.795810
plants                   0.7368     0.1232   5.978 0.000000743 ***
treatMice added:plants  -0.6840     0.1613  -4.241    0.000148 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.856 on 36 degrees of freedom
Multiple R-squared:  0.7393,    Adjusted R-squared:  0.7176
F-statistic: 34.04 on 3 and 36 DF,  p-value: 0.0000000001308

And here is my plotting code trying to visualize the result:
plot(eledens~plants, data=elemice, type="n", xlab="Plant Density", ylab="Elephant Density")
points(elemice$plants[elemice$treat=="Control"], elemice$eledens[elemice$treat=="Control"], col="skyblue3", pch=16)
points(elemice$plants[elemice$treat=="Mice added"], elemice$eledens[elemice$treat=="Mice added"], col="salmon", pch=16)
abline(fit.mice$coefficients[1:2], col="skyblue3")
abline(fit.mice$coefficients[1]+fit.mice$coefficients[3],fit.mice$coefficients[2], col="salmon")
new.x <- rep(seq(min(elemice$plants), max(elemice$plants), len=100),2)
new.s <- rep(c("Control","Mice added"), each=100)
pred <- predict(fit.mice, new=data.frame(plants=new.x, treat=new.s), interval="conf")
pred <- data.frame(pred, treat=new.s, plants=new.x)
head(pred)
lines(new.x[1:100],pred[1:100,"lwr"],lty=2, col="skyblue3")
lines(new.x[1:100],pred[1:100,"upr"],lty=2, col="skyblue3")
lines(new.x[101:200],pred[101:200,"lwr"],lty=2, col="salmon")
lines(new.x[101:200],pred[101:200,"upr"],lty=2, col="salmon")
legend("topleft", pch=16, col=c("skyblue3","salmon"), legend=c("Control","Mice added"))

As you can see below (see output graph) the fitted lines from the coefficients look a bit odd, so does this mean my model is incorrect? Or have I assigned the coefficients incorrectly in the coding? I am fairly new to R coding, so advice on interpreting this would be much appreciated.

A: You appear to be misunderstanding the output from your model.
In your code, the line:
abline(fit.mice$coefficients[1:2], col="skyblue3")

plots a line with the correct intercept, but the wrong slope. fit.mice$coefficients[1] is the intercept, but fit.mice$coefficients[2] is the estimate for treat in the Mice added group, hence this is an offset to the intercept for the Mice added group. What you want for the slope in the Control group is simply the estimate for plants which is fit.mice$coefficients[3]. So:
abline(fit.mice$coefficients[1], fit.mice$coefficients[3] , col="skyblue3")

Then to plot the line for the Mice added group, the intercept will be the global intercept plus the estimate for treat and the slope will be the estimate for plants plus the interaction term. So:
abline(fit.mice$coefficients[1] + fit.mice$coefficients[2], fit.mice$coefficients[3] + fit.mice$coefficients[4], col="salmon")


text:
Q: sync d3.js map and leaflet map In one application I have both d3 map and leaflet map, I follow Mike's code to sync them(http://bost.ocks.org/mike/leaflet/) and draw svg points on leaflet map. The problem is that some points being cutoff at the edge of SVG container, and other SVG elements added later on (an animated pulse in this case) will only partially shown. I wonder if there's anyway to expand the SVG container based on the features (points) bound.
a working demo is here: http://xqin1.github.io/usschools/usac_school_stat.html, to reproduce the issue:
1. select the 'Number of Students' slider bar to 5300-6545, the two points on Leaftlet map only half shown.
2. click the first table row, map will zoom to the point, but the animated pulse being cut off.
Any suggestions are highly appreciated.
thanks
xiaoming

A: I had this problem as well, and found a solution.  Referencing mbostock's sample code you just need to add a little bit of padding to the projected bounding box that is calculated each time reset is called:
   var bottomLeft = project(bounds[0]),
       topRight = project(bounds[1]);

Insert something like this (just after the above declarations):
   var padding = 25;  // In pixels, choose large enough to prevent edge clipping
                      // of your largest element

   bottomLeft = [bottomLeft[0]-padding, bottomLeft[1]+padding]
   topRight = [topRight[0]+padding, topRight[1]-padding]


text:
Q: IdentityServer 4 with Active Directory on Premise Our client have many applications and they want to integrate it to just log once (single sign on), but they want that using active directory on premise they have their own server.
We decided to evaluate identityserver so we found this http://docs.identityserver.io/en/latest/topics/windows.html that identitserver 4 support active directory but here we dont see where we are going to put the LPAD//... route to connect to the active directory... so we are with doubts if identityserver supports or not Active directory or Maybe we cant undertand it very well. Thank you.

A: IdentityServer supports multiple ways to authenticate Windows users

*

*Windows integrated authentication if the machine running IS is domain joined (as the documentation describes)

*Username/password login page via LDAP (manual code from the account controller)

*via federation (e.g. with OpenID Connect/ADFS or a domain joined IdentityServer)


text:
Q: How to pass scope from directive to template I can't understand how to pass my scope object from directive to template, i need to change background my div, i did like this:
var app = angular.module('comments', []);
app.controller('fooCtrl', function($scope){
    $scope.bg= {};
})

app.directive('foo', function ($rootScope) {
    return {
        link: function (scope, element, attrs) {
            element.bind('click', function(){
                scope.bg= {background: 'blue'};
            });
        }
    };
});

and:

        <foo>foo</foo>
        <foo>foo</foo>
        <foo>foo</foo>
        <foo>foo</foo>

But this is not working.
It's probably so funny question, and my code is awful, but it my first Angular app. Hope for your help.

A: you can use controller attribute in the directive to pass the current controller scope to directive, then change the value of the controller and use $timeout to update the value back to original controller. please check the sample

angular.module('testApp', [])
            .directive('foo', function($timeout) {
                return {
                    restrict: "E",
                    scope: {
                        controller: '=',
                        color: '@'
                    },
                    link: function(scope, element, attrs) {
                        element.bind('click', function() {
                            $timeout(function() {
                              scope.controller.bg = {
                                   background: scope.color
                               };
                            });
                        });
                    }
                };
            })
            .controller('AppCtrl', function () {});

      <foo controller="vm" color="red">foo</foo>
      <foo controller="vm" color="black">foo</foo>
      <foo controller="vm" color="blue">foo</foo>
      <foo controller="vm" color="yellow">foo</foo>

            {{vm.bg.background}}

A: Better try this way
HTML
<foo data-method="ctrlFn">foo</foo>
        <foo data-method="ctrlFn">foo</foo>
        <foo data-method="ctrlFn">foo</foo>
        <foo data-method="ctrlFn">foo</foo>

{{bg.background}}

JS
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
          $scope.bg= {};
          $scope.ctrlFn = function(arg) {
        $scope.bg = arg;
        $scope.$apply();
    }
});

app.directive('foo', function() {
    return {
        restrict: 'E',
        scope: {
            fromDirectiveFn: '=method'
        },
        link: function(scope, elm, attrs) {
          elm.bind("click", function(e){
         var bg= {background: 'blue'};
            scope.fromDirectiveFn(bg);
       });
        }
    }
});

data-method="ctrlFn" from the Directive create the scope name called fromDirectiveFn using that uyou can call the controller Function ctrlFn for ref https://plnkr.co/edit/XLtahJNwTDP2T3s8Gok0?p=preview


text:
Q: Finding all graphs with a certain vertex degree sequence I've been given the following problem as homework:

Q: How many graphs are there (up to isomorphism) with score (3, 3, 3, 3, 3, 3, 6)?  Also, do this for (3, 3, 3, 3, 3, 3).
The "score" is the ordered list of degrees for the vertices in a graph; that is, the vertex degree sequence.  For example, if a graph has score (3, 3, 3, 3, 3, 3), this means it has 6 vertices, each with degree 3.

I'm honestly pretty lost as to how to start here.  "Up to isomorphism" means ignoring isomorphisms of the same graph (I'm guessing).
My attempts so far: I realize that for the first score, one of the points (with degree 6) is connected to all others, and they're all arranged in some way.
What approach do I take to finding all graphs with some score up to isomorphism?
Note: Please do NOT give me the solution to the question since this is homework.  Just looking for tips and strategies.

A: Draw pictures. It will help. Don't be afraid to consider different cases, unless there are really just too many cases.
For the $(3,3,3,3,3,3,6)$ one, let the vertex with degree $6$ be $A$, and the other vertices be $B$ through $G$. Now you know that $A$ is connected to $B$, so $B$ must be connected to two other vertices in order to have degree $3$. Suppose without loss of generality that $B$ is also adjacent to $C$ and $D$. Now what might $C$ by adjacent too? How many more edges does it need? Where does that lead?
For the $(3,3,3,3,3,3)$ problem, call the vertices $A$ through $F$. WLOG $A$ is connected to $B$, $C$, and $D$. Now $E$ and $F$ each have degree three. What happens if $E$ and $F$ are not connected to each other? What happens if they are?

A: For the first case, since you know the one vertex is connected to all other vertices, delete it and arrive at the degree sequence (2, 2, 2, 2, 2, 2).  Find all such graphs up to isomorphism.  Then, for each graph you found, add the one vertex back and you're done with that case.


text:
Q: different build configs and use it in code I was wondering if it is possible to define multiple build configs in Netbeans (Java) and somehow understand which build config you are in, in code!
I did this using Visual Studio and C++ long time ago, where I was able to #define something (e.g. #define DEBUG_MODE) in build config and check it using #ifdef(e.g. output some debug info). but I have no idea if this is possible in Java, or particularly in Netbeans.


text:
Q: host-specific .htaccess using if On a service available through different subdomains/domains, I want to be able to use only one .htaccess file. For each possible value of %{HTTP_HOST}, I have set up if blocks like this:
<if "%{HTTP_HOST} == 'staging.project.example.org'">
    [detailed configuration...]
</if>

<if "%{HTTP_HOST} == 'development.project.example.org'">
    [detailed configuration...]
</if>

This works well with access configuration lines like:
<if "%{HTTP_HOST} == 'staging.project.example.org'">
    AuthType Basic
    AuthUserFile ".htusers"
    Require user example
    Order deny,allow
    Deny from all
   Allow from xxx.xx.xx.xxx
</if>

But RewriteRule lines like this will be ignored by Apache:
<if "%{HTTP_HOST} == 'production.project.example.org'">
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^/maintenance\.html$
    RewriteRule ^(.*)$ https://www.project.example/maintenance.html [R=307,P]
</if>

Is it possible to use RewriteRule with if in .htaccess? I think it might be because of

"Only directives that support the directory context can be used within
  this configuration section."
  in https://httpd.apache.org/docs/2.4/en/mod/core.html#if

but is there a way around this?

A: I don't think rewrite rules can work in an if directive, but you can include the same logic in the rewrite rule itself:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} production.project.example.org
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ https://www.project.example/maintenance.html [R=307,P]

The RewriteCond statements form a logical AND giving you the same logic as if you encapsulated in if directives

A: If and mod_rewrite in some cases can play the exact same roles, for instance, in mod_rewrite an "If" would be like RewriteCond.
So.. do not mix them together, use one, or the other.

A: To answer my own question: For host-specific rules within the same .htaccess file, I did this, which uses a logic similar to this other answer.
SetEnvIfNoCase Host staging.project.example.org $ require_auth=true
AuthType Basic
AuthUserFile "/path/to/your/.htusers"
Order Deny,Allow
Deny from env=require_auth
Allow from xxx.xx.xx.xx # to allow certain IPs without login
Require user ... # users from the .htusers file above that are allowed to login
Satisfy any

Using this setting, any access using the host staging.project.example.org will need to go through authentication or match a whitelisted IP.
Multiple lines of SetEnvIfNoCase are possible.


text:
Q: Changing place of boxes tkinter I am creating an app and this is the part of it. I will put a canvas up to the screen so I want these variables to be at the bottom of the page but when I run this code it places everything on top left corner as shown in the photo(figure1). I am using grid function but I couldn't understand why it doesn't place where I want.(Sorry for bad english)
main = Tkinter.Tk()
main.geometry("1500x1000")
main.title("Momentum")

ml1 = Tkinter.Label(main, text ="MASS OF THE FIRST OBJECT")
ml2 = Tkinter.Label(main, text ="MASS OF THE SECOND OBJECT")
me1 = Tkinter.Entry(main)
me2 = Tkinter.Entry(main)
ml1.grid(row=600, column =400)
ml2.grid(row =600, column =600 )
me1.grid(row=650, column =400)
me2.grid(row=650, column=600)
main.mainloop()


text:
Q: Working with cv::Mat as signed values I want to deal with cv::Mat values as signed float values. for example if I made subtraction operation I want the negative values to be stored as negative and also if I made a divide operation I want the the result to be stored as float.
What is the best to do this?
Many thanks

A: Float values in OpenCV are always signed (as they are in C/C++).
A cv::Mat with depth CV_32F is signed float.


text:
Q: Express.js Route Handler Execution Order I am trying to query some documents from my MongoDB database, then add the documents to an array, and then send it to a rendered view. However, it seems that the line that I have to render the page is getting executed before the db query is completed. Below is the code:
router.get('/blog/:username/:postid', async function(req, res, next) {
  var posts = [];

  await collPosts.find( { $and : [{ postid : parseInt(req.params.postid) }, { username : req.params.username }] }, function(err, docs) {
    docs.each(function(err, doc) {
      if (doc) {
        var renderedTitle = renderer.render(parser.parse(doc.title));
        var renderedBody = renderer.render(parser.parse(doc.body));

        var post = { postid : doc.postid, username : doc.username, created : doc.created, modified : doc.modified, title : renderedTitle, body : renderedBody };
        posts.push(post);
        console.log("0"); // EDIT
      }
    });
    console.log("1"); // EDIT
  });

  console.log("2"); // EDIT
  res.render('index', { title : 'Post Results', Posts : posts });
});

I am very new to using Express, so if someone could help me to get the query to execute, and then the page to render, it would be greatly appreciated. Currently, where I log the posts array to console, the posts array is empty (as it is executing before the query is completed). Thanks
EDIT: When using the async/await approach (and some debugging), the 2 is now being logged to console before the 1 as expected. However, the 0 is being logged to console after 1 and 2. Could someone help me to resolve this please? Thanks

A: This happens because I/O operations are asynchronous operations. You must wait for your db response and then send it back to client. You are sending res.render outside find callback, which results in sending response to client before your db returns something. Put your res.render inside find callback so you will be sure you will only send your response to client after db get your docs.
router.get('/blog/:username/:postid', function(req, res, next) {
  var posts = [];

  collPosts.find( { $and : [{ postid : parseInt(req.params.postid) }, { username : req.params.username }] }, function(err, docs) {
    docs.each(function(err, doc) {
      if (doc) {
        var renderedTitle = renderer.render(parser.parse(doc.title));
        var renderedBody = renderer.render(parser.parse(doc.body));

        var post = { postid : doc.postid, username : doc.username, created : doc.created, modified : doc.modified, title : renderedTitle, body : renderedBody };
        posts.push(post);
      }
    });
    console.log(posts);
    res.render('index', { title : 'Post Results', Posts : posts });
  });
});

A: I have been coding a lot in express lately, and sometimes the issue when querying the database is that it returns a promise. You can either provide a callback or use ES6 async/await as shown below. Hope this helps!
router.get('/blog/:username/:postid', async function(req, res, next) {
  var posts = [];

  await collPosts.find( { $and : [{ postid : parseInt(req.params.postid) }, { username : req.params.username }] }, function(err, docs) {
    docs.each(function(err, doc) {
      if (doc) {
        var renderedTitle = renderer.render(parser.parse(doc.title));
        var renderedBody = renderer.render(parser.parse(doc.body));

        var post = { postid : doc.postid, username : doc.username, created : doc.created, modified : doc.modified, title : renderedTitle, body : renderedBody };
        posts.push(post);
      }
    });
  });

  console.log(posts);
  res.render('index', { title : 'Post Results', Posts : posts });
});


text:
Q: Chutzpah Error: Object doesn't support property or method 'filter' I'm trying to run jasmine tests on my knockout viewmodels, written in typescript via chutzpah but this doesn't seem possible due to the following error:
Chutzpah Error: Object doesn't support property or method 'filter'

This error gets thrown whenever I access a knockout observable and can be recreated via the following simple example.
/// <reference path="../../typings/jquery/jquery.d.ts" />
/// <reference path="../../typings/knockout/knockout.d.ts" />
/// <reference path="../../typings/jasmine/jasmine.d.ts" />

module Example {
    export class KnockoutClass {
        public anObservable = ko.observable<string>();

        public aComputed = ko.computed<boolean>(() => {
            return this.anObservable().length() > 5;
        });
    }
}

describe("This", () => {
    it(" will throw an error", () => {

        var temp: Example.KnockoutClass = new Example.KnockoutClass();

    });
});

Am I doing something fundamentally wrong here or is chutzpah not compatible with the knockout/typescript combination?
UPDATE
So I've managed to get chutzpah to run my tests by doing the following:

*

*Remove the 'Jasmine Test Framework' NuGet package from my project and replace it with the 'jasmine.js' NuGet package instead.

*Add a jasmine specrunner.html file to my tests directory that references my tests and their dependencies

*In Tools->Options->Chutzpah->Unit Test Explorer set Testing Mode to HTML

*Run tests from the Test Explorer window

This gets my tests running successfully but I still get the same exception when I try to run by right click->'Run JS Tests' and I can't debug tests either.
The issue seems to be that none of my references are resolved (the filter method is defined within jquery) so maybe I need to use require.js or some other module loader to resolve my dependencies?

A: This is resolved by upgrading to the latest version of Chutzpah.


text:
Q: my virtual-machine goes into standby If not using virtual-box for 5 min, it goes automatically in standby. How do I increased the time for it to stay a bit longer. Is my VM goes into standby

A: If you are in ubuntu you need to go to settings and power settings and change the settings there to never.


text:
Q: we want to draw arrow head using fabricjs free drawing tool A free drawing mode is enabled simply by setting isDrawingMode property of Fabric canvas to true. This immediately makes any further clicks and movements on canvas get interpreted as a pencil/brush
Arrow head using fabric js free drawing tool.
Like below image


text:
Q: ssh: connect to host 10.0.2.8 port 22: Connection timed out Telnet to Machine B through the firewall. To bypass the firewall, we can establish an SSH tunnel between Machine A and B, so all the telnet traffic will go through this tunnel (encrypted), evading the inspection. The following command establish an SSH tunnel from the localhost's port 8000 and machine B, and when packets come out of B's end, it will be forwarded to Machine C's port 23 (telnet port). If you only have two VMs, you can replace Machine C with Machine B.
I'm using this ssh -L 8000:10.0.2.7:23 seed@10.0.2.8
[06/10/19]seed@VM:~$ sudo ssh -L 8000:10.0.2.9:23 seed@10.0.2.8
ssh: connect to host 10.0.2.8 port 22: Connection timed out


text:
Q: TCL multi capture group for simplified csv string parsing with regexp I'm trying to parse a simplified CSV format with TCL regexp. I chose regexp over split to perform rudimentary format compliance test.
My problem is that I want to use a count quantifier but want to exclude the ',' from the match.
My test line:
set line "2017/08/21 16:06:20.0, REALTIME, late by  0.3, EOS450D,   1/640, F/8.0, ISO   100, Partial 450D 0.0%"

So far I have:
regexp -all {(?:([^\,]*)\,){8}} $line dummy date tm off cam exp fnum iso com

My thought process is:
Get a match group for all characters that are not comma up to the next comma.
Now I want to match this 8 time so I put it into a non-capturing group followed by a counting quantifier. But that defeats the purpose as now nothing is matched. What I need is a way to make the match go through the CSV 8 times and capture the text but not the comma.
My CSV is simplified in the following.
No quoted strings in the CSV
No empty entries in CSV
I've checked google for csv matching but most hits were too blown up due to allowing special cases in the CSV content.
Thanks,
Gert

A: In the regexp command, the interaction between the -all switch and the match variables is that the values captured in the last iteration of matching are used to fill the variables. This means that you can't fill eight variables by having one capture group and iteratively matching it eight times.
Your regular expression doesn't match anyway, since it requires a comma after the last field.
For this particular example, you could use the invocation
% regexp -all -inline {[^,]+} $line
{2017/08/21 16:06:20.0} { REALTIME} { late by  0.3} { EOS450D} {   1/640} { F/8.0} { ISO   100} { Partial 450D 0.0%}

This means to match all groups of characters that aren't commas (note that the comma isn't special: you don't need to escape it) and return them as a list.
As you noted, this is the same as using
% split $line ,

(which is also about five times faster).
You didn't want to use split because you wanted to do some validation: it is unclear what forms of validation you wanted to do, but you can easily validate the number of fields found:
% set fields [split $line ,]
% if {[llength $fields] ne 8} {puts stderr "wrong number of fields"}

You can store the fields in variables and validate them separately, which is a lot easier to get right than trying to validate them all at the same time while extracting them:
lassign $fields date tm off cam exp fnum iso com
if {![regexp {ISO\s+\d+} $iso]} {puts stderr "in search of valid ISO"}

The best method is still to split the data string using the csv package. Even if you just want to use this simplified CSV now, sooner than you think you might want to, say, allow fields with commas in them.
package require csv
set fields [::csv::split $line]

Documentation:
csv (package),
if,
lassign,
llength,
package,
puts,
regexp,
set,
split,
Syntax of Tcl regular expressions
ETA: Getting rid of leading/trailing whitespace. This is a bit unusual, since CSV data is usually arranged to be fields of strictly significant text separated by a separator character. If there is anything to be trimmed, it is usually done when saving the data.
A good way is to put the matched groups through an lmap/string trim filter:
lmap field [regexp -all -inline {[^,]+} $line] {string trim $field}

Another way is to get rid of whitespace around commas first, and then split:
split [regsub -all {\s*,\s*} $line ,] ,

You can use the Tcllib variant of split that splits by regular expression:
package require textutil
::textutil::splitx $line {\s*,\s*}

You can also swap out the earlier regular expression for [^\s,][^,]*[^\s,] (will not match fields of less than two characters). This is a regular expression that is on the verge of becoming too complex to be useful.


text:
Q: Postgres Partitioning Query Performance when Partitioned for Delete We are on Postgresql 12 and looking to partition a group of tables that are all related by Data Source Name.  A source can have tens of millions of records and the whole dataset makes up about 900GB of space across the 2000 data sources. We don't have a good way to update these records so we are looking at a full dump and reload any time we need to update data for a source. This is why we are looking at using partitioning so we can load the new data into a new partition, detach (and later drop) the partition that currently houses the data, and then attach the new partition with the latest data.  Queries will be performed via a single ID field.  My concern is that since we are partitioning by source name and querying by an ID that isn't used in the partition definition that we won't be able to utilize any partition pruning and our queries will suffer for it.
How concerned should we be with query performance for this use case?  There will be an index defined on the ID that is being queried, but based on the Postgres documentation it can add a lot of planning time and use a lot of memory to service queries that look at many partitions.

A: Performance will suffer, but it will depend on the number of partitions how much. The more partitions you have, the slower both planning and execution time will get, so keep the number low.
You can save on query planning time by defining a prepared statement and reusing it.


text:
Q: three.js Line disappears on updating the vertices of its geometry I am learning three.js library in JS. I used the Line objects to create my own coordinate axes. I am trying to move them. The problem is when I update the vertices, two of the lines work fine, but the third line disappears completely. I tried printing its vertices on console but they are within visibility range. So, what is the reason I am facing this problem? My code:
// create and axes to the scene
    //// X axis
    var material = new THREE.LineBasicMaterial({
        color: 0x00ff00
    })
    var geometry = new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(1500,0,0), new THREE.Vector3(-1500,0,0));
    Xaxis = new THREE.Line(geometry,material);
    scene.add(Xaxis);

    //// Y axis
    var material = new THREE.LineBasicMaterial({
        color: 0xff0000
    })
    var geometry = new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(0,1500,0), new THREE.Vector3(0,-1500,0));
    Yaxis = new THREE.Line(geometry,material);
    scene.add(Yaxis);

    //// Z axis
    var material = new THREE.LineBasicMaterial({
        color: 0x0000ff
    })
    var geometry = new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(0,0,1500), new THREE.Vector3(0,0,-1500));
    Zaxis = new THREE.Line(geometry,material);
    scene.add(Zaxis);

function changePosition(newVal)
{
    if(!transformCo_ordinate) {
        sphere.position.set((vx/100)*newVal,(vy/100)*newVal,(vz/100)*newVal);
    }
    else{
        Xaxis.geometry.vertices[0].set(1500,-(vy/100)*newVal,-(vz/100)*newVal);
        Xaxis.geometry.vertices[1].set(-1500,-(vy/100)*newVal,-(vz/100)*newVal);

        Yaxis.geometry.vertices[0].set(-(vx/100)*newVal,1500,-(vz/100)*newVal);
        Yaxis.geometry.vertices[1].set(-(vx/100)*newVal,-1500,-(vz/100)*newVal);

        Zaxis.geometry.vertices[0].set(-(vx/100)*newVal,-(vy/100)*newVal,1500);
        Zaxis.geometry.vertices[0].set(-(vx/100)*newVal,-(vy/100)*newVal,-1500);

        Xaxis.geometry.verticesNeedUpdate = true;
        Yaxis.geometry.verticesNeedUpdate = true;
        Zaxis.geometry.verticesNeedUpdate = true;
        console.log(Xaxis.geometry.vertices[1]);
    }

}

THe function changePosition is being called by a slider which passes its current value as newVal within range 0-100. vx = 100, vy = 100, vz = -300
Xaxis is the line that disappears. transformCo_ordinate is a boolean controlled by a checkbox. I am new to three.js so please understand if I am doing some stupid mistake.

A: Zaxis.geometry.vertices[0].set(-(vx/100)*newVal,-(vy/100)*newVal,1500);
Zaxis.geometry.vertices[0].set(-(vx/100)*newVal,-(vy/100)*newVal,-1500);

It seems you are updating the same vertex of the z axis twice. I've ported a simplified version of your code into the following fiddle. After fixing this minor bug, everything seems to work fine.
https://jsfiddle.net/gcL7dwbp/
The axis are automatically updated two seconds after application start.
three.js R104


text:
Q: Intercept DNS request in a Chrome Extension? If I want to test http://www.domain.com, but I want to test two versions of it by switching the IP out (e.g. one resolves to 127.0.0.1 and the other 192.168.1.200) is it possible to write/use a chrome extension to handle intercepting the DNS query and resolving to my IP of choice?
The current workaround is to utilize the hosts file and flush the DNS cache to switch between them but that's less than optimal and was hoping a browser extension could handle the same thing.

A: There's no mechanism to manipulate DNS requests/responses natively inside Chrome, not even via the upcoming WebRequest API.
Is there a reason that you need to test with exactly the same domain name? Setting up a dev environment on something like http://dev.example.com/ (or http://example.dev/ if you run your own DNS or have edited your hosts file) is a clean mechanism for producing the effect you want in a way that's functional with the APIs you have access to; writing an extension that gave you a button to toggle between the two domains with the push of a button would be trivial


text:
Q: Fastest way to create array from pandas dataframe with multiple values (~500 000) I have a dataframe containing a column vector with around 500 000 rows of array vector. What I'm trying to do is unloading the content of this column into a 2 dimension array but I don't know the fastest way to do it.
This is the format of the array I'm trying to obtain ([1, 2], [3, 4] and [5, 6] are array contained in my dataframe):
array([[1, 2],
       [3, 4],
       [5, 6]])

I tried to_numpy, as_matrix, and .values but it gives me a 1D array which is not what I'm looking for:
array([array([1, 2]),
       array([3, 4]),
       array([5, 6])])

The only methods which gave me the result I want are np.asarray() and np.array() but they take too much time in my case.
What I want is the same array I obtain with using numpy array methods (vector1,2 and 8) but faster if possible because it takes too much time when we have lot of data.
Thank you for your help !
edit : Here is my function which does the following: it takes in parameter a dataframe which  which contains two columns : id and vectors which is a serie of array objects.
 id      vectors
  1      array([1,2,3], dtype='float32')
  2      array([3,4,5], dtype='float32')
  3      array([6,7,8], dtype='float32')

[11530 rows x 2 columns]
What i want to do with this function is unloading the content of column id in a list which is fast and easy and the content of column vectors into an array. So i want a 2 dimensional array of array vectors.
def filter_df(df, request):

start = time.time()
filtered_df = df
ids = filtered_df['id'].tolist()

filtered_df_vectors = filtered_df['vectors'].tolist()

vectors9 = np.array(filtered_df['vectors'].tolist())

vectors1 = np.asarray(filtered_df_vectors)

vectors2 = np.array([f for f in filtered_df_vectors],dtype=np.float32)

vectors3 = filtered_df['vectors'].as_matrix()

vectors4 = filtered_df['vectors'].to_numpy()

vectors5 = filtered_df['vectors'].values

vectors6 = filtered_df.iloc[:,-1].values

vectors8 = np.array(filtered_df['vectors'].values.tolist())

vectors9 = np.array(filtered_df['vectors'].tolist())

filter_duration= time.time()-start
logger.info(f"duration: {filter_duration}s")
return ids,vectors2,filter_duration

I can't copy paste the exact output it returns me for the resulted arrays because it will be unreadable for you so i will just show the two type of array i obtain with the multiple methods i tested.
For vectors 1, 2, 8 and 9 where i use numpy methods, i obtain this format which is the one i'm looking for but it takes two much time (around 0,7 second which is too slow for my case). I wont copy paste the exact array i obtain because it will be unreadable for you. Know just that [1,2,3] represent  Here is what i obtain :
array([[1,2,3],
      [4,5,6],
      [7,8,9]], dtype=float32)

ndim : 2
dtype('float32')
shape : (11530, 300)
size : 3459000

For vectors 3, 4, 5 and 6 where i use no numpy methods like pandas to_numpy or as_matrix are fast (~0.05 sec) but returns me with the same entry an array of this form:
array([array([1,2,3], dtype=float32),
       array([4,5,6], dtype=float32),
       array([7,8,9], dtype=float32)], dtype=object)

ndim : 1
dtype('O')
shape : (11530,)
size : 11530

I don't understand why it doesn't give me the same array as numpy methods gives me.


text:
Q: Preferences Screen on Android Studio Where is this window on Android Studio?
How we can add Fragment Preferences from this window on Android Studio?
This window on Eclipse.
Thanks in advance,

A: This is called Component Tree in Android Studio.
To open this, follow the steps:

*

*Open layout.xml file

*Click on 'Design' Tab at bottom

*Select 'Component Tree' from right corner (See image)

Best luck!


text:
Q: Android. объявление кнопки через класс Подскажите, пожалуйста, как правильно сделать кнопку через класс? Всё это делается без xml, ну не считая главный Layout.
//////////// test.Java
public class test extends Activity
{
        Button buttonTest;

        public void init(){
                buttonTest = new Button(this); // что то тут не так
        }
}

///////////// mainActivity.java
public class MainActivity extends Activity
{
        Button button;

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

                test test1 = new test();

                button = new Button(this);// порядок
                // test1.init();        // снимаем коммент и весело вылетаем

        }
}

Подскажите, пожалуйста, как это правильно реализовать?
A: Вы пытаетесь создать кнопку в другой активити, в конструктор даете Context, который равен null, так как вторая активити не запущена!
public class test{
    Button buttonTest;

    public void init(Context context){
            buttonTest = new Button(context);
    }
}


text:
Q: VB SQL DELETE Statement Not Working - No Error At All This is my Code and it just doesn't work, I'm trying to make it Delete a record where the column staffID is equal to the variable currentStaffID although it doesn't delete the record or give an error, it just carries on and displays the MsgBox after the DELETE Statement.
Dim AreYouSureEdit = MsgBox("Are you sure you want to delete this record?", MsgBoxStyle.YesNo)

    If DbConnect() And AreYouSureEdit = MsgBoxResult.Yes Then

        Dim SQLCmd As New OleDbCommand
        SQLCmd.Connection = cn
        currentStaffID = editStaffIDTxtBox.Text()

        SQLCmd.CommandText = "DELETE * STAFF WHERE staffID = @currentStaffID"
        cn.Close()

        MsgBox("Record Deleted.", MsgBoxStyle.OkOnly)

    End If

A: You're setting up your command and everything - but you're never executing it! Of course nothing happens.....
You need to add one line of code:
Dim SQLCmd As New OleDbCommand
SQLCmd.Connection = cn
currentStaffID = editStaffIDTxtBox.Text()

SQLCmd.CommandText = "DELETE * STAFF WHERE staffID = ?"

'' You need to define the parameter and set its value here!
SQLCmd.Parameters.Add("p1", OleDbType.Int).Value = currentStaffID;

'' you need to actually **EXECUTE** your DELETE query!
SQLCmd.ExecuteNonQuery()

cn.Close()

Also, while you're setting up a parameter in your SQL query text just fine, I don't see where you're actually defining such a parameter on your SQLCmd object - and also be aware: OleDB doesn't use named parameters (like the native SQL Server client does) - it uses positional parameters (so that's what I replaced your named parameter with just a ?). Since there's only one parameter, this shouldn't be a problem here - but you need to properly define the SQLCmd's parameter (and set its value)

A: Connections and Commands can use unmanaged resources so, they need to have their .Dipose methods called to release these resources. Using...End Using blocks take care of this and also .Close the connection. Your database objects must be local to the method where they are used for this to work.
Always use Parameters to avoid Sql injection.
Private Sub OpCode()
    Dim AreYouSureEdit = MsgBox("Are you sure you want to delete this record?", MsgBoxStyle.YesNo)
    If AreYouSureEdit = MsgBoxResult.Yes Then
        Using cn As New OleDbConnection("Your connection string"),
                SQLCmd As New OleDbCommand("DELETE From STAFF WHERE staffID = @currentStaffID", cn)
            SQLCmd.Parameters.Add("@currentStaffID", OleDbType.Integer).Value = CInt(editStaffIDTxtBox.Text)
            cn.Open()
            SQLCmd.ExecuteNonQuery()
        End Using
        MsgBox("Record Deleted.", MsgBoxStyle.OkOnly)
    End If
End Sub


text:
Q: System.IO.IOException: Cannot create a file when that file already exists. Even after deleting the existing file Using .NET Core 3.1 and C#, I'm trying to move a directory (including all subdirectories and files) to another directory. The destination directory may contain folders and files that already exist with the same name as the source directory, for example "source/folder/file.txt" may already exist in "destination/folder/file.txt" but I would like to overwrite everything in the destination directory.
The error I am getting is "System.IO.IOException: Cannot create a file when that file already exists.", however I am deleting the file that already exists in the destination before moving the file from the source (File.Delete before File.Move), so I don't understand why I am getting this error. Also to add, I am not able to reproduce this error 100% of the time for some reason.
This is the code I am using to move a directory (lines 137 - 155):
        public static void MoveDirectory(string source, string target)
        {
            var sourcePath = source.TrimEnd('\\', ' ');
            var targetPath = target.TrimEnd('\\', ' ');
            var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
                                 .GroupBy(s => Path.GetDirectoryName(s));
            foreach (var folder in files)
            {
                var targetFolder = folder.Key.Replace(sourcePath, targetPath);
                Directory.CreateDirectory(targetFolder);
                foreach (var file in folder)
                {
                    var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
                    if (File.Exists(targetFile)) File.Delete(targetFile);
                    File.Move(file, targetFile);
                }
            }
            Directory.Delete(source, true);
        }

This is the stack trace of my error:
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException: Cannot create a file when that file already exists.
   at System.IO.FileSystem.MoveFile(String sourceFullPath, String destFullPath, Boolean overwrite)
   at Module_Installer.Classes.Bitbucket.MoveDirectory(String source, String target) in F:\git\module-installer\module-installer\Module Installer\Classes\Bitbucket.cs:line 147
   at Module_Installer.Classes.Bitbucket.DownloadModuleFiles(Module module, String username, String password, String workspace, String repository, String commitHash, String versionNumber, String downloadDirectory, String installDirectory) in F:\git\module-installer\module-installer\Module Installer\Classes\Bitbucket.cs:line 113
   at Module_Installer.Classes.OvernightInstall.ProcessInstalledModule(TenantModule tenantModule, Boolean skipBackup) in F:\git\module-installer\module-installer\Module Installer\Classes\OvernightInstall.cs:line 393
   at Module_Installer.Classes.OvernightInstall.Run(Boolean skipBackup) in F:\git\module-installer\module-installer\Module Installer\Classes\OvernightInstall.cs:line 75
   at Module_Installer.Program.Main(String[] args) in F:\git\module-installer\module-installer\Module Installer\Program.cs:line 40

This error is happening when I am running the application via Windows Task Scheduler, which I have set to run at 03:30am every day, I have specified that the task should "Start In" the same folder as where the EXE is located.
Any suggestions would be appreciated, thanks!

A: Instead of deleting existing files in the target directory try to overwrite them using File.Move(file, targetFile, overwrite: true).
By the way there is an MSDN example on how to copy directories. It's not exactly your use case, but could be helpful anyway.


text:
Q: Python requests to send POST request with form-data input I have an API which send request to system, we are sending body request as form-data option.

*

*Key: Document, value: sample.doc, type: file

*Key: Request, value: {"Data": {    "Number": "17329937082",    "Format": "MSW"  }}, type: Text

How can achieve this in Pyhton script using Requests. This worked in Postman and I am trying to call this API with python script.

A: For form-encoded data, you'll want the data kwarg paired with a dictionary, not a string. To demonstrate how this works, I'll use the requests.Request object:
from requests import Request
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = Request('GET', 'https://my-url.com', data=data)
req = r.prepare()

r.headers
{'Content-Length': '80595', 'Content-Type': 'application/x-www-form-urlencoded'}

So in a normal request, that will look like:
import requests
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = requests.get('my_url.com', data=data)


text:
Q: How to deal with spatial autocorrelation AND temporal autocorrelation in a mixed model? When creating a mixed model (or GLS) with spatiotemporal data, you can include correlation structure into your model to address autocorrelation. Spatial autocorrelation can be modelled for with correlation structures given form from spatial coordinates (tutorial here: https://rfunctions.blogspot.com/2017/06/how-to-identify-and-remove-spatial.html). The same thing can also be done for temporal autocorrelation, with correlation structures given form from a temporal variable (tutorial here: https://rpubs.com/markpayne/164550).
However, in the nlme R code, both methods inhabit the 'correlation = CorStruc' code which can only be used once in a model. Therefore, it appears that either only spatial autocorrelation or only temporal autocorrelation can be addressed, but not both (see example code below).
#neither autocorrelation considered
spatialmodel1 <- lme(rv ~ iv1+time  , random = ~1|group,
              data = mydata)

#SAC considered
spatialmodel2 <- lme(rv ~ iv1+time  , random = ~1|group,
                     data = mydata,correlation = corSpher(form = ~ X + Y, nugget = T))

#TAC considered
spatialmodel3 <- lme(rv ~ iv1+time  , random = ~1|group,
                     data = mydata,correlation = corAR1r(form = ~ time))

#SAC and TAC considered
spatialmodel4 <- lme(rv ~ iv1+time  , random = ~1|group,
                     data = mydata,correlation = corSpher(form = ~ X + Y, nugget = T),
                     correlation = corAR1r(form = ~ time))

#spatialmodel4 fails, can't use correlation twice

My Question: Is there a way to incorporate both spatial and temporal autocorrelation into the same mixed model (or GLS), using multiple correlation structures in R? Moreover, does it make statistical sense to do so?
Any help appreciated, thanks.


text:
Q: Trying to convert strings to symbols This creates an infinite loop and i'm blanking as to why this happens. When I don't use the push command, the loop doesn't happen.
#strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = [ "a", "b", "c" ]
symbols.each do |x|
  symbols.push(x.to_sym)
end

A: The following code appends items to symbols array (the same array), while iterate it; the block provides infinite items by appending to the array. (each use those items for iteration)
symbols.each do |x| symbols.push(x.to_sym) end
#^^^^^^             ^^^^^^^

Use Enumerable#map instead:
symbols.map { |x| x.to_sym }
# => [:a, :b, :c]
symbols.map &:to_sym
# => [:a, :b, :c]

or use another array instead of using the same array.
new_symbols = []
symbols.each do |x| new_symbols.push(x.to_sym) end
new_symbols
# => [:a, :b, :c]

A: This is because, in each iteration with #each method you keep adding a new element to your original array symbols. Which causes an infinite loop. Rather do as below using Array#each_index:
code - I
symbols = [ "a", "b", "c" ]
symbols.each_index do |i|
  symbols[i]=symbols[i].to_sym
end
symbols # => [:a, :b, :c]

But the above code will update your original array. A slight modification in your code will do work as well :
code - II
symbols = [ "a", "b", "c" ]
nw_ary = symbols.each_with_object([]) do |e,a|
  a << e.to_sym
end
nw_ary # => [:a, :b, :c]

But you could also use symbols.map(&:to_sym) inplace of code -II and
symbols.map!(&:to_sym) inplace of code -I. Read Array#map and Array#map! .


text:
Q: Angular2 timeout in http post request Is it possible to make a timeout of 3 seconds in a post request ? How ?
My code for the moment
this.http.post('myUrl',
    MyData, {headers: Myheaders})
        .map(res => res.json())
        .subscribe(
            data => this.ret = data,
            error => console.debug('ERROR', error),
            () => console.log('END')
        );

A: You can use the timeout operator like this:
this.http.post('myUrl',
        MyData, {headers: Myheaders})
         .timeout(3000, new Error('timeout exceeded'))
         .map(res => res.json())
         .subscribe(
           data => this.ret = data,
           error => console.debug('ERROR', error),
           () => console.log('END')
         );

A: You might need to import timeout like so
import 'rxjs/add/operator/timeout'
I couldn't get it to work without that on rxjs 5.0.1 and angular 2.3.1
Edit 20 April 2018
please refrain from importing operators that way, in rxjs +5.5 you can import operators like this one with
import { timeout } from 'rxjs/operators/timeout';
// Use it like so
stream$.pipe(timeout(3000))

Please checkout this document which explains pipeable operators in great depth.

A: I modified the answer of Thierry to get it working with the latest release. It is necessary to remove the second parameter of the timeout function. According to a discussion regarding an angular-cli issue, the timeout function always throws a TimeoutError now.
this.http.post('myUrl',
    MyData, {headers: Myheaders})
     .timeout(3000)
     .map(res => res.json())
     .subscribe(
       data => this.ret = data,
       error => console.debug('ERROR', error),
       () => console.log('END')
     );


text:
Q: My shadow is correct but cut I'm currently working on a shadow mapping implementation for my game engine, it seems to be rendering and casting the shadow map well but if the shadow is too close from the emitter, it seems to be cut, as shown in this screenshot:

(the white lines are there to check if the shadow is at the right location, they are projected from the spot light origin towards the cube's vertices).
As you can see, the shadow is cut, as it should start from the cube's edge on the floor.
I'm using a 256*256 depth16 shadow map rendered from the light point of view with a perspective matrix:NzMatrix4f::Perspective(lightComponent.GetOuterAngle()*2.f, 1.f, 2.f, lightComponent.GetRadius())
Which ultimately gives us the following projection matrix:
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, -1.02041, -1,
0, 0, -2.04082, 0

I found out that reducing the zFar value was a little bit improving the shadow:
zNear = 0.1, zFar = 1000
zNear = 0.1, zFar = 500
I think the problem comes from the test, although I have no idea what I'm doing wrong.
Here's the shader code (when projecting the shadow):
Vertex Shader:
vLightSpacePos = LightProjMatrix * LightViewMatrix * WorldMatrix * vec4(VertexPosition, 1.0);

Fragment Shader:
#if SHADOW_MAPPING
if (vLightSpacePos.w > 0.0)
{
    vec3 ProjectionCoords = vLightSpacePos.xyz / vLightSpacePos.w;

    vec2 UVCoords;
    UVCoords.x = 0.5 * ProjectionCoords.x + 0.5;
    UVCoords.y = 0.5 * ProjectionCoords.y + 0.5;

    float Depth = texture(ShadowMap, UVCoords).x;
    if (Depth < ProjectionCoords.z)
    {
        lightDiffuse *= 0.5;
        lightSpecular = vec3(0.0);
    }
}
#endif

Here's a video I made to show the bug, with a spotlight casting a shadow from a cube (both are not moving) and where I'm making the floor going down, the shadow seems to fix itself once the distance is great enough:
https://youtu.be/sisbOOml_cg
Am I missing something?

A: I fixed my problem, it was caused by the bias (it should be applied before the perspective division, not after).


text:
Q: PHP not inputting into mysql database I'm trying to insert a username, password and email into a mysql database. The database works fine, as I can pull data out from it and use on the login page, but I can't seem to create new rows and insert data.
The sql database is built up like this:
Table: peter
Primary Key: user_id - Int(5), Not Null, Auto Increment
Attributes:
username - VarChar(35), Not Null
password - VarChar(35), Not Null
email - VarChar(35), Not Null

This is my code
<?php
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
   $myusername = mysqli_real_escape_string($db,$_POST['username']);
   $mypassword = mysqli_real_escape_string($db,$_POST['password']);
   $myemail = mysqli_real_escape_string($db,$_POST['email']);
   $tbl_name = "peter";

   $sql = "INSERT INTO $tbl_name (`username`, `password`, `email`) VALUES ($username, $password, $email)";

   header("location: login.php");
}
?>

        <form action = "" method = "post">
            UserName: <input type = "text" name = "username" class = "box" required/>

            Password: <input type = "password" name = "password" class = "box" required/>

            Email: <input type = "email" name = "email" class = "box" required/>

            <input type = "submit" value = " Submit "/>

        </form>

I've tried a lot of fixes, including from other Q&A threads, but none of them have worked. So I hope someone else sees the problem.
Edit:
This is the config.php file:
<?php
   define('DB_SERVER', 'xxx');
   define('DB_USERNAME', 'xxx');
   define('DB_PASSWORD', 'xxx');
   define('DB_DATABASE', 'xxx');
   $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

A: Your fields are of varchar type. So enclose them in quotes. Also you have to execute the query using mysqli_query().
$sql = mysqli_query("INSERT INTO $tbl_name (`username`, `password`, `email`) VALUES ('$username', '$password', '$email')");

A: It is not enough to just code a query into a variable. Once that is done you must issues that query to the database for execution.
As your query is an INSERT that is basically all you would need to do
Also you need to use the correct variable names for the data you want to pass to the query i.e. the variables from the result of the mysqli_real_escape_string()
<?php
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
   $myusername = mysqli_real_escape_string($db,$_POST['username']);
   $mypassword = mysqli_real_escape_string($db,$_POST['password']);
   $myemail = mysqli_real_escape_string($db,$_POST['email']);
   $tbl_name = "peter";

   $sql = "INSERT INTO $tbl_name
                  (`username`, `password`, `email`)
           VALUES ('$myusername', '$mypassword','$myemail')";

   $res = mysqli_query($db,$sql);

   if ( $res ) {
       header("location: login.php");
       exit;
   } else {
       echo mysqli_error( $db );
       exit;
   }
}
?>

        <form action = "" method = "post">
            UserName: <input type = "text" name = "username" class = "box" required/>

            Password: <input type = "password" name = "password" class = "box" required/>

            Email: <input type = "email" name = "email" class = "box" required/>

            <input type = "submit" value = " Submit "/>

        </form>

A better way would be to use parameterized queries like this
<?php
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
   $tbl_name = "peter";

   $sql = "INSERT INTO $tbl_name
                  (`username`, `password`, `email`)
           VALUES (?,?,?)";

   $stmt = mysqli_prepare($db,$sql);

   mysqli_bind_param($stmt, 'sss', $_POST['username'],
                                   $_POST['password'],
                                   $_POST['email']
                    );

   $res = mysqli_stmt_execute($stmt);

   if ( $res ) {
       header("location: login.php");
       exit;
   } else {
       echo mysqli_stmt_error ( $stmt );
       exit;
   }
}
?>

        <form action = "" method = "post">
            UserName: <input type = "text" name = "username" class = "box" required/>

            Password: <input type = "password" name = "password" class = "box" required/>

            Email: <input type = "email" name = "email" class = "box" required/>

            <input type = "submit" value = " Submit "/>

        </form>

A: As RiggsFolly suggested in his comment, you have wrongly used variable names in your query.
Your variable names should be '$myusername', '$mypassword', '$myemail'
Write your code as below:-
// Use single quote '' around variables in query
$sql = "INSERT INTO $tbl_name(`username`, `password`, `email`) VALUES('$myusername', '$mypassword', '$myemail')";
$result = mysqli_query($db,$sql);

// Check for query errors
if(!$result){
   printf("Error: %s\n", mysqli_error($db));
   die;
}

header("location: login.php");
exit; // write exit after header tag to stop executuon of below code

Hope it will help you :)


text:
Q: How do I append a table row at the end on an element click in VueJS? I am trying to have two rows available on the table, but the user may need more rows to enter more data part of a form that will be submitted. I am having a hard time making this work. Can someone help with this? I am trying to add a row when the user clicks on the little plus icon at the end of the last TR > TD.
 <template>

                {{content1}}
                {{content2}}
                {{content3}}
                {{content4}}>
                +

    </template>

 I am trying to have two rows available on the table, but the user may need more rows to enter more data part of a form that will be submitted. I am having a hard time making this work. Can someone help with this? I am trying to add a row when the user clicks on the little plus icon at the end of the last TR > TD.* <template>

        {{content1}}
        {{content2}}
        {{content3}}
        {{content4}}>

            +

</template>

 ``` Okay now, after a good response, I have edited the code. It now looks like this. ``` <template>

        D1

          <input type="text">

          <input type="text">

          <input type="text">

        D2

          <input type="text">

          <input type="text">

          <input type="text">

        D{{item.id}}

          <input type="text" v-model="item.Filename">

          <input type="text" v-model="item.ImageTitle">

          <input type="text" v-model="item.Caption">

            +

</template>

I want to only have the icon plus on the last row cell. I wish to hide or remove the others, but also, I edited the code to start with 3 rows instead of one.

A: Your data should be reactive.
You should bind your data to the html inputs.
You need to rethink your code a lot. Here is an example of how you could get started: Vue SFC Playground


text:
Q: Allow users to specify for how long they want the shared file to be accessed by external users We revived a requirement to implement the following scenario:-

*

*Contributor user shared a file with external user.

*the contributor users can specify for how long they want the file to be shared.
Is this scenario supported in SharePoint and how?

A: You can try to set an expiration date for Anyone links. Please refer to following document
https://learn.microsoft.com/en-us/microsoft-365/solutions/best-practices-anonymous-sharing?view=o365-worldwide
You can take following steps to set custom expiration date


text:
Q: Short Sci-fi Story about a door on the Moon? I read it in a sci-fi collection book, like a "Greatest Sci-Fi Of XXXX". I read a story years ago while underway on a submarine, about a door that appears on the moon, and a retired astronaut is brought out of retirement to go investigate it.
She and her team end up entering the door, and finding sufficiently advanced aliens that they are overcome with joy upon discovering, and end up unable to do anything but kneel and worship, which the aliens seem delighted with at first, but slowly become unhappy with the worship aspect.
Throughout the story, it becomes clear that the aliens are a "partner-race" to Humanity, but Humanity is not evolved enough to be able to stand equal to the aliens, and the aliens do not want to be worshipped. The aliens end up leaving and taking their moon-door with them, to wait for another unspecified epoch to pass, to see if Humanity can evolve again to join them as desired.
Does anyone know what this is?

A: I love this story. It was a pleasure to reread it yet again to refresh the details.
Your question is such a cogent, accurate summary that it doesn't need any details fixed.
The brilliant author and title:
"I Saw the light" by Terry Bisson
It is written in the first person, narrated by the retired "lunar subcrust engineer".
When she sees an artificial light pattern on the moon while at home with her dog, she makes a few calls. But, she figures, it's a long shot.

A sixty-one-year-old woman does not exactly fit the profile for space flight and lunar exploration. So Imagine, as they say, My Surprise, when the phone rang. It was Berenson, my Russian-English boss from the old days.

This engaging story brings the team of five, two technical and three SETI, whom the reader gets to know well, next to a black pyramid on the lunar surface.
Kinda like Clarke's The Sentinel, it … just stands there.
Their attempts and interactions bring them inside several times to the aliens they can not see. Much of their experience, even the "language" and "communication", is their powerful feelings. The powerful feelings coalesce into concepts.

"The thing is, we knew them long ago," said Bee. As I listened, my emotions were spinning, like dust in sunlight, settling as he spoke onto the table of my mind, in which his voice, like a fingertip, traced his words: "This is not first contact, it is second contact."

The crew-members' feelings, almost hopelessly worshipful, change after each entry into the pyramid.

"But something is wrong," said Bee. "We have to go back in. Once more."

The crew members' feelings are crushingly overwhelming, life-changing.

"And do I get to go?" I could still feel the hand on my head. I wanted to feel it there again, more than anything.

The engineer's dog, from the first scene in the beginning of the story, comes into the scene a few times, even with communications from Earth letting her know the dog wouldn't eat, and just howled – at the moon, as if he knew.
The dog is more than just story setting. He seems to be an unspoken parallel to the doglike, worshipful way the humans feel in the presence of the aliens.

And what he was saying, we all knew.
"They were our gods," said Chang.
"Not exactly," said Vishnu. "We were their companion species, their helper. We lived only to please them. We looked up to them."
"Their favorite," I said. "Their pet."
"And they loved us," said Chang. "And they love us still."

"But they wanted more," said Bee. "They set us free so we could develop without them. They put us down on Earth, where we could escape the worship of them that makes our knees go weak and our minds go blank. They wanted a true companion. They thought if they left us alone we would develop into a sentient race on our own."

And to be more than mournful worshipful dogs howling at our abandonment and capable of more than wagging our tails with joy at our reunion.
I read it in 2003 on Ellen Datlow's SciFiction site when  SciFiction still existed.  Written in 2002, this story was one of the newest Originals.
After SciFi and then SyFy bought it out (or whatever they do), they kept it up for a while, but no longer.
The internet Archive had a lot of SciFi stories – it's sadly ironic that SciFi itself called its two long-gone columns "Archived Classics" and "Archived Originals" – but even Internet Archive seems to have lost a lot of my previously bookmarked stories.
Don't know how long this link will last, but I had saved one that doesn't show up now in my DuckDuckGo search: the old SciFi "archived original" still archived.
ISFDB shows the story's home anthologies, and Year's Best SF 8
is archived.


text:
Q: SQL Backup very slow I takes like an hour to backup my 24GB database. I put the backup on the same disk as the location of the actual SQL database, but I dont think thats the cause.
When I execute exec sp_who2, here is the result:

And here is the result of
SELECT  wt.session_id, ot.task_state, wt.wait_type, wt.wait_duration_ms, wt.blocking_session_id, wt.resource_description, es.[host_name], es.[program_name] FROM  sys.dm_os_waiting_tasks  wt  INNER  JOIN sys.dm_os_tasks ot ON ot.task_address = wt.waiting_task_address INNER JOIN sys.dm_exec_sessions es ON es.session_id = wt.session_id WHERE es.is_user_process =  1

Here is the perfmon window:

How can I diagnose this issue?

A:
I put the backup on the same disk as the location of the actual SQL
  database, but I dont think thats the cause.

Reality check - that is absolutely one reason that a backup like that is slow.
Discs break down in IO when you do multiple operations at the same time. Even worse so when it is "the disc" not "the disc array in a high performance raid 10".
Your head is busy moving back and forh between database operations, reading for backup and writing to the file.


text:
Q: undefined method `to_key' for # Did you mean? to_set to_ary This is my form
      <%= form_for @customer do |f| %>

<%= f.text_field  :NameAndFamilyName,class:'1', placeholder:'نام و نام خانوادگی' %>

<input class="1" placeholder="نام و نام خانوادگی">

<input class="1" placeholder="تلفن همراه">

<input class="1" placeholder="آدرس ایمیل">

<input placeholder="موضوع پیام">

<textarea placeholder="متن پیام"></textarea>

          <button>ارسال پیام</button>

      <% end %>

This is my controller
    class CustomerController < ApplicationController
  def index
        @customer = Customer.all

    end

    def new
        @customer = Customer.new
    end

    def create
        @customer = Customer.new(customer_params)

        if @customer.save
            redirect_to @customer
        else
            render 'customer/index'

        end

    end
end

This is my migration:
     class CreateCustomers < ActiveRecord::Migration[5.2]
       def change
        create_table :customers do |t|
          t.string  :NameAndFamilyName
          t.integer :Phone
          t.string  :Email
          t.string  :MessageSubject
          t.text    :Message

          t.timestamps
        end
      end
    end

What should I do this code its not running?
I want create form but this error apears   every things is normal for me but its not running. I'm having this error:
undefined method `to_key' for #<ActiveRecord::Relation []>
  Did you mean? to_set to_ary

A: I assume you have this error on index action.
@customer = Customer.all

It returns not one customer but the list of customers. So I suggest to change it on:
def index
  @customers = Customer.all
  @customer = Customer.new
end


text:
Q: Angular velocity and transformation of Euler Angles Suppose we have an evolving system describing a rigid body by euler angles with respect to the bodies center. Suppose we do a constant offset parameter transformation for the euler angles, in other words suppose we re-define the center of the coordinate system with respect to a different set of euler angles. Does the body fixed frame angular velocity vector get changed during this process?
Since it's body fi
xed frame I would like to say it does not get changed, can someone explain?

A:
Two coordinate systems that not parallel to each other are attached to a rigid body
the transformation matrix between system "1" and inertial system is described by the three Euler angles
$$S_1=S_1[\alpha(t)~,\beta(t)~,\gamma(t)]$$
the transformation matrix between system "2" and inertial system is
$$S_2=S_s^T\,S_1\,S_s$$
where $~S_s$ is a static transformation that make at $t=0$ the two coordinates system parallel to each other , you can describe the static coordinate system also by a three Euler angles they are time independent .
the angular velocity $~\vec\omega=[\omega_x'~,\omega_y'~,\omega_z']~$ can obtained from this equation
$$\begin{bmatrix}
    0 & -\omega_z' & \omega_y' \\
    \omega_z' & 0 & -\omega_x' \\
    -\omega_y' & 0 & \omega_x' \\
  \end{bmatrix}=S_2^T\,\dot{S_2}$$
where the components of the angular velocity $~\vec \omega~$ are given in body fixed coordinate system "2".


text:
Q: IndexedDB getting all data with keys as a promise This is the code I have that wraps IndexedDb API in promises.
const asyncStorage = function(databaseName, storeName, version) {
    return new Promise((resolve, reject) => {
        const openRequest = window.indexedDB.open(databaseName, version)

        openRequest.onupgradeneeded = () => openRequest.result.createObjectStore(storeName)
        openRequest.onblocked = () => reject(new Error(`onblocked`))
        openRequest.onerror = () => reject(openRequest.error)
        openRequest.onsuccess = () => {
            const db = openRequest.result

            resolve((transactionType, fn) => runQueriesInTransaction({ db, storeName, transactionType, fn }))
        }
    });

    function runQueriesInTransaction({ db, storeName, transactionType, fn }) {
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(storeName, transactionType)
            const store = transaction.objectStore(storeName)

            const requests = fn(store)

            const resultsPromise = Array.isArray(requests)
                ? Promise.all(requests.map(promisifyRequest))
                : promisifyRequest(requests)

            transaction.onerror = () => reject(transaction.error)
            transaction.oncomplete = () => resolve(resultsPromise)
        })
    }

    function promisifyRequest(request) {
        return new Promise((resolve, reject) => {
            request.onerror = err => {
                // prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873
                if (typeof err.preventDefault === `function`) {
                    err.preventDefault()
                }
                reject(request.error)
            }

            request.onsuccess = () => resolve(request.result)
        })
    }
};

The problem is getAll() seems to retrieve only the data in an array format, and getAllKeys() gets all the keys without the data. I could not find a method to get both keys and values. I currently loop through each key and get items in their own separate queries. Seems inefficient.
    const transaction = await asyncStorage('db', 'keyvaluepairs', 1);
    let keys = await transaction(`readonly`, idbStore => idbStore.getAllKeys());
    for (const key of keys)
        let json = await transaction(`readonly`, idbStore => idbStore.get(key));

I'm trying to convert my code from localStorage.
Bonus question: can I sort database results in descending order similar to SQL?


text:
Q: Analyzing only modified classes in Sonar I would like to know if it's possible to focus a sonar analysis in the classes you have modified.
Imagine you have a huge project, analyzed with a SonarQube Ant Task that can spend a lot of time analyzing all its code and generating the results in the server.
If you only modified 3 classes in this huge project... would be possible to make a shorter analysis with only that 3 classes and update the results?
I'm looking the 'sonar.sources' and 'sonar.exclusions' properties, but I cant find a solution.
My idea is to have the complete proyect analyzed in sonar server. If you use the Sonar Eclipse Plugin you can see all the info displayed, and if you use the sonar ant task you can update the information, but only analyzing the source you have modified.

A: This feature will be implemented in next version of SonarQube (4.0).
You can vote and watch the following ticket: SONAR-3677


text:
Q: How does hide()/show() system works? fragment android after some research i need to implement hide() and show() system on my app,
now I'm doing this way:
When i select some fragment to show on my menu, i create with new Fragment(), then i use beginTransaction().replace() to replace the content on my FrameLayout with this new Fragment...
But i need to don't recreate this fragment, and i think, use the hide() and show() system, but, how do i implement this? how exactly hide() and show() works? do i need to use backstack and so?
Thank you!!

A: I thought I had tried the hide/show mechanism of FragmentManager. There below is one segment of my source codes implementing this. Have a look:
This method to hide all visible and non-null Fragments:
private void hideAllFrags(FragmentTransaction fragmentTransaction) {
    for (String name : fragNames) {
        Fragment fragment = fragmentManager.findFragmentByTag(name);
        if (fragment != null && !fragment.isHidden()) {
            fragmentTransaction.hide(fragment);
        }
    }
}

And then, the key method is here:
{
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    hideAllFrags(fragmentTransaction);
    switch (v.getId()) {
        case R.id.button1:
            if (fragA == null) {
                fragA = new FragA();
                fragmentTransaction.add(R.id.frag_container, fragA, fragNames[0]);
                fragmentTransaction.addToBackStack(fragNames[0]);
            } else {
                fragmentTransaction.show(fragA);
            }
            break;
        case R.id.button2:
            if (fragB == null) {
                fragB = new FragB();
                fragmentTransaction.add(R.id.frag_container, fragB, fragNames[1]);
                fragmentTransaction.addToBackStack(fragNames[1]);
            } else {
                fragmentTransaction.show(fragB);
            }
            break;
        default:
            break;
    }
    fragmentTransaction.commit();
}

I hope this will help you;)


text:
Q: Space needed for a little more than basic Ubuntu installation I will want my basic dual boot Ubuntu installation alongside Windows to have the following:
1. JDK 7.0
2. Android Eclipse IDE
3. Some basic video playing programs (like VLC)
4. Shell utilities (I'm not sure, but I believe some of the utilities need to be downloaded)
Does 30GB space allocated to Ubuntu in my Windows laptop sound reasonable to achieve this Ubuntu installation?

A: 30 GB is quite resonable it takes 4gb to install ubuntu and 4gb as swap area and rest are all your space you can install anything in it


text:
Q: validation messages don't display all at the same time with custom validation on MVC3 I have made some custom validations looking like this
if (UnEquip == false && (Salaries < 1 || Salaries > 1000000))
{
    yield return new ValidationResult("Le champ 'Nombre de salariés' doit être renseigné et compris entre 1 et 1000000", new[] { "Salaries" });
}

The validation works just fine, but if i have an error on a validator that is not custom, the error messages from the custom validators doesn't show. They areas displayed only if there is only error from a custom validation.
i've tried turning off client side validation, but without any success.
i'm using a validationSummary,Jquery.validate and Jquery.Unobstrusive as scripts.
I have no clue on how to display every error messages at the same time, it seems it's a problème in the js.

A: Use if(ModelState.IsValid) on controller to validate fields.

A: Did you implement the "IClientValidatable" interface?
http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3


text:
Q: Ramanujan's puzzling problem Question:
$$ f_1 (x) = \sqrt {1+\sqrt {x} } $$
$$ f_2 (x) = \sqrt{1+ \sqrt {1+2 \sqrt {x} } } $$
$$ f_3 (x) = \sqrt {1+ \sqrt {1+2 \sqrt {1+3 \sqrt {x} } } } $$
... and so on to
$$ f_n (x) = \sqrt {1+\sqrt{1+2 \sqrt {1+3 \sqrt {\ldots \sqrt {1+n \sqrt {x} } } } } } $$
Evaluate this function as n tends to infinity.
Or logically:
Find
$ \displaystyle{\lim_{n \to \infty}} f_n (x) $ .
MyProblem:
Ramanujan discovered
$$ x+n+a=\sqrt{ax + (n+a)^2 +x \sqrt{a(x+n)+(n+a)^2 +(x+n) \sqrt{\ldots}}} $$
which gives the special cases
$$ x+1=\sqrt{1+x \sqrt{1 + (x+1) \sqrt{1 + (x+2) \sqrt{1 + (x+2) \sqrt{\ldots}}}}}$$
for x=2 , n=1 and a=0
$$3= \sqrt{1+2 \sqrt{1+3 \sqrt{1+ 4 \sqrt{1+\cdots}}}}$$
Is there any proof of this discovery?Without proof I don't think that the problem should be solved in this way.And if there is a proof please share it and also tell your approach to solve it.


text:
Q: jQuery selector - extjs - escape brackets I have an ExtJS component query selector that looks like this:
var field = Ext.ComponentQuery.query("myformpanel [fieldName="+fieldName+"][xtype!=container]")[0];

this works fine but when fieldNamehas brackets [ ], for example "Date [From]" i get this error:

Invalid ComponentQuery selector: "][xtype!=container]"

A: You should add single quotes ' around the variable to consider the value as a string, like :
var field = Ext.ComponentQuery.query("myformpanel [fieldName='"+fieldName+"'][xtype!=container]")[0];

Hope this helps.


text:
Q: Postgresql cumulative sum Last 3 days I have this data and I want to compute a rolling 3-day  sum like below.
Note: Missing date has to be considered. So isn't just the last 3 rows, but 3 solar days.

I tried with a window function but it's not working:
SELECT
    date,
    SUM(clicks) OVER (ORDER BY DATE ASC ROWS BETWEEN DATE - INTERVAL '3 day' AND date)
FROM table

A: Upper bound should be current row and range:
SELECT
    date,
    SUM(clicks) OVER (ORDER BY DATE ASC range BETWEEN INTERVAL '3 day' PRECEDING AND CURRENT ROW)
FROM table


text:
Q: Change a CSS style of Raphael text with javascript I can change a CSS attribute of a Raphael text with jQuery like so:
var text = paper.text(10,10,'abc');
$(text.node).css('font-style','italic');

How can I do the same with just javascript and no jQuery?

A: In javascript, use element.style.property = 'new-style'; to edit styles of an element.
var text = paper.text(10,10,'abc');
text.node.style.fontStyle = 'italic';


text:
Q: Conditional Sass Variables with Nativescript Android and iOS render fonts in vastly different ways.  I'd like to be able to get their renders looking a little more similar, so I need to change the font-sizes and weights throughout my entire app depending on whether it's on iOS or android.
Obviously, going through every place font-size or weight is defined and adding a conditional for is out of the question, and (fortunately) I already have all my font sizes and weights defined by sass variables.
Regardless of whether or not there is a better solution than conditional sass variables, I would like to know:
How can I conditionally select sass variables in nativescript?
I know that modules will use MyModule.ios.css or MyModule.android.css depending on the os.  Can I take advantage of that?

A: Yes, you are on right track. You can have MyVariable.android.scss and MyVariable.ios.scss to define different values for Sass variable. In my code sharing project I have MyVariable.scss as well that I use for HTML(Web).
I have created a sample playground for you here.
In my home.component.ios.scss
$labelfontSize: 10;
$labelfontColor: red;
.home-panel{
    vertical-align: center;
    font-size: 20;
    margin: 15;
}

.description-label{
    margin-bottom: 15;
    color: $labelfontColor;
    font-size: $labelfontSize;
}

and in my home.component.android.scss
$labelfontSize: 18;
$labelfontColor: green;
.home-panel{
    vertical-align: center;
    font-size: 20;
    margin: 15;
}

.description-label{
    margin-bottom: 15;
    color: $labelfontColor;
    font-size: $labelfontSize;
}

It shows red text in ios while in android text is green.