text:
Q: Java AWT EventQueue "Not on FX application thread" exception in JavaFX I've got a problem by migrating an application from Swing to JavaFX.
To make it as simple as I can, at the start of my application, a JavaFX Stage is initialized in the main JavaFX class (Main.java). At the end of initialization (in JFX thread), I open a Swing customed JDialog (not migrated at the moment) which asks the user to choose a device. In this JDialog I have an ObservableModel which send as parameters entries from user in the device selection JDialog. My main JavaFX class is an Observer and I get the entries from the selected device by overriding the update() function. So far, all is working fine.
And then, still in the update() function, if the user is not connected, i want to open a login dialog which I created in JavaFX (was a Swing JDialog before migration). And when I try to open it, I get an java.lang.IllegalStateException exception telling "Not on FX application thread; currentThread = AWT-EventQueue-0"
Some code now :
JavaFX Main class Main.java : Important is that I open the JDialog by calling openSlpDlg() which will ask the user to choose a device and the result of the selection will be returned in the update() method as argument
public class Main extends Application implements Observer {

    @Override
    public void start(Stage stage) {

        // init stage
        stage.setTitle(Messages.getString("Appli_HaslerST"));
        stage.getIcons().add(new Image(getClass().getResourceAsStream("../gifs/application.gif")));
        mainContainer = new BorderPane();
        Scene root = new Scene(mainContainer, 1200, 1000);
        stage.setScene(root);

        // init stage content
        initialize();

        stage.show();

        // open that device selection dialog
        openSlpDlg();

        this.stage = stage;

    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void update(Observable o, Object arg) {

        // called when user has chosen a device in the JDialog

        if (arg instanceof Object[]) {
            Object[] set = (Object[]) arg;

            try {

                // con is an Interface that will create the correct
                // device JPanel, depending of selection.
                // the JPanel is created in constructor of MainGUI

                // Start method of device application which creates a
                // new MainGUI (JPanel)
                // AbstractTabbedPanel is a customed JPanel
                AbstractTabbedPanel panel = con.getTabbedPanel();

            } catch (Exception e) {

            }
        }
    }

}

The external device application returns a JPanel which will be stored in my stage by using SwingNode (it works fine). But at the creation of this JPanel, in the MainGUI (as mentionned in the comments in the code above), I check if the user is logged, and if not, I open the login dialog which is a JavaFX Dialog<R>

MainGUI from external application. con.getTabbedPane() called by the JavaFX Main application in update() (in the code above) will create a new MainGUI.
public class MainGUI extends JPanel {

    public MainGUI() {

        // [...] all initalization done in constructor

        // test if user connected
        if (LocalAccessControl.getInstance().getAccessControl() == null) {

            // not connected case

            // JavaFX custom login extends from Dialog<LoginInfo>
            LoginDlg login;
            login = new LoginDlg()

            // show login dialog and get a LoginInfo object with
            // user info
            LoginInfo userInfo = login.showLogin();
        }
    }

}

And by LoginInfo userInfo = login.showLogin(); I get this exception :java.lang.IllegalStateException: Not on FX application thread; currentThread = AWT-EventQueue-0
Problem is, I need login info stored in userInfo to continue constructing my JPanel in the constructor (so in AWT EventQueue thread) but my LoginDlg is JavaFX implemented. I tried to use Platform.runLater(new Runnable(){...}) but it doesn't work and it's normal, because I'm currently not using JavaFX thread and it's not executed immediately in FX thread (the dialog is never displayed and login can't be done, so the JPanel will be null and a warning message is displayed telling that connection was not possible).
I've already seen few posts on stackoverflow for this exception but I think my case is a bit more tricky and I can't find a great solution to get over this.
Hope you can help me. If you need more details, please ask!

A: Mixing Swing and JavaFX is tricky, because each toolkit is single-threaded and each has its own UI thread on which "live" UI elements must be managed. For Swing, see "Swing's Threading Policy" in the javax.swing package documentation; for JavaFX see the "Threading" section of the Application documentation. JavaFX attempts, where possible, to enforce these rules by throwing a runtime exception if you violate them (as you have seen); Swing does not throw exceptions. In either case, violating the threading rules has the potential to leave your application in an indeterminate state and cause bugs at essentially arbitrary times in the application lifecycle.
You can use SwingUtilities.invokeLater(() -> { ... }); to invoke code on the AWT event dispatch thread, and Platform.runLater(() -> { ... }); to invoke code on the FX application thread. These calls are asynchronous, so they will not be executed immediately; in other words code immediately following these calls is likely to be executed before the code submitted to the UI threads.
Additionally, you should not make blocking calls on the UI threads, except where these blocking calls are explicitly designed to do so. For example, if dialog is a FX dialog (or stage), dialog.showAndWait() is a blocking call that is designed to be safely executed on the FX Application thread; however you should not make calls that block for input from an FX dialog on the AWT event dispatch thread.
You haven't shown a complete example in your code, but it looks like you need something like this:
@Override
public void start(Stage stage) {

    // init stage
    stage.setTitle(Messages.getString("Appli_HaslerST"));
    stage.getIcons().add(new Image(getClass().getResourceAsStream("../gifs/application.gif")));
    mainContainer = new BorderPane();
    Scene root = new Scene(mainContainer, 1200, 1000);
    stage.setScene(root);

    // init stage content
    initialize();

    stage.show();

    // open that device selection dialog: this is a Swing dialog,
    // so it must be performed on the AWT event dispatch thread:
    SwingUtilities.invokeLater(this::openSlpDlg);

    this.stage = stage;

}

Your update() method is executed as a response to user input in the AWT event dispatch thread (from an action listener in the Swing dialog shown from openSlpDlg, I am assuming); hence it, and the methods it invokes, such as new MainGUI() are executed on the AWT event dispatch thread. So you now need:
public MainGUI() {

    // this method is executed on the AWT event dispatch thread

    // [...] all initalization done in constructor

    // test if user connected
    if (LocalAccessControl.getInstance().getAccessControl() == null) {

        // not connected case

        // JavaFX custom login extends from Dialog<LoginInfo>

        // Tricky part. We need to create a JavaFX dialog (so must be
        // done on the FX Application Thread), show it and wait for the result
        // (so make a blocking call, which needs to be on a background thread),
        // and process the result back on the AWT thread.

        // task to execute on the FX Application Thread, returning a LoginInfo:
        FutureTask<LoginInfo> getLoginTask = new FutureTask<>(() -> {
            LoginDlg login;
            login = new LoginDlg()

            // show login dialog and get a LoginInfo object with
            // user info
            return login.showLogin();
        });

        // execute the task on the FX Application Thread:
        Platform.runLater(getLoginTask);

        // now create a background thread that waits for the login task to complete,
        // and processes the result back on the AWT event dispatch thread:
        Thread waitForLoginThread = new Thread(() -> {
            try {
                final LoginInfo userLogin = getLoginTask.get();
                SwingUtilities.invokeLater(() -> {

                    // process userLogin here...

                });
            } catch (InterruptedException exc) {
                throw new Error("Unexpected interruption waiting for login");
            } catch (ExecutionException exc) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error getting login info", exc);
            }
        });
        waitForLoginThread.start();
    }
}

If you really want to block the MainGUI constructor until the FX dialog is dismissed, you could do it by waiting for the task submitted to the FX Application Thread to complete directly there (instead of in a background thread):
public MainGUI() {

    // this method is executed on the AWT event dispatch thread

    // [...] all initalization done in constructor

    // test if user connected
    if (LocalAccessControl.getInstance().getAccessControl() == null) {

        // not connected case

        // JavaFX custom login extends from Dialog<LoginInfo>

        // Tricky part. We need to create a JavaFX dialog (so must be
        // done on the FX Application Thread), show it and wait for the result
        // (so make a blocking call, which needs to be on a background thread),
        // and process the result back on the AWT thread.

        // task to execute on the FX Application Thread, returning a LoginInfo:
        FutureTask<LoginInfo> getLoginTask = new FutureTask<>(() -> {
            LoginDlg login;
            login = new LoginDlg()

            // show login dialog and get a LoginInfo object with
            // user info
            return login.showLogin();
        });

        // execute the task on the FX Application Thread:
        Platform.runLater(getLoginTask);

        // wait for task submitted to FX Application Thread to complete.
        // note this blocks the AWT event dispatch thread:
        try {
            final LoginInfo userLogin = getLoginTask.get();

            // process userLogin here...

        } catch (InterruptedException exc) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException exc) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error getting login info", exc);
        }
    }
}

I don't recommend this approach: it will make the Swing UI unresponsive and may result in a poor user experience. It's generally better to structure the application so that either MainGUI can be shown without login having completed, and then updated when login is complete; or so that the MainGUI constructor is not invoked at all until login is complete.


text:
Q: Does joint continuity imply separate continuity? I know that separate continuity does not, in general, imply joint continuity but does the converse hold? Given $X,Y,Z$ topological spaces, if $f: X\times Y \to Z$ is continuous ($X\times Y$ with the product topology) does it follow that $f$ is separately continuous?

A: Yes, if $f : X \times Y \to Z$ is continuous, then for each $(x_0, y_0) \in X \times Y$, $f(x_0, y)= f\restriction_{\{x_0\} \times Y}$ is continuous as a map from $Y \to Z$ and so is $f(x, y_0) = f\restriction_{ X \times \{y_0\}}$ as a map $X \to Z$. The maps $x \to (x,y_0)$ and $y \to (x_0, y)$ are always embeddings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: setTimeout in a loop: callbacks happen with no delay between them I searched around and found some others with similar issues, but I can't seem to find a solution or clear explanation.
var content = 'test
';

for( var i = 1; i < 6; i++ ) {
    setTimeout(function() {
        document.write(content);
    }, 3000);
}

I'd like the code in the for loop to execute 5 times, with a three second delay between each loop. When it runs it, at least on the surface, looks like a three second delay at page load, then goes through all the loops with no delay.
What am I missing?

A: Your problem is that all the calls are happening after 3000 ms. Do perform each call 3s apart do this:
var content = 'test
';

for( var i = 1; i < 6; i++ ) {
    setTimeout(function() {
        document.write(content);
    }, 3000 * i);
}

A: You probably need to use setInterval ('cause you're trying to run code at a certain "interval")
// first create an isolated namespace because we don't need to dirty the global ns //
(function(){
  var counter = 0;
  var maxIterations = 6;
  var intervalReference = setInterval(function(){

    // your code goes here //
    alert('test');

    // the stop condition //
    ++counter;
    if (counter == maxIterations) {
      clearInterval(intervalReference);
    }
  }, 3000);
}())

A: setInterval is probably the way to go (see Alin's answer) but if you were wanting to go down the setTimeout route, the code would look something like this:
var loop = 0;
var content = "test
";

function startTimeout(init){
  if(init!==true){
    document.write(content);
    loop++;
  }

  if(loop<5){
    setTimeout(startTimeout, 3000);
  }
}

startTimeout(true);


text:
Q: An equation for an extremely convex (curved) function? Suppose we have four points, $x_1<x_2<x_3<x_4$
Is anyone able to provide me with an equation for a function that is

*

*nearly flat  $x_1,x_2$ (i.e. $f(x_1)/f(x_2) \approx 1)$

*Steep between $x_3,x_4$ (specifically, I want $\frac{f(x_3)}{f(x_4)}<\frac{f(x_1)}{f(x_2)}$)

*strictly increasing, continuous, positive, and convex over the positive reals

For example, suppose $x_1 = 2.2,x_2=5,x_3=7.5,x_4=9$,
Is there a convex, strictly increasing, function where  $\frac{f(x_3)}{f(x_4)}<\frac{f(x_1)}{f(x_2)}$

Some comments:

*

*Im okay with either a general answer or an answer for the specific points i have given

*convexity is not a requirement as long as the function is strictly increasing (I prefer if it is convex though

*

*I'd like $f(0)=0$ if possible (but not required)

I've been generating a bunch of points in mathematica and trying to generate a curve, but i haven't had luck.
I have also tried an exponential function (this is the steepest thing I could think of),but then $x_1,x_2,x_3,x_4$ need to satisfy $x_1+x_4 > x_3+x_2$, (which my example points don't satisfy)
This has been bugging me because its so easy to draw such a function, but I haven't been able to come up with an equation.

A: A simple answer is to define $x_c=\frac 12{x_2+x_3}$, then
$$f(x)=e^{k(x-x_c)}$$
The side below $x_c$ will be pretty flat because it is like $e^x$ for $x \lt 0$ while the side above is like $x \gt 0$.  Increase $k$ to make it more pronounced.

A: If $g(x)$ is strictly increasing and convex then $f(x)=e^{g(x)}$ is strictly increasing, positive, and convex. Then the requirement $f(x_4)/f(x_3)>f(x_2)/f(x_1)$ reduces to $g(x_4)-g(x_3)>g(x_2)-g(x_1)$. It is much easier to construct such a function, for example by setting $g(x)=1/(c-x)$ when $x_1\le x\le x_4$ and extending linearly outside this interval.


text:
Q: Is there a way to group RadioButtons generated from the ItemTemplate of an ItemsControl  <DataTemplate x:Key="Genre_DataTemplate">
        <RadioButton GroupName="One" Content="{Binding...
 </DataTemplate>

Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree.
Any solution or workaround to group them together?. GroupName property also doesn't have any effect here.
[Update] I am trying this in Silverlight

A: The problem is that the RadioButton.GroupName behavior depends on the logical tree to find a common ancestor and effectively scope it's use to that part of the tree, but silverlight's ItemsControl doesn't maintain the logical tree.  This means, in your example,  the RadioButton's Parent property is always null
I built a simple attached behavior to fix this.  It is available here: http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/

A: I think the problem is somewhere else in the control tree. Can you post more details?
Here is a sample xaml code that works as expected:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
    <Grid.Resources>
       <XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&lang=en-us&format=rss_200">
          <XmlDataProvider.XmlNamespaceManager>
             <XmlNamespaceMappingCollection>
                <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/>
             </XmlNamespaceMappingCollection>
          </XmlDataProvider.XmlNamespaceManager>
       </XmlDataProvider>
       <DataTemplate x:Key="itemTemplate">
        <RadioButton GroupName="One">
          <Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/@url}"/>
        </RadioButton>
       </DataTemplate>
       <ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}">
          <WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
       </ControlTemplate>
    </Grid.Resources>
    <ItemsControl
       Width="375"
       ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}"
       ItemTemplate="{StaticResource itemTemplate}"
       Template="{StaticResource controlTemplate}">
    </ItemsControl>
 </Grid>

</Page>

P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)


text:
Q: Animating a rectangle to go left for a set amount of time and back and another rectangle to go up and down The problem that I have is that I can't get my animation to work. All I need the program to do is on a button click animate a rectangle to go left up to a point then go back. I used Double animation class but that doesn't want to work
I've already tried using the Double Animation class but that didn't work and crashed my program each time. Its running on visual studio and its a simple program that isn't designed to do much.
        System.Drawing.SolidBrush myBrush = new
        System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Graphics formGraphics;
        formGraphics = this.CreateGraphics();
        formGraphics.FillRectangle(myBrush, new System.Drawing.Rectangle(0, 0, 200, 200));
        System.Drawing.Rectangle rec = new System.Drawing.Rectangle(40, 40, 40, 40);

        myBrush.Dispose();
        formGraphics.Dispose();

        DoubleAnimation da = new DoubleAnimation();
        da.To = 50;
        da.From = 500;
        da.Duration = TimeSpan.FromSeconds(5);

The expected result is that the rectangle goes from left to right, reach a certain point, then go right to left . Ideally I want to introduce threads in this program and thought that it would be good to add it here.


text:
Q: AWS Cognito PHP SDK - Unable to verify secret hash for client So far I created user pool, app client and marked Generate client secret box.
I am able to register, login, logout.
But I'm unable to refresh token using REFRESH_TOKEN_AUTH flow.
private function refreshConf($refreshToken, $hash)
{
    return [
        'AuthFlow' => 'REFRESH_TOKEN_AUTH',
        'ClientId' => $this->client_id,
        'UserPoolId' => $this->userpool_id,
        'AuthParameters' => [
            'REFRESH_TOKEN' => $refreshToken,
            'SECRET_HASH' => $hash
        ]
    ];
}

public function refreshToken(string $refreshToken, string $hash)
{
    try {
        $conf = $this->refreshConf($refreshToken, $hash);
        $result = $this->client->InitiateAuth($conf);
        $result = $result->toArray();
        logger($result);
        if (isset($result['AuthenticationResult'])) {
            return [
                'error' => false,
                'message' => 'SUCCESS',
                'data' => $result
            ];
        }
    } catch (\Exception $e) {
        logger(get_class($e));
        return [
            'error' => true,
            'message' => $e->getAwsErrorMessage()
        ];
    }
}

And my function to generate secret hash:
public function cognitoSecretHash($username)
{
    $hash = hash_hmac('sha256', $username . $this->client_id, $this->client_secret, true);
    return base64_encode($hash);
}

Secret hash is stored in User model during registration so I can send it when I want to refresh the token. But every time Aws\CognitoIdentityProvider\Exception\CognitoIdentityProviderException
is thrown. And I get the response Unable to verify secret hash for client d***************9.
So far I've spent hours trying too google the solution. There seems to be a problem with javascript SDK, but no mentions of PHP. I've gone through AWS documentation and can't find what am I doing wrong. I would appreciate any help. Thanks.

A: if the client has client_secret generated, then you have to replace:
'SECRET_HASH' => $hash

with
'SECRET_HASH' => $this->client_secret


text:
Q: Find the poles of this function $$F(z) = \frac{\pi\cot(\pi z)\coth(\pi z)}{z^3}$$
The book says this function has a pole of order 5 at $z=0$
Then the book says this has poles at (simple poles):
$z = \pm 1, \pm 2, \pm 3, ....$
$z = \pm i, \pm 2i, \pm 3i, ...$
I dont get how those are the simple poles, the function isnt undefined at those points.
How should I do this?

A: Other than at $z=0$, the denominator $z^3$ does nothing interesting in terms of causing or cancelling potential poles.  So the non-zero poles of $F(z)$ will be contained in the union of the poles of $\cot (\pi z)$ and the poles of $\cot (\pi z)$.  (One could imagine a pole of one being wiped out by coinciding with at least as strong a zero of the other; for this $F(z)$ that does not happen so the set poles is in fact the union.)
Let's look at the be poles of
$$\cot (\pi z) = i\frac{e^{i\pi z} + e^{i\pi z}}{e^{i\pi z} + e^{i\pi z}}$$
Let
$$
z = n + \delta + i \phi$$
with $n\in \Bbb{Z}-\{0\}$ and $\delta, \phi \in \Bbb{R}$ with $| \delta| \leq \frac{1}{2}$.
A modest amount of algebra, using the fact that $e^{i\pi n} = \pm 1$, yields
$$\cot (\pi z) =i\frac{e^{-\pi\phi}(\cos \delta + i\sin \delta)+e^{+\pi\phi}(\cos \delta - i\sin \delta)}{e^{-\pi\phi}(\cos \delta - i\sin \delta)+e^{+\pi\phi}(\cos \delta - i\sin \delta)}$$
For this to be a pole the denominator must approach zero.  The real part of the denominator can  approach zero only if $\phi \approx 0$ or $\cos \delta \approx 0$. If $\cos \delta \approx 0$ then $|\sin \delta \approx 1$ so the imaginary part of the denominator will approach zero only if $\phi \approx 0$; thus all the poles of $\cot (\pi z)$ lie on the real axis, and are at $z = \pm n$.  These are poles of order 1, stemming from the $\pm x$ behaviors of $\sin(n\pi + x)$ for small $x$.
Similarly, all the poles of $\coth(\pi z)$ lie at $z = \pm i n$.


text:
Q: VPN from a Remote Desktop Session Here's what I'd like to do:  I have a multi-monitor workstation (Vista) at home. I also have a work laptop (XP) with Cisco VPN client 4.8.01.0300.  I want to interact with the work laptop as a window as opposed to just giving it a whole monitor (and keyboard and mouse of its own).
I'd like to remote-desktop into the laptop and then connect the VPN to work, but of course when I connect the VPN the remote desktop session gets closed.
How can I make this work?  Note the home workstation cannot connect to work over the VPN.  It can only be the laptop so that is not an option.

A: So your problem to solve is how to enable LAN access while the VPN is up on your Laptop.
You have to allow this on the server side (VPN server/concentrator.). There is an "allow local LAN access" option (split tunneling) you have to enable. This setting overwrites the VPN client setting.
There is a related (closed) question on Stack Overflow. The answer mentions an alternative VPN client in case your sysadmin doesn't want to enable split tunneling.


text:
Q: How to call an item from graph api fb? I want to select an specific field.item from the requested api call and echo it.for example something like this:
$getlike = $facebook->api("/fql?q=SELECT%20like_info%20FROM%20stream%20WHERE%20post_id=".$id);

$getcm = $getlike['data']['like_info']['user_likes'];
echo $getcm;

The JSON for the above code:
{
  "data": [
    {
      "like_info": {
        "can_like": true,
        "like_count": 70,
        "user_likes": false
      }
    }
  ]
}

When i echo the $getcm,it wont return anything.Is there anything wrong?

A: data is an array; so you should fetch it like-
$getcm = $getlike['data'][0]['like_info']['user_likes'];
echo $getcm;


text: Q: Is chompack not suitable for windows 64 bit machine? I have installed python, cython, cvxopt but failed to install chompack. The error message is Cython does not appear to be installed. But Cython is stalled as when I try to install it says requirement already satisfied. Any suggestion? My machine is windows 64 bit.


text:
Q: Google Analytics same property ID tracked twice Considering the fact that I want both self domain traffic tracking as well traffic tracking across multiple domains, I would like to know if the following implementation is acceptable and if I can keep both GA scripts on a site.
On the contrary, if for some reason this implementation is faulty, I would like advice as to which of the two should be removed in order to avoid tracking the same property ID twice.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', UA-XXXXXXXX-Y', 'auto'); ga('send', 'pageview'); </script>

<script> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXXX-Y']); _gaq.push(['_setAllowLinker', true]); _gaq.push(['_setDomainName', 'ironlawofmarket.com']); </script>

A: You cannot track the same property ids with both Universal Analytics and asynchronous Google Analytics. You would have to look into your account if it's UA or "classical" Analytics and use the appropriate code (look into the property settings and there in the tracking code tab. Since you have UA tracking code in your example I assume that you have UA). It's an either - or decision.
(Or at least it should be - actually accounts that have been switched to Universal Analytics will for some time accept tracking calls from the old tracking code. However this would simply count everything double if used with the same property id).
Bottom line: You should never track to the same property id twice.
You can however use two different versions of the tracking code if they track to different property ids and if the accounts are configured for the respective versions of the code.


text:
Q: iMacros VBScript Error 800A000D Type Mismatch I'm getting an error on a vb script that connects my report database to an iMacros macro for entry to a web form. It is basically the same code as the example from their site (Database-2-Web Script), just with some extra fields. The data types are all varchar. Error message below:
 Script: C:\users\me\path\file.vbs
 Line: 70
 Char: 4
 Error: Type mismatch: 'iimSet'
 Code: 800A000D
 Source: Microsoft VBScript runtime error

Line 70, which is:
 iret = iim1.iimSet("RiskStatusReason", rs.fields(48))

I can't see what makes that line special. It is the same as the others, so why the error here? Any VB pros have answers to this? I am brand new to VBS.
Full code below (I added the cheerleading message):
Option Explicit
dim rs, iim1, sql
dim myname, mypath, connstring
dim iret

dim message
message = "This script reads data from a SQL Server database and submits this information to a web form."
message = message + " It reads from the database <database> and uses the macro <wsh-submit-2-web>." + vbCrLf + VbCrLf
message = message + "Tip: This script has the same function as <file-2-web-method2.vbs> but reads the data from a database instead of a text file." + vbCrLf + VbCrLf
message = message + "Tip: You're incredible, go get 'em tiger."

MsgBox (message)

'Note for x64 users: You must start the VBS script in 32bit mode (C:\Windows\SysWOW64\wscript.exe) for the Microsoft ODBC Driver to work
'Please see the note about VBS scripts on http://wiki.imacros.net/x64 for more details

' find current folder
myname = WScript.ScriptFullName
mypath = Left(myname, InstrRev(myname, "\"))

' open ACCESS database
set rs = CreateObject("ADODB.Connection")

'connstring = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & mypath & "IIM-TEST-SUBMIT.MDB"

'NOTE: To open an SQL database instead of an ACCESS database please use:
'
connstring = "driver={SQL Server};server=server\server1;uid=user;pwd=password;database=database"
'
    rs.Open (connstring)

    ' use SQL to select information
    sql = "select * from _Temp"
    set rs = rs.Execute(sql)

    set iim1= CreateObject ("imacros")
    iret = iim1.iimOpen("")
    iret = iim1.iimDisplay("Submitting Data from SQL Server")

    do until rs.eof
       'Set the variable
       iret = iim1.iimSet("AccountingName", rs.fields(9))
       iret = iim1.iimSet("ReportFileDate", rs.fields(8))
       iret = iim1.iimSet("LastWeekStatus", rs.fields(31))
       iret = iim1.iimSet("CurrentStatus", rs.fields(32))
       iret = iim1.iimSet("TrendingStatus", rs.fields(33))
       iret = iim1.iimSet("Headline", rs.fields(28))
       iret = iim1.iimSet("CostStatus", rs.fields(34))
       iret = iim1.iimSet("CostStatusReason", rs.fields(43))
       iret = iim1.iimSet("ScheduleStatus", rs.fields(35))
       iret = iim1.iimSet("ScheduleStatusReason", rs.fields(44))
       iret = iim1.iimSet("ScopeStatus", rs.fields(36))
       iret = iim1.iimSet("ScopeStatusReason", rs.fields(45))
       iret = iim1.iimSet("TMStatus", rs.fields(37))
       iret = iim1.iimSet("TMStatusReason", rs.fields(46))
       iret = iim1.iimSet("ResourceStatus", rs.fields(38))
       iret = iim1.iimSet("ResourceStatusReason", rs.fields(47))
       iret = iim1.iimSet("RiskStatus", rs.fields(39))
       iret = iim1.iimSet("RiskStatusReason", rs.fields(48))
       iret = iim1.iimSet("BenefitsStatus", rs.fields(40))
       iret = iim1.iimSet("BenefitsStatusReason", rs.fields(49))
       iret = iim1.iimSet("QualityStatus", rs.fields(41))
       iret = iim1.iimSet("QualityStatusReason", rs.fields(50))
       iret = iim1.iimSet("Filename", rs.fields(2))

     iret = iim1.iimPlay(mypath & "Macros\_SRfromSQL.iim")
       If iret < 0 Then
            MsgBox "Error code: "+cstr(iret) + VbCrLf + "Error Text: "+iim1.iimGetErrorText()
       End If
      rs.movenext
    loop

    iret = iim1.iimDisplay("Done!")
    iret = iim1.iimClose
    WScript.Quit(iret)


text:
Q: ibm_db multiline sql query execution issue I am trying to run a multi line query on a DB2 Database using ibm_db via python script. But when the script is executed it is executing as boolean exp instead of a sql statement which is why am not able to get the result. Can anyone help me.
import ibm_db
sql = """ Multi line sql statement with multiple joins across tables """

stmt = ibm_db.execute_immediate(conn,sql)

dictionary = ibm_db.fetch_both(stmt)

print(type(dictionary))

print(dictionary)

Result:
type boolean

False

Whereas when I try to execute a single line statement it is running perfectly fine. I am need help badly. Thanks in advance.

A: not execute_immediate, but ibm_db.exec_immediate https://github.com/ibmdb/python-ibmdb/wiki/APIs#ibm_dbexec_immediate
Show me an example of your multiline query.
In the test code there is a long query and they work. False means that you have an error in the request itself.


text:
Q: считывания чисел из файла с помощью QFile Есть файл вот такого типа
12286 0 4459 11909 0 4760 12265 0 4206 11942 0 5014
12216 0 4472 11969 0 4760 12210 0 4198 12001 0 5029
12205 0 4473 11976 0 4743 12198 0 4208 12010 0 4998
12183 0 4475 11987 0 4741 12177 0 4226 12019 0 4997
12177 0 4501 11990 0 4728 12173 0 4235 12024 0 4976
12165 0 4501 11997 0 4712 12159 0 4242 12029 0 4964
12158 0 4527 12003 0 4707 12151 0 4259 12034 0 4963
12151 0 4509 12006 0 4693 12148 0 4244 12039 0 4956
12145 0 4538 12010 0 4689 12140 0 4270 12043 0 4956
12143 0 4535 12012 0 4687 12138 0 4276 12043 0 4951
12135 0 4545 12014 0 4672 12132 0 4280 12048 0 4928
12134 0 4547 12016 0 4664 12126 0 4279 12048 0 4924
12128 0 4565 12018 0 4666 12124 0 4302 12054 0 4931
12126 0 4566 12021 0 4660 12119 0 4313 12054 0 4907
12123 0 4569 12024 0 4653 12116 0 4309 12056 0 4900
12120 0 4563 12024 0 4654 12113 0 4325 12059 0 4914
12118 0 4573 12026 0 4650 12110 0 4315 12061 0 4902
12113 0 4565 12030 0 4639 12107 0 4317 12062 0 4892
12111 0 4575 12030 0 4651 12109 0 4336 12065 0 4876

Нужно причитать числа с определенной строки с конвертированием в int.

A: Стоит ещё добавить проверку на число, но я этого не делал.
#include <QVector>
#include <QString>
#include <QFile>

QFile file("test.txt");
file.open(QIODevice::ReadOnly);
QVector<int> data;

int currentLine = 0;
while(!file.atEnd())
{
    currentLine++;
    QStringList lineData = QString(file.readLine()).split(" ");
    for(int i = 0; i < lineData.length(); ++i)
    {
        data.push_back(lineData[i].toInt());
    }

    if(currentLine == 2) // доходим, например, до второй строки
        break;
}}


text:
Q: Como puedo obtener mis registros de firebase de 10 en 10? Tengo mi base de datos en firebase y quiero que me regrese los datos de 10 en 10 cada que presione un boton. Como puedo hacer esto?? Estoy programando en android studio y soy nuevo em esto de firebase
Desde ya muchas gracias....
Esto es lo que estoy haciendo pero no me regresa ningun dato

A: Lo que intentas hacer se llama paginacion.
Prueba lo siguiente
mOffset = 0;
mPageSize = 10;

mOffset += mPageSize;

mQuery = mDatabase.child("TU_PATH_FIREBASE")
   .limitToFirst(mPageSize)
   .startAt(mOffset);

En resumen, mPageSize indicas cuantos items quieres leer (campo limitToFirst)
El mOffset te sirve para saber cuantos items ya leiste. Cuando es tu primera lectura, mOffset vale 0 y vas a leer del 0 al 9, y en tu segunda lectura, debes aumentar ese valor a 10 (tamaño de la pagina) para que lea del 10 al 19 y asi sucesivamente


text:
Q: unable to access Jenkins installed on ubuntu 18.10, browser says " xxxxx took too long to respond" a question from a beginner.
I have just installed Jenkins on:

*

*Ubuntu 18.10 minimal - google cloud Platform

*Java 8 installed

*UFW  configured to allow traffic on port 80 from anywhere

when accessing it from the client computer browser through the internet; it says <server IP address> took too long to respond
running netstat -apn|grep 80; i get:
tcp        0      0 10.142.0.3:58216        169.254.169.254:80      ESTABLISHED
tcp        0      0 10.142.0.3:58214        169.254.169.254:80      ESTABLISHED
tcp        0      0 10.142.0.3:58212        169.254.169.254:80      CLOSE_WAIT
tcp        0      0 10.142.0.3:58218        169.254.169.254:80      ESTABLISHED
tcp6       0      0 :::8080                 :::*                    LISTEN
tcp6       0      0 :::80                   :::*                    LISTEN

$ ps aux|grep jenkins
jenkins   6939  0.0  0.4  46188  7856 ?        Ss   11:59   0:00 /lib/systemd/systemd --user
jenkins   6950  0.0  0.1 149060  2744 ?        S    11:59   0:00 (sd-pam)
jenkins   6978  0.0  0.0   4684   156 ?        S    11:59   0:00 /usr/bin/daemon --name=jenkins --inherit --env=JENKINS_HOME=/var/lib/jenkins --output=/var/log/jenkins/jenkins.log --pidfile=/var/run/jenkins/jenkins.pid -- /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8081
jenkins   6979  0.1  9.9 2437292 172520 ?      Sl   11:59   0:28 /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8081
root     12198  0.0  0.2  31912  4300 pts/1    S    16:45   0:00 sudo /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1
root     12199  0.9  8.7 2437292 151936 pts/1  Sl   16:45   0:11 /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1
xcvbtr+ 12375  0.0  0.0   5016   896 pts/1    S+   17:05   0:00 grep --color=auto jenkins

A: Solved, i needed to allow traffic not only from my instance firewall, but also from the cloud platform.


text:
Q: how to run Docker in Travis hosted in travis-ci.com I am trying to run some tests in Travis CI using Docker (and docker-compose).
A search on "run docker in Travis" does yield several how-to-do results, but none of these seem to be running remotely on Travis CI (travis-ci.com), instead I assume are on local Travis.
The answers to the closest question I found, Can travis-ci run docker? , have not helped me so far.
The problem I encounter is that Travis CI runs Ubuntu 12.04 on an outdated kernel and installing Docker requires updating the kernel and rebooting - but 'sudo reboot' will cause the virtual machine to be destroyed and leads to an infinite cycle of [install kernel -> reboot -> install_kernel ...]

A: Just wanted to drop in a quick note that Docker support for Travis CI is now official: http://blog.travis-ci.com/2015-08-19-using-docker-on-travis-ci/
It's support Docker and Docker-compose.

A: https://github.com/moul/travis-docker claims support for Docker in Travis. It apparently uses User Mode Linux to achieve this. I haven't tried this yet.

A: I know it does not help you with travis-ci but I build my docker image on circle-ci. Also Circle-CI just upgraded to docker 1.6.2.
My build file can be found here:
https://github.com/blacklabelops/jenkins/blob/master/circle.yml


text:
Q: Alexa Skill ARN - The remote endpoint could not be called, or the response it returned was invalid I've created a simple Lambda function to call a webpage, this works fine when I test it from the functions page however when trying to create a skill to call this function I end up with a "The remote endpoint could not be called, or the response it returned was invalid." error.
Lambda Function
var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

The Test Event code looks like this:
{
  "url": "http://mywebsite.co.uk"
}

and I've added a trigger for the "Alexa Skills Kit".
The ARN for this function is showing as:

arn:aws:lambda:us-east-1:052516835015:function:CustomFunction

Alexa Skill (Developer Portal)
I've then created a skill with a simple Intent:
{
 "intents": [
   {
 "intent": "CustomFunction"
   }
 ]
}

and created an Utterance as:
CustomFunction execute my custom function

In the Configuration section for my skill I have selected the "AWS Lambda ARN (Amazon Resource Name)" option and entered the ARN into the box for North America.
In the Test -> Service Simulator section, I've added "execute my custom function" as the Text and this changes the Lambda Request to show:
{
  "session": {
"sessionId": "SessionId.a3e8aee0-acae-4de5-85df-XXXXXXXXX",
"application": {
  "applicationId": "amzn1.ask.skill.XXXXXXXXX"
},
"attributes": {},
"user": {
  "userId": "amzn1.ask.account.XXXXXXXXX"
},
"new": true
  },
  "request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.445267bd-2b4a-45ef-8566-XXXXXXXXX",
"locale": "en-GB",
"timestamp": "2016-11-27T22:54:07Z",
"intent": {
  "name": "RunWOL",
  "slots": {}
}
  },
  "version": "1.0"
}

but when I run the test I get the following error:

The remote endpoint could not be called, or the response it returned was invalid.

Does anyone have any ideas on why the skill can't connect to the function?
Thanks

A: The Service Simulator built into the Amazon Alexa Developer Console has known issues.  Try copying the JSON generated by the Simulator and pasting it into your lambda function's test event.  To access lambda's test events first find the blue 'Test' button.  Next to that button select the (Actions Drop down menu) -> (Configure Test Event) -> Paste the provided JSON into the code area -> (Save and Test). Lambda's built in testing features are much more reliable than Alexa's.
If this does not solve the problem lambda's testing event returns a complete stackTrace and error codes.  It becomes much easier to trouble shoot when every error isn't "The remote endpoint could not be called, or the response it returned was invalid."
{
  "session": {
"sessionId": "SessionId.a3e8aee0-acae-4de5-85df-XXXXXXXXX",
"application": {
  "applicationId": "amzn1.ask.skill.XXXXXXXXX"
},
"attributes": {},
"user": {
  "userId": "amzn1.ask.account.XXXXXXXXX"
},
"new": true
  },
  "request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.445267bd-2b4a-45ef-8566-XXXXXXXXX",
"locale": "en-GB",
"timestamp": "2016-11-27T22:54:07Z",
"intent": {
  "name": "RunWOL",
  "slots": {}
}
  },
  "version": "1.0"
}

A: While uploading .zip, do not compress the folder into .zip.
Instead, go into the folder, select package.json, index.js and node modules & then compress them and then upload the .zip.

A: This error message is very broad and may imply a lot of different issues. I was getting this error and in my case it was a timeout issue. How long does that website you are pinging taking to respond? The timeout doesn't seem to be properly documented, see my original question here: Troubleshooting Amazon's Alexa Skill Kit (ASK) Lambda interaction


text:
Q: What explains this bulb/motor behavior? My son was building circuits with a hobby kit.  He tried connecting a small DC motor and incandescent bulb in series with two batteries.  The motor is not marked, probably is rated at no more than 6V.  The lamp is marked 3V.
The motor shaft spun, but the bulb did not illuminate.  When he added a fan blade to the motor, we were both surprised to see that the lamp turned on.
I know that neither the lamp nor the motor can be explained with Ohm's law, but beyond wildly guessing that the motor increases the circuit's current as it has to work harder I couldn't get very far.
We are both happy to figure this out on our own but need a nod in the right direction.  I have a multimeter and a good selection of resistors if that would help us.  What kind of an experiment or demonstration could we try to help us understand?

A:
but beyond wildly guessing that the motor increases the circuit's
current as it has to work harder I couldn't get very far.

It's a good guess because it is correct.
The motor draws more current because it is shifting air with the fan. In other words, it is producing a mechanical output power and, that power is supplied by the battery and, that means it has to take more current.
Another good test is to hold the shaft to prevent it from rotating. No mechanical output power is being produced (because the motor shaft is stalled) but, the motor will act a bit like a short circuit under these circumstances and the lamp will glow to near-full brightness.

A: To add to the other responses. When the motor is starting up (no fan) it accelerates until the motors back EMF equals the battery voltage. At this point the motor spins at steady state speed and consumes very little current. Only enough current to overcome the bearing friction. When the back EMF and battery voltage are approximately equal there is only a small voltage drop across the lightbulb (hence small current flow and a very dimly lit light).
When you put a load (connect a fan) on the motor. The speed is reduced. Thus, the back EMF, which is proportional to speed) is now less than the battery voltage. The rest of the voltage drop (which is bigger now) occurs across the lightbulb. A bigger voltage drop means more current is flowing. Hence the light will be brighter.

A: The motor behavior can be also explained in terms of "armature reaction".
Think of the electric motor also as an electric "generator" producing a voltage proportional to the speed and opposing the input voltage. So at normal speed, the current is lower and the lamp will glow less.
If the speed slows down (due to increased load), this "anti voltage" will decrease, the current will increase and the lamp will glow brighter.
This mechanism reminds the so-called "bootstrapping" technique in electronic circuits where the output voltage is subtracted from the input voltage. As a result, the current enormously decreases (as though the input resistance has increased).
If you are meticulous enough, you can also take into account the non-linear behavior of the lamp - the more it heats up, the more its resistance increases.  Thus, it acts as a current-stabilizing nonlinear resistor.

A: For an ideal motor, speed and voltage are proportional to each other, as are current and torque.
A small low voltage motor will be far from ideal, but the general relationship still holds.
With no load on the shaft, the torque and hence current will be very low (zero in an ideal motor), with little voltage dropped across the bulb, and a high voltage across the motor, reflecting its high speed.
As you increase the load on the shaft, the current increases as the torque output increases.
As you slow the motor down, the voltage across the motor decreases, resulting in more voltage across the bulb, which increases the current.
If you stall the motor, safe to do as you have a current-limiting bulb in series, the voltage across the motor will be small (zero in an ideal motor), and the current through it high.

A: Congratulations on asking a great question.
The discussion point here is Kirchhoff's Current Law, KCL. In context, the current through the motor is the same as in the lamp. More current in the motor: more current through the lamp. More current in the lamp: more better brighter the bulb.
As you begin to experiment further, a lamp wired this way is pretty good idea to limit current through your test circuit. Search on "smoke stopper" or "load bulb" for more info!


text:
Q: Spring Authorization Server use additional parameters from authorization request for login So basically, what I want is that following request:
http://127.0.0.1:9000/oauth2/authorize?response_type=code&client_id=test-client&redirect_uri=http://127.0.0.1:8080/authorized&scope=message.read&state=someState?color=red
is for example redirected to http://127.0.0.1:9000/login?color=red, so that I can access the color parameter for rendering the login page. The color parameter does not necessarely have to be in the URL, it should just be acessible in Thymeleaf.
It this possible?

A: One easy way to accomplish this is to provide a custom AuthenticationEntryPoint that reads the parameter color and adds it to a redirect to /login. I have an example that does something like this in the Federated Identity sample. Your implementation would be simpler in that you only want to append ?color=... to /login, and don't require any of the other code in that example.
You can see the entry point applied here.


text:
Q: How to get data attribute value in component.ts in angular 2 I am trying to get value of data attribute inside component.ts in angular2.
1) form2.component.html
<md-select  placeholder = "BedRooms" [formControl]="userForm.controls['bedRooms']" >
    <md-option #bedRoom  *ngFor="let bedRooms of formSettings?.prices?.pricingParams?.bedRooms" [value] = bedRooms.title [attr.data-price] = bedRooms.price (click)="test(bedRoom)"> {{bedRooms?.title}} </md-option>
</md-select>

How to get value of data-price in test function?

A: You can access the value of data-price from reference bedRoom as below.
bedRoom.getAttribute('data-price');


text:
Q: Fastest way to add columns when there in inter-row dependency? I am working on a problem that has a dataframe with family information. Each family is made of one or more parents and children. Each person has a unique UserID and each family has a unique FamilyID. One person can belong to only one family. The Type column indicates whether the person is parent or child and Age indicates age of the user.
I would like to add a column called ParentAge for children that indicates the age of the oldest parent.
import pandas as pd
import numpy as np

#example data
df = pd.DataFrame([[1, 22, 'Child', 8],
                   [1, 62, 'Parent', 36],
                   [2, 102, 'Child', 6],
                   [2, 103, 'Child', 10],
                   [2, 107, 'Parent', 40],
                   [2, 108, 'Parent', 42]],
                  columns=['FamilyId', 'UserId', 'Type', 'Age'])

expected_result = pd.DataFrame([[1, 22, 'Child', 8, 36],
                   [2, 102, 'Child', 6, 42],
                   [2, 103, 'Child', 10, 42]],
                  columns=['FamilyId', 'UserId', 'Type', 'Age', 'ParentAge'])

Here is what I have tried so far (I've tried few other ways, but the perf is roughly similar)
parents = df.query('Type=="Parent"')
children = df.query('Type=="Child"')

oldest_parents = parents.groupby('FamilyId') \
    .apply(pd.DataFrame.nlargest, n=1, columns='Age') \
    .reset_index(drop=True) \
    .rename(columns={'Age': 'ParentAge'})

pd.merge(children, oldest_parents[['FamilyId', 'ParentAge']], on='FamilyId')

The method above works, but for a dataframe to close to a million rows, its taking 20+ hours to complete. All other techniques were in the same ballpark. It took me couple seconds to do this in R using dplyr library. I was wondering if there is a faster way to accomplish this?

A: Option 1: Try groupby().max() instead of apply:
df[df['Type'].eq('Child')].merge(df[df['Type'].eq('Parent')].groupby('FamilyId').Age.max(),
                                 on='FamilyId',
                                 suffixes=('','Parent'))

Option 2: Fastest, assuming oldest parent is also the oldest in family:
df['Parent_Age'] = df.groupby('FamilyId').Age.transform('max')
df[df['Type'].eq('Child')]

Option 3: Faster, without assuming parents are oldest (e.g., grant parents):
df['Parent_Age'] = (df['Age'].mul(df['Type'].eq('Parent'))
                             .groupby(df['FamilyId']).transform('max')
                   )
df[df['Type'].eq('Child')]

Output:
   FamilyId  UserId   Type  Age  AgeParent
0         1      22  Child    8         36
1         2     102  Child    6         42
2         2     103  Child   10         42


text:
Q: NSTableView data disappears when print panel settings are changed I am trying to print data populated in an NSTableView through a custom NSView.  When the print command is issued by the user, the custom NSView containing the NSTableView is shown in the Print Panel as expected
The problem I am encountering is as follows: if the user changes any settings in the Print Panel, the data populating the NSTableView is blanked out.  The same thing happens if the user clicks Print.  My question: how do I make the data not disappear when the user interacts with the Print Panel?
Additional Information: (1) There are labels in the NSView that appear as expected, and (2) If I bypass the Print Panel, by issuing [printOp setShowsPrintPanel:NO]; [printOp runOperation]; the data in the NSTableView prints as expected.
Speculation: I am in the process of updating my program to use Automatic Reference Counting (ARC).  It almost seems as if the pointer to the data is being released early, such that when the user interacts with the Print Panel the data is not longer available to the NSView; but I am not able to determine where that happens (my code is not being accessed, as far as I can tell, after the Print Panel is first presented).
Any help would be greatly appreciated.  Thank you.  Attached is some of the code to help in diagnosis.
From MyDocument.m (subclass of NSDocument), the code that kicks off the print operation:
-(NSPrintOperation *)printOperationWithSettings:(NSDictionary *)ps error:(NSError **)e
{
    DeductionTablePrintViewController *pvc = [[DeductionTablePrintViewController alloc] initWithScopeDeduction:deduction andHelper:helper andDeductionController:self];

    NSPrintInfo *printInfo = [self printInfo];

    NSRect viewFrame = [[pvc view] frame];
    viewFrame.size.width = [printInfo imageablePageBounds].size.width;
    [[pvc view] setFrame:viewFrame];

    NSPrintOperation *printOp = [NSPrintOperation printOperationWithView:[pvc view] printInfo:printInfo];
    return printOp;
}

DeductionTablePrintViewController is a subclass of NSViewController used strictly for printing.  There is a corresponding xib file.  From DeductionTablePrintViewController.h (hooked up to the xib:
IBOutlet DeductionTable *deductionTable;

Now for DeductionTablePrintViewController.m:
-(id)initWithScopeDeduction:(ScopeDeduction *)aDeduction andHelper:(DeductionHelper *)aHelper andDeductionController:(MyDocument *)aDeductionController
{
    self = [super initWithNibName:@"DeductionTablePrintView" bundle:nil];
    if (self) {
        // Set deduction
        deduction = [aDeduction copy]; // Deep copy
        deductionController = aDeductionController; // MyDocument

        [[(DeductionTablePrintView *)[self view] deductionTable] setDeduction:deduction];
    }
return self;
}

-(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)row
{
    id objectValue = nil;

    // objectValue is calculated here
    ... ... ...
return objectValue;
}

*

*Here is the 'before' screenshot, with the table data in the print preview (and from here, the print output) being properly populated.

*Here is the 'after' screenshot, with the table data in the print preview (and from here, the print output) having disappeared after clicking the "Pages: From  to " radio button.

A: The view controller was being deallocated by ARC, as suggested by Willeke above (thank you).  The solution was to add to MyDocument.h:
DeductionTablePrintViewController *pvc;

And then changing the method printOperationWithSettings to read:
-(NSPrintOperation *)printOperationWithSettings:(NSDictionary *)ps error:(NSError **)e
{
    pvc = [[DeductionTablePrintViewController alloc] initWithScopeDeduction:deduction andHelper:helper andDeductionController:self];
    .... ....
}

Once the referent was no longer being deallocated, the Print Panel worked as expected.
Additional Information: An interesting aspect of this problem is that the view controller was deallocated after the Print Panel appeared, so the panel had time to create a print preview, but then did not have access to the data for the table.  Also, I think the reason the formula, deduction identifier, and tableview (see pictures above) still appear after the view controller was deallocated was that the once they were drawn onto the view the Print Dialog did not try to redraw them.  But the Print Panel repeatedly reads in data for the table with calls to tableView:objectValueForTableColumn:row.  Further frustrating attempts to diagnose this problem were two things: (i) when the Print Panel calls tableView:objectValueForTableColumn:row on a deallocated view controller, no warning or error is issued, but instead fails silently; (ii) when I inserted a breakpoint in tableView:objectValueForTableColumn:row the debugger breaks before the Print Panel is shown to the user but not once the view controller is deallocated.  This latter behaviour makes sense, since it is deallocated and the code cannot be run; but this led me to believe the Print Panel only sent messages to tableView:objectValueForTableColumn:row in the initial setup.


text:
Q: Non english file names saved in server shows as? When i upload non english files from an application deployed in portal server .After the file is saved .The file name changes to ??????. i have added the savefile function code for reference which gets called on saving file
The Non english filename gets printed correctly in the logger wherever the logger is given to print the filename . But the filename gets saved in the server as ????.
public void saveFile(java.io.InputStream is, String fileName, String fpath, String remoteUser, String uiniqueId, String fileSize)
{
    logger.info("fileName: "+fileName);
    logger.info("fpath: "+fpath);
    logger.info("remoteUser: "+remoteUser);
    logger.info("uiniqueId: "+uiniqueId);

    //Define upload directory, notice that permissions to write are needed for upload directory
    String uploadDir = getBaseDir() + fpath;
    String fullFileName = uploadDir+"/"+fileName;

    String filePath = uploadDir + "/"+uiniqueId;
    logger.info("filePath: " + filePath);
    //write to disk
    //Process a file upload
    File uploadedFile = new File(fullFileName);
    File bFile = new File(uploadDir+"/"+ ".mpbac." + fileName);

    if(fileName.lastIndexOf(".war")==-1) {
        if(uploadedFile.exists()) {
            if(bFile.exists()) {
                //if uploaded file is different from backup file
                if(uploadedFile.lastModified()!=bFile.lastModified()) {
                    File orig_uploadedFile = new File(fullFileName);
                    File thisbackupFile = new File(uploadedFile.getParent() + "/.mpbac."+fileName);
                    thisbackupFile.delete();
                    orig_uploadedFile.renameTo(thisbackupFile);
                    logger.info("orig_uploadedFile:" + orig_uploadedFile.getAbsolutePath());
                    logger.info("thisbackupFile:" + thisbackupFile.getAbsolutePath());
                }
            }
        }
    }

    OutputStream os = null;
    try
    {
        File dst = new File(filePath);

        if (dst.exists()) {
            os = new BufferedOutputStream(new FileOutputStream(dst, true),
                    40960);
        }else {
            os = new BufferedOutputStream(new FileOutputStream(dst),
                    40960);
        }
        byte[] buffer = new byte[40960];
        int len = 0;
        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        logger.info("File touch starting...: " +filePath);
        FileUtils.touch(new File(filePath));

        logger.info("File write done successfully...: " +filePath);

    }
    catch (IOException ex) {
        ex.printStackTrace();
        logger.log(Level.SEVERE,"saveFile>> IOException  "+getStackTrace(ex));
    }
    catch(Exception exp)
    {
        logger.log(Level.SEVERE,"saveFile>> Exception "+getStackTrace(exp));
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ex) {
            }
        }
    }

    //Renaming and writing backup files
    try
    {
        //Renaming files
        File file = new File(filePath);
        logger.info("Testing file length::" + file.length());
        if (file.length() >= Integer.parseInt(fileSize)) {
            File renameFile = new File(fullFileName);
            boolean isDeleted = false;
            //if same file already existing, delete it first.
            if(renameFile.exists())
            {
                isDeleted = renameFile.delete();
                logger.info("Existing file- "+fullFileName+" has been deleted");
            }
            else
            {
                isDeleted = true;
                logger.info(fullFileName+" NOT exist to delete.");
            }
            //Renaming started
            if(isDeleted)
            {
                boolean isSuccess = file.renameTo(new File(fullFileName));
                if(isSuccess)
                {
                    logger.info("File renamed to "+fullFileName);
                }
                else
                {
                    logger.info("NOT able to rename- "+fullFileName);
                }
            }
        }

        Action action = new Action();
        action.action = Action.IMPORT;
        action.user = remoteUser;
        action.path = fpath;
        action.description = action.user + " importing " + fileName + " to " + action.path + " in Import Operation";
        AuditManager.getInstance().logAction(action);

        //create new backup file
        if(fileName.lastIndexOf(".war")==-1) {
            if(!bFile.exists()) {
                logger.info("Attempting to new backup file for " + fullFileName);
                File uploadedFiletemp = new File(fullFileName);
                //rename current for backup
                String path = uploadedFiletemp.getParent();

                File backupFile = new File(path + "/.mpbac."+fileName);
                //FileUtils.copyFile(uploadedFile,backupFile);
                logger.info("New Backup file write done successfully : " + path + "/.mpbac_"+fileName);
            }
        }
    }
    catch(Exception exp)
    {
        logger.log(Level.SEVERE,"saveFile>> Exception while renaming or writing backup files- "+getStackTrace(exp));
    }

}


text:
Q: Add dependency on a local swift package in Xcode 11 I am trying to add a dependency on a local swift package in my Xcode project. (I don't want to add a dependency using a file url file://me/dev/app/package as this cannot be shared to other environments)
I tried to drag & drop the package to the target. This creates a references to the package in the project that I was able to add in the "Link Binary With Libraries" build phase, but the library is still not found.
No such module 'Analytics'

My original configuration

After drag & drop

and here is my package configuration:
// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "Analytics",
    products: [
        .library(name: "Analytics", targets: ["Analytics"]),
    ],
    dependencies: [
        .package(path: "../SomeOtherPackage"),
    ],
    targets: [
        .target(name: "Analytics", dependencies: [
            "SomeOtherPackage",
        ]),
    ]
)

I've also included the Package in the target linked binaries and/or bundle resources and/or compiled sources to no avail:

I've read this long discussion that doesn't seem to be conclusive.
Here is a simple example of what I'm trying: https://github.com/gsabran/SPM_Xcode_test

A: Here is literally what I do and it just works... Xcode 11.2
I. Prepare package

*

*File > New > Swift Package > Select Empty Folder (or create new) > Enter Library Name (MyLibrary)

*Here in project find MyLibrary.swift and make public structure & variable, so there is some export to use in app (I made static constant and fixed UT)

*Build > OK > Close Project
II. Prepare project

*

*File > New > Project > iOS > Single View App > Enter Name (MyApp) > Next > Select Same Folder as above (it is by default) > Create

*Build > OK

*From Finder drag MyLibrary folder right below project name in Xcode Project Navigator

*Build > OK

*Click MyApp project icon in Project Navigator > Select MyApp application target > section Frameworks, Libraries, … click + > In topmost Workspace section select MyLibrary > Add

*Clean > Build > OK

*Open ContentView.swift > type import MyLibrary (autocompletion already see it)
Replace "Hello, World" with "(MyLibrary.text)"

*Build & Run > OK
That's it.
To verify used relative path open project.pbxproj in TextEdit, here is screenshot

Update:
Note1 - I've considered some delay in package resolving after Clean, so during some period of time, 1-2 mins here, Build fails exactly with reported error, but after that delay it is visible that index restarted and following Build succeeded.
Note2 - Adding second dependent package in graph (MyApp > MyLibrary > AnotherLibrary) is the same.


text:
Q: How to find pairs of slightly differing file names with similar core names using python I have a list of files with similar basenames, some of which are slightly differing.
Atwood_1_F ,
Atwood_1_B ,
Atwood_1_F2 ,
Atwood_1_B2
I need to find a way to create a list of paired values. The basename in the above list are Atwood_1 and Atwood_2. In this specific list, I would need to create 2 sets of  pairs with the same baseline:
Pair1: should contain Atwood_1_F & Atwood_1_B
Pair2: should contain Atwood_1_F2 & Atwood_1_B2
This is a small subset of several needed pairs. Does anyone have any ideas of ways to create these pairs in python?

A: So if I am understanding you correctly, you need to end up with 2 lists? Or is it you need 2 variables containing the files? In either case the method startswith() should start you out. Just call it on your lists (or otherwise), and set what you want the string to start with. Unless I am misunderstanding your question, you should be able to use the method as such:
    if str.startswith("Atwood_1_F", beg=0,end=len(string)-1);
    elif str.startswith("Atwood_1_B", beg=0,end=len(string)-1); //the -1 in both statments only serve to denote the F from F2 as len(string)-1 on F will be "_" but the same from F2 will be "F"
    Pair1.append(str)

You just need to then similarly append Pair2, and that should answer your question, if I understood it. Let me know if I helped.


text:
Q: How do I download a file given the URL in C# I am trying to download a file from a URL and I want to have a Popup where I can decide where to save the file on my pc. I know how to save it to a setlocation but that's not what I want.
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("URL"), @"d:\location");

So I get that this is how I download it so a set location but I need to be able to save it to a location of choice with the usual popup you normally get when you download anything.
To give more sight into this I have 2 radiobuttonlists in which the user can check what topics he wants then he can choose from a dropdownlist which file he wants to download and then he click on a downloadbutton which should trigger the download of that file.

A: Use DownloadFileAsync and listen to DownloadFileFinished. First download it to temp file and at event DownloadFileFinished, show popup and ask where to save. Then just copy the file from temp file to the filename from user.
-or-
Show SaveFileDialog before you start DownloadFileAsync.

A: Talking about a desktop app you can use SaveFileDialog.
The msdn code example:
    private void button1_Click(object sender, System.EventArgs e)
 {
     Stream myStream ;
     SaveFileDialog saveFileDialog1 = new SaveFileDialog();

     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;
     saveFileDialog1.FilterIndex = 2 ;
     saveFileDialog1.RestoreDirectory = true ;

     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         if((myStream = saveFileDialog1.OpenFile()) != null)
         {
             // Code to write the stream goes here.
             myStream.Close();
         }
     }
 }


text:
Q: Motivation of Fourier Coefficents What motivates the definition of the definition of the Fourier coefficients? I understand that one would try to find Fourier coefficients, but not why they are defined the way they are.

A: The original motivation came from solving the problem of a vibrating string stretched between fixed endpoints, which arose in the mid to late 1700s. In the process of studying this equation, Mathematicians discovered standing wave solutions vibrating at frequencies that were integer multiples of a base frequency. (This is origin of harmonic analysis.) In order to solve a general problem with a more general initial displacement of the string using sums of such standing wave solutions, it became necessary to determine the coefficients for those solutions in a general sum
Clairaut and Euler discovered a way to isolate the coefficients through the amazing discovery of the orthogonality conditions for trigonometric functions. Most Mathematicians at the time thought that such a general expansion of initial displacement of the string into trigonometric functions would not be possible. So, there was a consensus that this represented a restriction on the problems that could solved, and not a way to find general solution of the vibrating string problem.
Fourier became convinced that a general "mechanical" function representing the initial position of the string would have to be expandable in such a way. Because of the work of Fourier in this direction, the coefficients were named after Fourier, even though Fourier did not discover them. Fourier extensively studied trigonometric expansions.


text:
Q: Sitecore Solr Search on data sourced sublayouts I have a page item which has sublayout which is data sourced to data item, My question is If I used solr search to search for a term that is contained within the content of the data item; Should the page item be returned by solr search or should I apply custom code to do that?
I am using sitecore 7.2 and solr version is 4.10.2-0.

A: SOLR will return whatever you index, in this instance since it is just an item then it will return the item itself and not the link to the page that this item is referenced on.
Instead what you need to do is index the datasourced items as part of the main content item on which they are referenced. You can either do this as a post-processor/computed field or use a module like Sitecore Datasource Indexer.


text:
Q: PowerShell: how to capture (or suppress) write-host I have a script call "a.ps1":
write-host "hello host"
"output object"

I want to call the script and obtain the output object, but I also want the standard output to be suppressed:
$result = .\a.ps1
# Don't want anything printed to the console here

Any hint?

A: There really is no easy way to do this.
A workaround is to override the default behavior of Write-Host by defining a function with the same name:
function global:Write-Host() {}

This is very flexible. And it works for my simplistic example above. However, for some unknown reason, it doesn't work for the real case where I wanted to apply (maybe because the called script is signed and for security reasons it doesn't allow caller to arbitrarily change the behavior).
Another way I tried was to modify the underlying Console's stdout by:
$stringWriter = New-Object System.IO.StringWriter
[System.Console]::SetOut($stringWriter)
[System.Console]::WriteLine("HI") # Outputs to $stringWriter
Write-Host("HI") # STILL OUTPUTS TO HOST :(

But as you can see, it still doesn't work.

A: OK, I did a little digging over it. You can use:
The Following Link
And do:
$result = .\1.ps1 | Select-WriteHost -Quiet
$result[1]

And then select the second object in the variable:
Another explanation
You can also change the script in a way that will not change Write-Host to Write-Output and just "remove" the Write-Host.
Done...
function Remove-WriteHost
{
   [CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
   param(
     [Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')]
     [object] $InputObject,

     [Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)]
     [ScriptBlock] $ScriptBlock
   )

   begin
   {
     function Cleanup
     {
       # Clear out our proxy version of Write-Host
       remove-item function:\write-host -ea 0
     }

     function ReplaceWriteHost([string] $Scope)
     {
         Invoke-Expression "function ${scope}:Write-Host { }"
     }

     Cleanup

     # If we are running at the end of a pipeline, need to
     # immediately inject our version into global scope,
     # so that everybody else in the pipeline uses it.
     #
     # This works great, but it is dangerous if we don't
     # clean up properly.
     if($pscmdlet.ParameterSetName -eq 'FromPipeline')
     {
        ReplaceWriteHost -Scope 'global'
     }
   }

   process
   {
      # If a scriptblock was passed to us, then we can declare
      # our version as local scope and let the runtime take it
      # out of scope for us. It is much safer, but it won't
      # work in the pipeline scenario.
      #
      # The scriptblock will inherit our version automatically
      # as it's in a child scope.
      if($pscmdlet.ParameterSetName -eq 'FromScriptBlock')
      {
        . ReplaceWriteHost -Scope 'local'
        & $scriptblock
      }
      else
      {
         # In a pipeline scenario, just pass input along
         $InputObject
      }
   }

   end
   {
      Cleanup
   }
}
$result = .\1.ps1 | Remove-WriteHost

Thanks to "latkin" for the original function :)

A: The output object i.e. "output object" is output to standard output. So I don't think you want to suppress standard output.  If you don't want anything printed to the console don't use Write-Host as that bypasses all streams (stdout, stderr, warning, verbose, debug) and displays directly to the host.  There is currently no easy mechanism I'm aware of to redirect host output.
BTW why do you need to write "hello host" to the console if you don't want to see it displayed later?


text:
Q: Alternative To Page Refresh PHP I'm working on learning PHP and I wanted to make a clock with some crypto-like number images I made.
The problem I'm running in to is that I want the clock to be updated every second but without refreshing the page. So my question is, how would you suggest I go about doing this?
Right now I use the HTML page refresh which causes my images to flicker every reload.
Thank you in advance for your help!
Code below:

        <meta http-equiv="refresh" content="0.5" >

    <?php
        date_default_timezone_set('America/New_York');
        $hour = date(H);
        $minutes = date(i);
        $seconds = date(s);

        echo '';
        echo '';
        echo '';
    ?>

A: This  can be  done  with Javscript , Ajax or Jquery whichever you have  experience  with .Only php is not  sufficient  enough  to  do  this as  without  refreshing  you can't request  something from the  server  without  ajax.

A: You can (only) use Javascript:
(i added alt tag, because the images obiously can't be loaded here)

setInterval(function(){
  var date = new Date();

  var hr = date.getHours();
  var min = date.getMinutes();
  var sec = date.getSeconds();

  //document.getElementById("hours").src = "images/" + hr + ".png";
  document.getElementById("hours").alt = hr;
  //document.getElementById("minutes").src = "images/" + min + ".png";
  document.getElementById("minutes").alt = min;
  //document.getElementById("seconds").src = "images/" + sec + ".png";
  document.getElementById("seconds").alt = sec;
},1000)

  :
  :

be aware that you should preload the images!
JS:
//before starting the interval:
var preloadedImages = [];
for(var i=0;i<60;i++){
    preloadedImages[i] = new Image();
    preloadedImages[i].src = "images/"+i+".png";
}

whis way, the browser keeps them in memory, so you won't have a flickering second counter when the images are loaded for the first time
[EDIT]:
By the way....avoid this:
$hour = date(H);
$minutes = date(i);
$seconds = date(s);

should be this:
$hour = date("H");
$minutes = date("i");
$seconds = date("s");

else they will be checked as constant variables and print out a notice, which will spam your logs, if you have the log level low enough...also, it needs more processing time (no big deal with only three calls, but is accumulative if used more often...)

A: The sad news is that php cannot do it. This happens because php was made do be a pre-processed script. That means that when you access a php page, the server will read that code, execute all the lines internally and, if there is any output, it will be sent to your browser. You HTML code is actually an output of your php script. Is VERY important to understand this when learning php.
The output can be an HTML text, JavaScript, only text or even images. What is important to have in your mind is that any output will only be shown at your browser after the server is done with reading your code. So any dynamic action can't be done using php. When you need dynamic, you need JavaScript.


text:
Q: Visual Basic Loop Through Array of Strings I am trying to extract a sub string from a string using Visual Basic.
This is what I have tried:
Dim TestString = "Aberdeen, 1"
for i = 0 to TestString.length-1
debug.print(teststring(i))
next

What I would like to do is loop through the TestString so that it only extracts and prints the words "Aberdeen" WITHOUT the comma and the number 1.  So far, all the characters are getting added.
Any help much appreciated.

A: Assuming you are using VB.NET, you can create a LINQ statement which will take characters from the string until (but not including) it finds a comma:
Dim TestString = "Aberdeen, 1"
Dim toComma = TestString.TakeWhile(Function(c) c <> ","c)
For Each c In toComma
    Debug.WriteLine(c)
Next

If you know that there is a comma, it could be:
Dim toComma = TestString.Split({","c}, 2)(0)

Or:
Dim toComma = TestString.Substring(0, TestString.IndexOf(","c))


text:
Q: jQuery attribute value encoding I would like to set tag title attribute with text that contains characters which break html structure. I have encoded some special characters using jQuery parser, but title text also includes quotes ". Do I have to encode them by myself or I can expect jQuery will take care of that when I will use .attr() function?
In this example quotes are not encoded: https://jsfiddle.net/a76nxrz4/2/
jQuery('div').attr({ title :'Some text with
html
 ""'});

As I explore DOM I see:

  simple div container

Am I doing something wrong or this is expected behavior (no encoding for quotes)?
It Man


text:
Q: Visual Studio Project Favicon After migrating a template over to my visual studio web application, I can't seem to get the favicon to work. The icon is 16x16, is named favicon.ico, and is placed in the Content/images directory of my project. I've made references to other images with this path that work fine. Any ideas?
 <link runat="server" rel="icon" href="../Content/images/favicon.ico" type="image/ico" />

A: Well if it doesn't work, there's only one option - your path is wrong.
Try this:
<link runat="server" rel="icon" href="~/Content/images/favicon.ico" type="image/x-icon" />

Also, the type is "image/x-icon"...

A: Traditionally (a hangover from the first use of favicon.ico) it should be placed at the root of the website.
The image/x-icon is for IE.
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

For the following browsers it is best to still be in the root...
Google Chrome   Internet Explorer   Safari
For the following browsers it is optional to be in the root...
Firefox     Opera

A: Clearing your cache may fix this.

A: Add ?v=2 to your href
for example: <link rel="icon" href="favicon.ico?v=2" type="image/x-icon"/>
Some browsers try to  cache previous versions of the "favicon.ico".This addition overrides that functionality  if they didn't exist. I ran in to this using Live Server in VSCode editor, it works!


text:
Q: How to debug python code using vs code by attaching to a running container (without Dockerfile)? I want to be able to debug python code in D:\Tools\sima\source after running :
docker run --rm -it -v ${PWD}:/mnt -w /mnt sima-sdk:latest /bin/bash
Then I open VSCODE and do attach to running container.
This opens a second VS Code window in that container as shown in the picture below : enter image description here
Then I select the python interpreter within the docker /usr/bin/python3
Now I want to run the debugger. I creates a  launch .json file as below
    {
        // Use IntelliSense to learn about possible attributes.
        // Hover to view descriptions of existing attributes.
        // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Python: Current File",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal",
                "justMyCode": true
            }
        ]
    }

and my python code is very simple :
    a = 4
    b = 7
    c = a* b
    print("c is equal to", c)
    print("Hello test 1 ")
    print("Hello test 2")

When I set a breakpoint in the python code editor and run the debugger, nothing seems to happen although the variable and watch windows are showing up
enter image description here
Can I get hep to understand what I am doing wrong  if anything please?
I have googled a lot without results
Thanks in advance

A: Set your "justMyCode:false". This can make your code sotp at breakpoint:
{
    "name": "Python: Current File",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "justMyCode": false,
    "console": "integratedTerminal"
}


text:
Q: php postgresql using cache
*

*I have a php page with lot of queries and takes 2-3 minutes to load.

*The database to which queries are hiting is updated once a month (1st
of every month).

*The page hits different schemas of database depending on user selection (User selects options from select box depending on which different schema's of db are used).

*So, if the database is updated once a month, means after that same result per input selection are displayed till next month.
Is there any solution (caching etc.) so that if any of the client has generated that page, it is used for remaning days instead of hitting queries again ?

A: 2-3 minutes it's too long, this means your database is not optimized. You should make right indexes for your tables, need to analyze your queries and according to it create indexes for tables.
Also you can create temporary view which will contain data from your most frequent queries. Refresh it once per month or every big update of your data in DB.
Create cron task which will be executed once per month to recreated updated view. Then make queries from that generated view.
Also you can think about replication if there are a lot of select queries, try to separate them between several servers to reduce the load.

A: Sounds like you might be able to just write the output to a file and just have a seperate command line script that generates the reports once a month.
A example of someone doing this in php is at https://www.sanwebe.com/2013/09/php-cache-dynamic-pages-speed-up-load-times, although I'm sure there are lots of others out there :)


text:
Q: How to use SessionStorage for a chrome extension I am making a Google Chrome Extension and i'm having an issue figuring out how to use the sessionStorage ability:
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
This is the Code i have from the link above:
    /* Session Storage */
    sessionStorage.setItem('inputtextB', 'inputtext');

// Get the text field that we're going to track
var field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
  // Restore the contents of the text field
  field.value = sessionStorage.getItem("autosave");
}

// Listen for changes in the text field
field.addEventListener("change", function() {
  // And save the results into the session storage object
  sessionStorage.setItem("autosave", field.value);
});

"inputtext" is the textarea i want to save. I just want its current state to be remembered. As i understand this will make a copy of "inputtext" every time it changes and save it to "inputtextB", then if the pages reloads (But not closes) It will replace "inputtext" with "inputtextB".
my confusion is that i do not know how to make this work, I've been working with this all day and can't figure it out. I dont want this to persist if chrome shuts down only if i open/close the popup, or i reload the current page.
I have looked over a few things and these are close but i don't know if these are exactly what i want to happen.
HTML5 sessionStorage or chrome.storage for Chrome Extension? I think this might be the closest?
Chrome Extensions - Saving Settings
Chrome Extension: How to persist data in popup across popup clicks
I hope i can get a little help to figure out the best way to do this.
Edit:
What happens is you enter text Then you press a button and it parses it for use in HTML.
Example of how this works:
( Hi, how are you? ) and it outputs-
(Hi, how are you? )

When using Inspect popup this shows:
https://i.gyazo.com/9effdfac3e8b38ba7aa3908189ec50a4.png
since i added the above code whenever i press the button to parse this shows:
https://i.gyazo.com/7264a620eb6019302909e12675343870.png


text:
Q: Strings carrying Kalb-Ramond charge I am confused about how strings in bosonic string theory carry Kalb-Ramond ($B_{\mu\nu}$) charge.  This idea is usually introduced by analogy to how the worldline of a charged point particle couples to the EM gauge potential $A_\mu$. The string/Kalb-Ramond case is just supposed to be the two-form generalization of this. See 7.2.1 of Tong's notes.
But in the particle/EM case, the charged particles (electron/positron) can just be introduced by fiat. In string theory, the only allowed particle states are what we find from quantizing the string, namely the graviton, dilaton, and Kalb-Ramond states. None of these carry a discrete charge like an electron.
So, when people claim strings carry Kalb-Ramond charge, which string states are they talking about?


text:
Q: How to determine the unit-step response of a $h(t)=\frac{t}{1+t^2}\theta(t)$ I have this function  $h(t)=\frac{t}{1+t^2}\theta(t)$, and I have to find its unit step response. By the use of this post I took the convolution of the function, $h(t)$, which I consider composed of two convolving functions, $\frac{t}{1+t^2}$ and the unit step function, $\theta(t)$. So the convolution theorem gives
\begin{equation}
\int_0^t\theta(t-\tau)\frac{\tau}{1+\tau^2}d\tau
\end{equation}
However, there are two issues I am not sure about, first, how does one remove $\theta(t-\tau)$ and include it in the boundaries instead? Then, once this is done, assuming I am right, I get:
\begin{equation}
\int_0^t \frac{\tau}{1+\tau^2}d\tau=t \arctan t-\int_0^t\arctan\tau d\tau=\arctan\tau-\big[ t\arctan t-\frac{1}{2}\ln |1+t^2| \big]_0^t=\frac{1}{2}\big(\ln|1+t^2|-\ln1\big)
\end{equation}
When I plot this I get

But this does not seem right, when the plot of the function $h(t)$ is:

The part before zero should be different in the first plot, not gradually decreasing?
Where is the error in this procedure?
Thanks
UPDATE:
Correction: have to multiply in $\theta(t)$
\begin{equation}
\int_0^t \frac{\tau}{1+\tau^2}d\tau=t \arctan t-\int_0^t\arctan\tau d\tau=\arctan\tau-\big[ t\arctan t-\frac{1}{2}\ln |1+t^2| \big]_0^t=\frac{1}{2}\big(\ln|1+t^2|\big)\theta(t)
\end{equation}
Gives the plot

Which by Mathematica codes is still different:

A: The step response is given by the convolution
$$y(t) = \int_{-\infty}^\infty\theta(t-s)\dfrac{s}{1+s^2}\theta(s)\mathrm{d}s=\dfrac{t-s}{1+(t-s)^2}\theta(t-s)\theta(s)\mathrm{d}s.$$
The first expression is much easier to consider and reduces to
$$y(t)=\int_0^t\dfrac{s}{1+s^2}\mathrm{d}s=\dfrac{1}{2}[\log(1+s^2)]^t_0\theta(t)=\dfrac{1}{2}\log(1+t^2)\theta(t).$$


text:
Q: I am getting into infinite loop in property setter public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            Position = Convert.ToInt32(Session["Position"]);
        }
        else
        {
            Position = 5;
        }
        return Position;
    }
    set
    {
        Position = value;
    }
}

my program calls the get and goes into if loop and then runs infitely into set code

A: Use a member variable or perhaps store it in the session.
private int _position;
public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            _position= Convert.ToInt32(Session["Position"]);
        }
        else
        {
            _position= 5;
        }
        return _position;
    }
    set
    {
        _position = value;
    }
}

A: There's nothing particularly string-like about session state items.
Why wouldn't you just follow the KISS principle and do something like
public int Position
{
  get { return (int) ( Session["Position"] ?? 5 ) ; }
  set { Session["Position"] = value ;               }
}

or (depending on your actual requirements/specs:
public int Position
{
  get { return Session["Pointer"] as int? ?? position ?? 5 ; }
  set { position = value ; }
}
private int? position ; // backing store

A: The error is because in your set {} you are invoking the same setter recursively.
Correct code would be
private int _position;
public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            this._position = Convert.ToInt32(Session["Position"]);
        }
        else
        {
            this._position = 5;
        }
        return this._position;
    }
    set
    {
        this._position = value;
    }
}

A: An auto-implemented property property consists of a getter, a setter and a backing field. If you write the code yourself, a field might not be necessary.
Your getter invokes setter, and the setter invokes setter; that would be infinite recursion. You might need a field for storing Position.
However, if we change it with storing to a field, and the setter in fact doesn't effect. So, the code could be changed to:
public int Position {
    set {
    }

    get {
        int x;
        return (x=Convert.ToInt32(Session["Position"]))>0?x:5;
    }
}

You don't need to check for null, Convert.ToInt32(null) is zero.


text:
Q: Mixture of Gaussian and Uniform in R I am trying to fit a mixture of a gaussian and a uniform distribution
in R with only limited success.
I rely on flexmix to provide an EM framework and I fit the
components using slightly adapted versions of the matching moment
estimators from fitdistrplus package.  (The adaptation is only a
replacement of the sample mean and variance with weighted versions.)
As I am not terribly familiar with flexmix the code (below) is quite
a hack.
It looks as if the uniform distribution gets too little weight.
Any help with how to improve the fit is highly appreciated.
First the example
Generate toy data
a <- rnorm(10000)
b <- runif(10000, min=1, max=5)
c <- c(a,b) + 10
testdata <- data.frame(c=c)

The ideal fit
comp1 <- 0.5*dnorm(testdata$c, mean=10)
comp2 <- 0.5*dunif(testdata$c, min=11, max=15)

The fit
fit <- flexmix(c~1, data=testdata, k=2,
               model=FLXMCnormplusunifw(),
               cluster=as.integer(testdata$c < 12)+1)

The functions
## adapted from the 'fitdistrplus' package
fitnorm_w <- function(data, weights) {
  library("Hmisc")
  n <- length(data)
  m <- weighted.mean(data, weights)
  v <- wtd.var(data, weights, normwt = TRUE)

  list(mean=m, sd=sqrt(v))
}
## adapted from the 'fitdistrplus' package
fitunif_w <- function(data, weights) {
  library("Hmisc")
  n <- length(data)
  m <- weighted.mean(data, weights)
  v <- wtd.var(data, weights, normwt = TRUE)

  min1 <- m - sqrt(3*v)
  max1 <- m + sqrt(3*v)

  list(min=min1,
       max=max1)
}

## generate needed S4 class for flexmix -- "norm"
FLXMCnorm1w <- function (formula = . ~ .)
{
  z <- new("FLXMC", weighted = TRUE, formula = formula, dist = "norm",
           name = "model-based univariate norm clustering")
  z@defineComponent <- expression({
    logLik <- function(x, y) dnorm(y, mean = mean, sd = sd,
                                    log = TRUE)
    predict <- function(x, ...) matrix(mean, nrow = nrow(x),
                                       ncol = 1, byrow = TRUE)
    new("FLXcomponent",
        parameters = list(mean = as.vector(mean), sd = as.vector(sd)),
        df = df, logLik = logLik, predict = predict)
  })
  z@fit <- function(x, y, w, ...) {
    ##browser()
    para <- fitnorm_w(as.vector(y), as.vector(w))
    para$df <- 2
    with(para, eval(z@defineComponent))
  }
  z
}

## generate needed S4 class for flexmix -- "unif"
FLXMCunif1w <- function (formula = . ~ .)
{
  z <- new("FLXMC", weighted = TRUE, formula = formula, dist = "unif",
           name = "model-based univariate uniform clustering")
  z@defineComponent <- expression({
    logLik <- function(x, y) dunif(y, min = min, max = max,
                                   log = TRUE)
    predict <- function(x, ...) matrix(runif(nrow(x), min=min, max=max),
                                       nrow = nrow(x), ncol = 1, byrow = TRUE)
    new("FLXcomponent",
        parameters = list(min = as.vector(min), max = as.vector(max)),
        df = df, logLik = logLik, predict = predict)
  })
  z@fit <- function(x, y, w, ...) {
    ##browser()
    para <- fitunif_w(as.vector(y), as.vector(w))
    para$df <- 2
    with(para, eval(z@defineComponent))
  }
  z
}

## ---------------------------------- ##
## the norm+uniform flexmix class     ##
## ---------------------------------- ##

setClass("FLXMCnormplusunifw", contains = "FLXMC")
##
FLXMCnormplusunifw <- function(formula = . ~ ., ...)
{
  new("FLXMCnormplusunifw", FLXMCnorm1w(formula, ...),
      name = paste("FLXMCnormplusunifw" , sep=":"))
}
##
setMethod("FLXremoveComponent", signature(model = "FLXMCnormplusunifw"),
          function(model , nok, ...)
          {
            if (1 %in% nok) as(model , "FLXMC") else model
          })
##
setMethod("FLXmstep", signature(model = "FLXMCnormplusunifw"),
          function(model , weights , ...)
          {
            ##browser()
            comp.1 <- FLXMCunif1w()
            c(list(comp.1@fit(model@x, model@y, weights[, -1,drop=FALSE])),
              FLXmstep(as(model , "FLXMC"), weights[, 1, drop=FALSE]))
          })


text:
Q: Ruby on Rails: Subclasses The idea behind the project: Content Management System. I have a superclass called Content, and a subclass of Text/HTML, for now. Later it will handle content types of Video and Images.
All using Single Table Inheritance.
My question is how to handle the subclass using only the parent class controller.
Here is the code for create under ContentController (It might contain stuff I don't necessarily need):
def create
 @content = Content.new(params[:content])
 @content_module = ContentModule.find(@content.content_module_id)

 respond_to do |format|
  if @content.save
    format.html { redirect_to admin_module_content_url(@content.content_module), notice: 'Content was successfully created.' }
    format.json { render json: @content, status: :created, location: @content }
  else
    format.html { render action: "new"}
    format.json { render json: @content_module.errors, status: :unprocessable_entity}
  end
 end
end

The params to @content should be able to take in params of, let's say something like params[:text/html] which will create that type of Content.
Could someone help me out with the logic needed to do something like this?

A: I usually introduce a new class method on the superclass which returns the correct instance based on params[:type]:
class Content

  def self.for(params)
    content_type = params.delete(:type)
    case content_type
      when 'text_html'
        TextHtml
      when 'video'
        Video
      else
        raise "invalid content type #{content_type}"
    end.new(params)
  end

end

and then call it like this
@content = Content.for(params)

Does this help?


text:
Q: How to have only email clients available to choose from when trying to email text from android app? I'm trying to send an HTML text from my app by email. So I have this code:
StringBuilder sb = new StringBuilder();
// Lots of HTML building code...

Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_SUBJECT, trip_to_manipulate.getTrip_name());
i.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(sb.toString()));
i.setType("message/rfc822");// to filter and display only email apps
try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

But when I run this code I have whole bunch of apps showing up in the chooser:

I tried to start activity without createChoser, I tried to change type to text/html, I tried to use ACTION_SENDTO instead of ACTION_SEND, I tried them separately, I tried them combined, but I still got all these apps. Sometimes even more. And when they were combined the app crashed.
So is there a way to limit this list to email clients only?


text:
Q: Upload to ADLS from file stream I am making a custom activity in ADF, which involves reading multiple files from Azure Storage Blobs, doing some work on them, and then finally writing a resulting file to the Azure Data Lake Store.
Last step is where I stop, because as far as I can see, the .NET SDK only allows for uploading from a local file.
Is there any way to to (programmatically) upload a file to ADL Store, where it is not from a local file? Could be a blob or a stream. If not, any workarounds?

A: Yes, it's possible to upload from Stream, the trick is to create file first and then append your stream to it:
string dataLakeAccount = "DLSAccountName";
var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(credentials);
adlsFileSystemClient.FileSystem.Create(dataLakeAccount, filepath, overwrite: true);
adlsFileSystemClient.FileSystem.Append(dataLakeAccount, filepath, stream);

See also this article.