text:
Q: Why can't I slide the ListView.builder on Flutter WEB? When I try to slide the ListView.Builder on my browser (chrome), it doesn't work...
What's messed up is that when I run the devtools of chrome and activate the device toolbar in 'Responsive mode' it works... It seems that Flutter only accepts simulated touch screens...
Any ideas?
         Scaffold(
  body: Container(
    width: 100.h,
    height: 100.w,
    decoration: const BoxDecoration(
      gradient: LinearGradient(
        colors:
        [
          Color(0xFF3366FF),
          Color(0xFF00CCFF),
        ],
        begin: FractionalOffset(0.0, 0.0),
        end: FractionalOffset(0.0, 1.0),
        stops: [0.0, 1.0],
        tileMode: TileMode.clamp
      ),
    ),
    child: Column(
      children: [
        TopBar(),
        Padding(
          padding: EdgeInsets.only(top: 2.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                onPressed: () {
                    Navigator.of(context).pop();
                },
                 icon: Icon(
                   Icons.arrow_back_ios,
                   color: Colors.white,
                   size: 8.sp,
                 )
              ),
              Text(
                "En attente de validation",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 8.sp
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 1.h),
          child: Align(
            alignment: Alignment.centerLeft,
            child: Text(
              "Prospection 'maison'",
              style: TextStyle(
                color: Colors.white,
                fontSize: 8.sp
              ),
            ),
          ),
        ),
        //normal
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(bottom: 1.w),
            child: ListView.builder(
              physics: const AlwaysScrollableScrollPhysics(),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                return Padding(
                  padding: EdgeInsets.only(left: 1.h),
                  child:

                  //Card Building
                  Container(
                    width: 20.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6)
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 4.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "22",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 15.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 1.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "JUMP STREET",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 9.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 2.w),
                          child: Center(
                            child: Icon(
                              CupertinoIcons.building_2_fill,
                              size: 40.sp,
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 1.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "a",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 9.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 2.w),
                          child: SizedBox(
                            width: 15.h,
                            child: CupertinoButton(
                              color: Colors.green,
                              child: Text("Completer"),
                              onPressed: () {

                              }
                            ),
                          ),
                        )

                      ],
                    ),
                  ),

                );
              },
              itemCount: 30,
            ),
          ),
        ),
        //multi
        Padding(
          padding: EdgeInsets.only(left: 1.h),
          child: Align(
            alignment: Alignment.centerLeft,
            child: Text(
              "Prospection 'immeuble'",
              style: TextStyle(
                color: Colors.white,
                fontSize: 8.sp
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(bottom: 1.w),
            child: ListView.builder(
              physics: const AlwaysScrollableScrollPhysics(),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                return Padding(
                  padding: EdgeInsets.only(left: 1.h),
                  child:

                  //Card Building
                  Container(
                    width: 20.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6)
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 4.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "22",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 15.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 1.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "JUMP STREET",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 9.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 2.w),
                          child: Center(
                            child: Icon(
                              CupertinoIcons.building_2_fill,
                              size: 40.sp,
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 1.h),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "b",
                              style: TextStyle(
                                fontFamily: 'Basic',
                                fontSize: 9.sp
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 2.w),
                          child: SizedBox(
                            width: 15.h,
                            child: CupertinoButton(
                              color: Colors.green,
                              child: Text("Completer"),
                              onPressed: () {

                              }
                            ),
                          ),
                        )

                      ],
                    ),
                  ),

                );
              },
              itemCount: 30,
            ),
          ),
        )
      ]
    ),
  ),
);

This is my flutter doctor.
[√] Flutter (Channel master, 2.5.0-2.0.pre.113, on Microsoft Windows [version
10.0.19043.1110], locale fr-FR)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
   X cmdline-tools component is missing
     Run `path/to/sdkmanager --install "cmdline-tools;latest"`
     See https://developer.android.com/studio/command-line for more details.
   X Android license status unknown.
     Run `flutter doctor --android-licenses` to accept the SDK licenses.
     See https://flutter.dev/docs/get-started/install/windows#android-setup for more
     details.
   [√] Chrome - develop for the web
   [√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.8.3)
   [√] Android Studio (version 4.1)
   [√] IntelliJ IDEA Community Edition (version 2021.1)
   [√] VS Code (version 1.58.2)
   [√] Connected device (3 available)

A: try to modify the listview parameter to :
        child: ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,


text:
Q: Trouble Redirecting after successfull Auth0 login attempt Using react-router and reacts context api i am attempting to authenticate a user in Auth0 and then redirect the user to a home page on successful login. What am i missing in my routing? I am passing the context to the rest of the app by wrapping the app using  and passing the login and logout methods down the tree. When I call the login() method from a child component the login method in the context gets called where i set state {isAuthenticated} to true and then i call the Auth.login() from within the context component as shown in the attached code.
I have searched Auth0 docs and have setup the correct callback route to http://localhost:3000/admin/dashboard
When i click login on the page the first time the appropriate Auth0 component shows up and i can login, however after i enter credentials and hit the login button i am redirected back to the {Login} component. If i then hit the login button in the {Login} component again after that i can see the page trying to redirect to my home route and then it kicks me back to the {Login} component.
import auth from '../Auth/Auth'

const AuthContext = React.createContext();
const Auth = new auth();

class AuthProvider extends React.Component {
  state = { isAuthenticated: false }
  constructor() {
    super()
    this.login = this.login.bind(this)
    this.logout = this.logout.bind(this)
  }

  auth0Signin() {
    Auth.login()
  }

  login() {
    this.setState({ isAuthenticated: true })
    this.auth0Signin()
  }

  logout() {
    Auth.logout()
    this.setState({ isAuthenticated: false })
  }

  render() {
    return (
      <AuthContext.Provider
        value={{
          isAuthenticated: this.state.isAuthenticated,
          login: this.login,
          logout: this.logout
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}
const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer };

import Auth from './Auth/Auth'
import Callback from './views/components/Callback'
import { createBrowserHistory } from "history";
import React from 'react';
import "react-notification-alert/dist/animate.css";
import { Redirect, Route, Router, Switch } from "react-router-dom";
import { AuthConsumer, AuthProvider } from './providers/AuthContext';
import Login from './views/pages/Login';
import Register from './views/pages/Register'
import Dashboard from './layouts/Admin/Admin'

const auth = new Auth()
const hist = createBrowserHistory();

const handleAuthentication = (nextState, replace) => {
  if (/access_token|id_token|error/.test(nextState.location.hash)) {
    auth.handleAuthentication();
  }
}

const ProtectedRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =>
          isAuthenticated ? <Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> : <Redirect to='/auth/login' />}
        {...rest}
      />
    )}
  </AuthConsumer>
)

const PublicRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =><Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> }
        {...rest}
      />
    )}
  </AuthConsumer>
)

const App = () => {
  return (
    <>
      <Router history={hist}>
        <AuthProvider>
          {/* <Header /> */}
            <Switch>
              <ProtectedRoute path='/admin/dashboard' component={Dashboard} />
              <PublicRoute path='/auth/Register' component={Register} />
              <PublicRoute path='/auth/Login' component={Login} />
              <Route path="/callback" render={(props) => {
                  handleAuthentication(props);
                  return <Callback {...props} />
                }}/>
              <PublicRoute path='/' component={Login} />
            </Switch>
          {/* <Footer /> */}
        </AuthProvider>
      </Router>
    </>
  );
}

export default App;

import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from './History';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    callbackUrl: AUTH_CONFIG.callbackUrl,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.redirectUri,
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        history.replace('/admin/dashboard');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  setSession(authResult) {
    // Set isLoggedIn flag in localStorage
    localStorage.setItem('isLoggedIn', 'true');

    // Set the time that the Access Token will expire at
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken;
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;

    // navigate to the home route
    history.replace('/home');
  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
       if (authResult && authResult.accessToken && authResult.idToken) {
         this.setSession(authResult);
       } else if (err) {
         this.logout();
         console.log(err);
         alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
       }
    });
  }

  logout() {
    // Remove tokens and expiry time
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;

    // Remove isLoggedIn flag from localStorage
    localStorage.removeItem('isLoggedIn');

    this.auth0.logout({
      returnTo: window.location.origin
    });

    // navigate to the home route
    history.replace('/auth/login');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }
}

A: The way I do it is with history.replace() in the Auth utility methods and then redirect to an authcheck component which upodates the global context state.
import auth0 from 'auth0-js'
import history from './history';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: 'webapp1.auth0.com',
    clientID: 'uZxUdMAsiDWeu3OrNpoi4JwJscdF5nAx',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid profile email'
  })

  userProfile = {}

  login = () => {
      this.auth0.authorize()
  }

  handleAuth = () => {
    this.auth0.parseHash((err, authResult) => {
      if(authResult) {
        localStorage.setItem('access_token', authResult.accessToken)
        localStorage.setItem('id_token', authResult.idToken)

        let expiresAt = JSON.stringify((authResult.expiresIn * 1000 + new Date().getTime()))
        localStorage.setItem('expiresAt', expiresAt)

        this.getProfile();
        setTimeout(() => { history.replace('/authcheck') }, 600);
      } else {
        console.log(err)
      }
    })
  }

  getAccessToken = () => {
    if(localStorage.getItem('access_token')) {
      const accessToken = localStorage.getItem('access_token')
      return accessToken
    } else {
      return null
    }
  }

  getProfile = () => {
    let accessToken = this.getAccessToken()
    if(accessToken) {
      this.auth0.client.userInfo(accessToken, (err, profile) => {
          if(profile) {
            this.userProfile = { profile }
          }
      } )
    }
  }

  logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('expiresAt')
    setTimeout(() => { history.replace('/authcheck') }, 200);
  }

  isAuthenticated = () => {
    let expiresAt = JSON.parse(localStorage.getItem('expiresAt'))
    return new Date().getTime() < expiresAt
  }

}

import React, { useEffect, useContext } from 'react';
import history from './history';
import Context from './context';
import * as ACTIONS from '../store/actions/actions';
import axios from 'axios';

const AuthCheck = () => {
  const context = useContext(Context)

  const send_profile_to_db = (profile) => {
   const data = profile
   axios.post('/api/posts/userprofiletodb', data )
    .then(axios.get('/api/get/userprofilefromdb', {params: {email: profile.profile.email}})
      .then(res => context.handleAddDBProfile(res.data)) )
    }

  useEffect(() => {
    if(context.authObj.isAuthenticated()) {
      context.handleUserLogin()
      context.handleUserAddProfile(context.authObj.userProfile)
      send_profile_to_db(context.authObj.userProfile)
      history.replace('/')
    }
    else {
      context.handleUserLogout()
      context.handleUserRemoveProfile()
      history.replace('/')
      }
    }, [])

    return(
        <div>
        </div>
    )}

export default AuthCheck;

You can check out the fully functioning app here
https://github.com/iqbal125/react_hooks_fullstack_skeleton

redpajama_set_name: RedPajamaStackExchange


text:
Q: release db connections in standalone application I am working on a standalone application using Spring/JPA and I am trying to release properly the database resources used.
In a Web application using tomcat for example, we shutdown the server, and this way, we let Tomcat manage the resources.
But as I am in a standalone app, I have to take care about this, I use Runtime.getRuntime().addShutdownHook to "catch" the shutdown event and call ((ClassPathXmlApplicationContext) context).close();, something like this:
Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        ((ClassPathXmlApplicationContext) context).close();
    }

It works but with an exception in the stacktrace if a thread was using a connection.
I am wondering if there is another option? Maybe getting a list of open transactions and force them to rollback?

A: I believe that you would need to implement something like this and inside your destroy method, you would retrieve your datasource and call a close method or something similar. I'm also assuming you have a few things to do when you shutdown your application.
I can't quite help with the right method name as I don't know what you are using for your datasource.


text:
Q: Kendo Menu selection issue I've a kendo menu to dynamically enable or disable the kendo grid columns. When I select the options from the KendoMenu, the selection is firing twice. I've created the demo version below.
demo
$("#menu").kendoMenu({
dataSource: [{
    text: "Menu",
    items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
    var selector;
    $.each(grid.columns, function () {
        if (this.hidden) {
            selector = "input[data-field='" + this.field + "']";
            $(selector).prop("checked", false);
        }
    });
},
select: function (e) {
    // don't show/hide for menu button --- calling twice
    if ($(e.item).parent().filter("div").length) return;

    console.log("******");

    var input = $(e.item).find("input.check");
    var field = $(input).data("field");
    if ($(input).is(":checked")) {
        grid.showColumn(field);
    } else {
        grid.hideColumn(field);
    }
}});

Check the console log while selecting the menu items.

A: Adding the checkbox to the menu item seems to lead to kendo firing the event for the menu click and the checkbox check.  It seems hard to differentiate between the two instances, so it might be better to do something different to indicate the check.  The following icons can be used - maybe use the tick icon instead of an actual checkbox:
http://demos.telerik.com/kendo-ui/styling/icons

A: I've fixed the issue with the updated code
$("#menu").kendoMenu({
dataSource: [{
    text: "Menu",
    items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
    var selector;
    $.each(grid.columns, function () {
        if (this.hidden) {
            selector = "input[data-field='" + this.field + "']";
            $(selector).prop("checked", false);
        }
    });
},
select: function (e) {
    // don't show/hide for menu button
    if ($(e.item).parent().filter("div").length) return;
    var removeItemFlag = false;
    var input = $(e.item).find("label");
    var selectedValue = input[0].innerHTML;

    if(selectedValue)
    {
        for(var i=0; i< droplist.length; i++){
            if(droplist[i] === selectedValue){
                removeItemFlag = true
                input[0].classList.remove = "fa fa-check-square-o";
                input[0].className = "fa fa-square-o";
                break;
            }
        }
        var selectedIndex = droplist.indexOf(selectedValue);
        if (selectedIndex > -1 && removeItemFlag) {
            droplist.splice(selectedIndex, 1);
             grid.hideColumn(selectedValue);

        }else{
            droplist.push(selectedValue);
            grid.showColumn(selectedValue);
            input[0].className = "fa fa-check-square-o";
        }
    }
}

});


text:
Q: Add Margin to using Sass mixins in bootstrap I have a page that has a bunch of Section tags in it and I have a my-5 class on each one. Rather than repeating that every time I'd love to see if I could use a Sass Mixin to apply the my-5 css automatically to the Section tag so I could simply turn this

into this

A: You would use SASS @extend inside the section rule...
section {
   @extend .my-5;
}

https://www.codeply.com/go/6ziZAFqFJj


text:
Q: Does persistent homology really make sense for mixed variable types? Purpose
Persistent homology is a fascinating approach to exploring data (see Chazal & Michel 2021 for an introduction). I have seen many impressive examples of it through AATRN. I'm considering how it can be used in my current and future projects. I am finding it confusing to consider the examination of persistence diagrams (e.g. Marchese 2017) of different types of measurement.
To help avoid an XY Problem, I want to first insist that this question really is about how to usefully apply persistent homology to experimental data. Experimental data very often involves mixed types of variables. Standardization can be used to remove units, but I have vague worry that the variables are still of incompatible 'types'. By 'type' I am not referring to level of measurement (i.e. Steven's typology, or group action invariance more broadly). Rather the resulting standardized variables are still monotonic functions of quantities that don't always feel like they should have a notion of proximity (e.g. X = number of people cringing in an audience, Y = short-time dominant frequency of sound coming from a trumpet playing The Ecstacy of Gold) even if it can be mathematically constructed.
The following is an example that is intended to illustrate how disparate the meaning of experimental variables can have, but it can be skipped if the reader finds it tedious.

A (Long) Example
Let me exemplify with a hypothetical, but not extremely unrealistic, scenario. I am going to make it rather more detailed than "here is my table of variables" because I want to emphasize to the reader that there is a lot of operational meaning behind each measurement. There is a lot of context behind each number in the data.
Suppose we have an unknown microorganism in a glass vial containing a thioglycolate tryptic soy broth. We might observe that the organism prefers to grow a different depths of the vial (depending on their optimal oxygen level for growth). Some of the possibilities are nicely shown below as five vials in which different populations of microbes growth optimally at different depths in a broth.

Wikipedia classifies these vials as the followed:

*

*obligate aerobes

*obligate anearobes

*facultative anaerobes

*microaerophiles

*aerotolerant organisms
We will take our first variable to be aliquots taken from different depths of the vial recorded in millimetres. The volume of the aliquots are equally 100 microlitres, but are serially diluted (perhaps logarithmically as shown below) for the following step.

At this point we have prepared some freshly autoclaved tryptic soy agar. The autoclaving was performed at some fixed temperature, pressure, and duration for each sample.

As the agar cools, but before it solidifies, we spike distinct concentrations of maltose using a syringe filter.

Then we add the dilutions of microbial broth and liquid agar to plates, allow them to incubate for 24 hours, and then examine the plates.

Finally, the colony-forming units are counted.

Tabulating the non-degenerate variables, we have:

Aliquot Depth
Dilution Factor
Maltose Spike Concentration
CFU Count

...
...
...
...

The aliquot depth is in units of distance (e.g. mm). The dilution factor is dimensionless. The maltose spike concentration is likely units of molar concentration. The CFU count is dimensionless, or if preferred: CFU's.
This process gives a data set where it isn't clear that a metric could be applied on the variables. Standardizing the scores would yield unit-less variables with more comparable centers and scale. But (1) it isn't clear whether the original scale might have been important and (2) such scores are still representing disparate types of quantities even if they are rendered unit-less.
In contrast, if we had collected the spatial cordinates of each colony in the agar plates, it seems natural to me to use a metric to compute how far each colony was from each other colony. And with this distance matrix, compute the persistence of each hole among the colonies.

Question
Does it make sense to apply persistent homology to variables that, in an experimental context, mean very different things? If so, how?

Apologies for the imprecision of this question. There is just something about this approach that has a "bad smell" when it comes to mixed variable types. I am hoping someone can see the problem I can't seem to put into words.


text:
Q: Making a function to take the inverse fourier transform I am trying to take the inverse fourier transform by making my own function. This is the function to take the Fourier transform of my time series which appears to work fine.
def DFT(x, frequencies):
    N1 = x.size
    k = frequencies.size
    t = np.arange(N1)
    fourier = np.zeros(k)
    for i in range(0,k):
        fourier[i] = np.dot(x,(1/k)*np.exp(-2j*np.pi*frequencies[i]*t))
    return fourier

This is my original signal (just a sine wave):
N2 = 1*10**6
time = np.arange(0,N2,1000)
lam = .1*10**6
f = 1/lam
freq = np.arange(0,.05,.0001)

signal = np.sin(2*np.pi*f*time)

And the power spectrum is plotted using my DFT (fourier function):
plt.plot(freq, np.abs(DFT(signal,freq))**2)
plt.xlabel('Frequency')
plt.title('Spectrum of Sine Wave')
plt.grid()
plt.show()

but when I try to apply my function for the inverse fourier transform, I am not getting my original sine wave back:
def IFT(fft, frequencies):
    N = fft.size
    k = frequencies.size
    n = np.arange(N)
    inverse_fourier = np.zeros(k)
    for i in range(0,k):
        inverse_fourier[i] = np.dot(fft,np.exp((-2j*np.pi*frequencies[i]*n)/N)) #[None,:]
    return inverse_fourier

What is wrong with my function? I get no errors, but the returned signal is totally wrong.

A: Running you code you should get the following warning:
ComplexWarning: Casting complex values to real discards the imaginary part
  fourier[i] = np.dot(x,(1/k)*np.exp(-2j*np.pi*frequencies[i]*t))

Since the resulting Fourier transform should be complex valued, this warning should be reasons for concerns. To get rid of this warning you may initialize fourier like so:
fourier = np.zeros(k, dtype=complex)

Also the formula for Discrete Fourier Transform includes summations over frequencies covering the complete [0,1) range. To get a 1000-point DFT (as you had in your code) you'd then have to use
freq = np.arange(0,1,.001)

This will result in a spectrum that includes 2 spikes: one at the expected frequency, and another symmetric one above the Nyquist frequency. It is common to discard the results above the Nyquist frequency when plotting the spectrum of real-valued signals (but use the full spectrum into your IFT function).
Finally, as GrimTrigger pointed out:

your inverse the exponent should be positive (2j instead of -2j) and drop the /N

A: In your inverse the exponent should be positive (2j instead of -2j) and drop the /N, which gives (added plots for demonstration):
import numpy as np
import matplotlib.pyplot as plt

def DFT(x, frequencies):
    N1 = x.size
    k = frequencies.size
    t = np.arange(N1)
    fourier = np.zeros(k)
    for i in range(0,k):
        fourier[i] = np.dot(x, (1/k)*np.exp(-2j*np.pi*frequencies[i]*t))
    return fourier

def IFT(fft, frequencies):
    N = fft.size
    k = frequencies.size
    n = np.arange(N)
    inverse_fourier = np.zeros(k)
    for i in range(0,k):
        inverse_fourier[i] = np.dot(fft, np.exp((2j*np.pi*frequencies[i]*n))) #[None,:]
    return inverse_fourier

N2 = 1*10**6
time = np.arange(0,N2,2000)
lam = .1*10**6
f = 1/lam
freq = np.arange(0,.05,.0001)

signal = np.sin(2*np.pi*f*time)

plt.plot(time, signal)
plt.xlabel('Time')
plt.title('Sine Wave')
plt.grid()
plt.show()

dft = DFT(signal, freq)

plt.plot(freq, np.abs(dft)**2)
plt.xlabel('Frequency')
plt.title('Spectrum of Sine Wave')
plt.grid()
plt.show()

plt.plot(time, IFT(dft, freq))
plt.xlabel('Time')
plt.title('Sine Wave')
plt.grid()
plt.show()

which gives (first sin graph omitted):

and


text:
Q: Changing the orders of the words
He has taken a picture.
  The picture he has taken become popular
He has his picture taken.
  The picture he ...... become popular

Fill in the blanks please. I don't think I can say something like
"The picture he has it taken become popular" so don't know what to say. Thanks

A: Firstly, the second sentence in the first example is not grammatical. It should be

The picture he has taken has become popular.

The picture he has taken is a noun phrase. "he has taken" describes "the picture." has become popular is a verb phrase, where the verb "to become" is in the present perfect tense.
As for the second example, I guess the answer could be

The picture he has taken of himself has become popular.

But this is kind of ambiguous. It sounds like someone else is taking his picture (because of the use of the passive voice in the first sentence), but then the phrasing in this second sentence makes it unclear whether "has" is an auxiliary verb (present perfect tense) or a "regular" transitive verb (as in the first sentence). To avoid this ambiguity, it could be reworded as:

The picture he gets taken of himself has become popular.

since "to get a picture taken" has a similar meaning to "to have a picture taken".

A: There is some ambiguity between using the helping verb "have" for the perfect tense, and using it as an imperative.  Nevertheless, there are certain conventions.

He has taken a picture

means that he took the picture himself.

He has his picture taken

means that someone takes a picture of him.  However,

The picture he has taken.

by itself, suggests that he is the one who took the picture.  If he asked or paid someone else to take a picture of him, it would be more natural to use the past perfect.

The picture he had taken

This is still somewhat ambiguous, so for clarity you should add more detail to define the subject of the picture:

The picture he had taken of himself became popular

Note that it's became popular, not become popular, as the action happens in the past, relative to the current moment.

A: The first translation looks like this (note that I am providing the two simplest ways of correcting the issue with become popular):

He has taken a picture.
  → The picture he has taken became popular.
  → The picture he has taken becomes popular.

Given that, the equivalent translation (keeping it as close as possible in terms of equivalent phrasing) would be this:

He has his picture taken.
  → His picture he has had taken became popular.
  → His picture he has had taken becomes popular.

This is because, in the second version, he has had somebody else take his picture. We can't say he has taken it, because he hasn't, so we have to say he has had it taken.
Also, while a picture becomes the picture in the first pair, his picture can remain as it is.
The phrasing isn't entirely natural, but it's still acceptable—and it follows the same pattern of translation.


text:
Q: Laravel 5.6 unable to import css file I am trying to import css file but i just cant.
my css file is in "public/css/style.css"
i ve tried all possible combinations that i found on internet but nothing works
<link href="/css/style.css" rel="stylesheet">
<link href="{!! asset('css/style.css') !!}" media="all" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="{{ URL::asset('css/style.css') }}" />

Laravel .htaccess
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

but nothing just works for me

A: <link href="{!! asset('css/style.css') !!}" media="all" rel="stylesheet" type="text/css" />

Change That to This
<link href="{{ asset('css/style.css') }}" media="all" rel="stylesheet" type="text/css" />

and it should work.

A: Solved
i ma probably missing some configuration that i cant find out.
But i create virtual host with xampp and set DocumentRoot "C:\xampp\htdocs\final\public" and this works.
Thanks for help guys.

A: Try:
<link href="./public/css/style.css" rel="stylesheet">
The ./ part is the current folder you are in.


text:
Q: WebKit jagged image on resize We're having a problem when an image (logo) is resized in WebKit, it is jagged for a couple of seconds. We've tried resizing it both by changing width in CSS and using scale transformation. Is there any way to fix this?

http://codepen.io/Znarkus/pen/xbxKLK
Example HTML:

CSS:
div {
  width: 300px;
  height: 100px;
  background: #ddd;
}

img {
  max-width: 100%;
}

div:hover img {
  width: 200px;
}

A: It seems to be a problem with the antialiasing of the images which has a short delay. My searches did not yield any good answers on how to solve this, so I've come up with two possible solutions.
Solution 1
Keep two versions of the image pre-rendered, then switch between the different sizes.
Pros: Perfect rendering
Cons:  Takes more memory
Solution 2
User the image-rendering CSS property to disable antialiasing. By adding image-rendering: [browser specific see codepen fork]; to the div, you can see that the rendering of the image isn't as good as without antialiasing.
Pros: All CSS, no extra memory consumption
Cons: Lesser image quality
http://codepen.io/anon/pen/XJWrvJ
EDIT: Solution 3
On second though, there might be a different solution. Images aren't particulary great for rendering text, but since it's a logo I'm guessing you have some kind of special twist on the text or styling. If you can export the logo as svg and render it in a canvas you might be able to get around these problems.


text:
Q: Extjs keeping current select items in combo and adding new items I have a Role combo box which already have 3 item (loaded User Model). Now I need to add the 4th item to the selection but it doesn't keep the current items, and when I add the 4th one, it will be the only item selected in combo.
Is there anyway to implement this behavior ?
    My grid record is selected like this
 doSelectUser: function(grid, record) {
        var me = this;
        var selectedRoleVals = record.get('roles');
        me.getUserForm().loadRecord(record);

And then I click the combo box in User Form:
 manageusers userform combobox[name=roles]': {
                select: this.doSelectRole
            }

combo handler
doSelectRole: function(combo, records) {
        var me =
        var rec = records[0];

A: I suspect you are doing something like
combo.getStore().loadRecords(arrayOfRecords);

You need to be doing
combo.getStore().loadRecords(arrayOfRecords, {addRecords: true});

loadRecords by default overwrites the contents of the store with the new data.
And to add a simple record to your combo box
Ext.ComponentQuery.query('combo[itemId=theComboItemId]')[0].getStore().add({value: 'aRoleValue', displayText: 'A new role'});


text:
Q: VBA / Internet Explorer: Capture Resulting URL From OnClick Event I am automating some data collection using the Internet Explorer object in VBA, and have hit a wall trying to obtain a url resulting from a href onclick event.
The link is being "clicked" by the code below, which takes me to a Save As dialogue. I would instead just like to grab the resulting url generated by the onclick event. I can't pull this from the <a> tag as the href attribute points to javascript:void(0).
I know that IE itself knows the resulting url, as I can inspect this from the Downloads window if I manually download the resulting file, but is there a way to programmatically access and capture (in a string) the url to where IE is being directed by the onclick event being fired? Without actually having IE try to download the file itself?
Set Link = IE.document.getElementsByTagName("a")

For Each l In Link
    If l.innertext = "Excel" Then
       l.FireEvent ("onclick")
    Exit For
    End If
Next l

A: Perhaps it helps you?
Sub tst()

    Dim ie As New SHDocVw.InternetExplorer
    Dim ieDOC As HTMLDocument
    Dim ieONC As IHTMLElement
    Dim ieONCs As IHTMLElementCollection

    ie.navigate "[your url]"
    ie.Visible = True
    Do: DoEvents: Loop Until ie.readyState = READYSTATE_COMPLETE
    Do: DoEvents: Loop While ie.Busy = True

    Set ieDOC = ie.document
    Set ieONCs = ieDOC.getElementsByClassName("[class]")

    For Each ieONC In ieONCs

        Debug.Print ieONC.onclick

    Next

End Sub


text:
Q: Spring Exception: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported I have a ResponseEntiy that receives a comment:
@RequestMapping(value="/save-comment", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> saveComment(@RequestParam("name") String comment, @RequestParam("id") long id) {

    SiteUser user = authController.getUser();

    String cleanedCommentBody = htmlPolicy.sanitize(comment);

    StatusUpdate status = statusUpdateService.getOneById(id);

    Comment createdcomment = new Comment();
    createdcomment.setCommentdate(new Date());
    createdcomment.setCommenttext(cleanedCommentBody);
    createdcomment.setStatusUpdate(status);
    createdcomment.setSiteUser(user);

    commentService.createComment(createdcomment);

    return new ResponseEntity<>(null, HttpStatus.OK);
}

The code in my JSP works fine.... it sends the values to my Controller method and the method receives it, process the information and saves the new comment in the database, but after that, showing the same page.... it gives me the error. But other POST request I have work fine.
http://192.168.160.128:8080/viewonestatus/58
Exception: org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported
Failed URL: http://192.168.160.128:8080/viewonestatus/58
Exception message: Request method 'POST' not supported

The AJAX snippet is that gives an ok code is:
.....
<c:url var="saveComment" value="/save-comment" />
.....

function saveComment(text) {
    //alert("El texto es...text " + text);
    editComment(text, "${status.id}", "${saveComment}");
}

function editComment(text, id, actionUrl) {

    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");

    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        jqXHR.setRequestHeader(header, token);
    });

    $.ajax({
        'url' : actionUrl,

        data : {
            'name' : text,
            'id' : id
        },

        type : 'POST',

        success : function() {
            alert("Ok");
        },

        error : function() {
            alert("error");
        }
    });
}


text:
Q: Search in multiple tables with priority I could use some input on the best way to develop the following search script:

*

*The client got a database with multiple tables (wiki, blog, articles and so on)

*The wiki and blog got a seperate table with tags.

If a user searches on a certain (or multiple) keyword(s) the script first has to check if there is an exact match on these tags (where a wiki has priority over a blog). These matches should show up first in the results.
Then it has to check if there is a match on the title (where again a wiki has priority over a blog, the blog over articles, etc). The last step is to check the relevancy in the content of the tables.
At the moment we just do a fulltext search on the tables with a priority factor for the titles, but this does not take into account 1) the priority for tags 2) the priority for wiki over blog articles (and so on).
Is there an efficient way to solve this?

A: From the top of my head, a few starting points:
Chaining Queries
The pretty much most simple solution would be to just do a lot of queries (match wiki tags, then match blog tags, then match wiki title, then match blog title, ...) but that probably wouldn't be very efficient.
Depending on your table structures, you could speed this up a bit by mashing everything into a single query using UNION statements and ordering that, but I imagine this would look really bad in code.
Building a search index
If all you want is a full-word match (so "and" matches "here and there" but not "in my hands") you could also build your own search index.
In its most simple form, that would be another table with, for example, those columns:

*

*keyword: this should obviously be an index (but not a unique one) and holds the search term

*source type: this indicates what type of content this is (blog article, wiki page, ...) and it could either be a string or an integer (which would make ordering more easy)

*source ID: this is the primary key in the respective content table, e.g. die blog article ID or the wiki page ID

*match type: indicates where the keyword appears, for example 0 = tag, 1 = title, 2 = content

Now, whenever new content is added, you have to dissect it and feed the search index with it. You would split the title and content into single words and add each as a new row into the search index table (with match type = 1 or 2, respectively) and also add each tag (as match type = 0). The same goes for updated content, only you have to remove its old search index entries first. For the initial building and if something goes wrong, you should also have a "re-build search index completely" routine.
Your search engine now only has to use the new search table which should be reasonably efficient. You can also do further optimizations by setting this table up as an in-memory table, use another database engine or whatever you come up with.
Use Lucene
Depending on your requirements, you could also look into Apache Lucene, which is a great search library that has its own query language and is really fast even for huge data sets.
There is also a PHP implementation of this (ZendSearch), but when I tried it a while ago, it wasn't fast enough for me.
In my last project I used Lucene along with Apache Solr, which serves as a REST frontend for Lucene. I had it running on a Tomcat server that only listened to 127.0.0.1. There is a PECL extension for using Solr servers: http://pecl.php.net/package/solr
Of course, that's quite a lot to set up (needs a full Java environment, a memory-consuming application server and a PHP extension) and also a lot to learn, but it's a really powerful solution that scales the best.

A: You're not telling what kind of app this is.
If it's a web app shooting different queries to the server asynchronously could be a simple solution. Send the most important queries first, they are in all likelihood also the fastest queries. Update the displayed results when the data comes back.
The downside is that you will have overlapping result sets. Filtering that by ID is not a probelm, but the server is sending back too much data. Only you can tell how (un)important that is.


text:
Q: Get Number after a text in Python I need some help with getting numbers after a certain text
For example, I have a list:
  ['Martin 9', '    Leo 2 10', '    Elisabeth 3']

Now I need to change the list into variables like this:
Martin = 9
Leo2 =10
Elisabeth = 3

I didn't tried many things, because I'm new to  Python.
Thanks for reading my question and probably helping me

A: I suppose you get some list with using selenium so getting integer from list works without using re like :
list = ["Martin 9","Leo 10","Elisabeth 3"]
for a in list:

    print ''.join(filter(str.isdigit, a))

Output :
9
10
3

A: Lets assume you loaded it from a file and got it line by line:
numbers = []
for line in lines:
   line = line.split()
   if line[0] == "Martin": numbers.append(int(line[1]))

A: I don't think you really want a bunch of variables, especially if the list grows large. Instead I think you want a dictionary where the names are the key and the number is the value.
I would start by splitting your string into a list as described in this question/answer.
s=
  "Martin 9
  Leo 10
  Elisabeth 3"
listData = data.splitlines()

Then I would turn that list into a dictionary as described in this question/answer.
myDictionary = {}
for listItem in listData:
    i = listItem.split(' ')
    myDictionary[i[0]] = int(i[1])

Then you can access the number, in Leo's case 10, via:
myDictionary["Leo"]

I have not tested this syntax and I'm not used to python, so I'm sure a little debugging will be involved. Let me know if I need to make some corrections.
I hope that helps :)

A: s="""Leo 1 9
Leo 2 2"""

I shortened the list here
look for the word in the list:
    if "Leo 1" in s:
then get the index of it:
i = s.index("Leo 1")

then add the number of character of the word
lenght=len("Leo 1")

And then add it: (+1 because of the space)
b = i + lenght + 1

and then get the number on the position b:
x = int(s[b]

so in total:
if "Leo 1" in s:
  i = s.index("Leo 1")
  lenght = len("Leo 1")
  b = i + lenght + 1
  x = int(s[b])


text:
Q: php Embedding single quote within double quotes won't work Please help. I'm really stuck on this and I'm learning PHP. I know the basics but I need to learn advance things like below:
echo "
$_POST[quiz_complete]
"; //this code won't execute
//Note: variable $_POST['quiz_complete'] exists
echo "
$str
"; //works fine

This ' single quotes don't work. How do I get single quotes to work within a variable that's inside double quotes for eg)
echo "<p>$_POST['quiz_complete']<p>";

A: Try this:
echo "
{$_POST['quiz_complete']}
"

or I would actually prefer
echo '
' . $_POST['quiz_complete'] . '
'

Syntax highlighting will make it much easier to read.

A: You can try
echo "
$_POST[quiz_complete]
";

Or
echo "
".$_POST['quiz_complete']."
";

Actually there is no need of quotes for an array key, if you are using it inside  double quotes.

A: echo "
".$_POST['quiz_complete']."
";


text:
Q: There is no directive with "exportAs" set to "routerLinkActive" I am using the mat nav list component for tab and navigation purpose inside my application. It works perfectly on front end but throws error on test case.

Getting the below error from karma.

 There is no directive with "exportAs" set to "routerLinkActive" ("        *ngFor="let tab of tabs"
             [routerLink]="tab.path"
             [routerLinkActive] [ERROR ->]#rla="routerLinkActive"
             [active]="rla.isActive"
             selectedIndex="0"

component.html

<nav mat-tab-nav-bar>
        <a
            mat-tab-link
            *ngFor="let tab of tabs"
            [routerLink]="tab.path"
            [routerLinkActive] #rla="routerLinkActive"
            [active]="rla.isActive"
            selectedIndex="0"
        >
            <i class="{{tab.icon}}"></i>
            {{ tab.label }}
        </a>
    </nav>

A: With the referene of
Angular 4 Error: No provider for ChildrenOutletContexts in Karma-Jasmine Test thread added the RouterTestingModule.
Solved the karma error.

A: I think you need to add RouterTestingModule to your tests, at the component level. Like this:
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { SettingsComponent } from './settings.component';
    import { PageService } from '../../services/page.service';

    import { MaterialModule } from '../shared/material/material.module';

    describe('SettingsComponent', () => {
      let component: SettingsComponent;
      let fixture: ComponentFixture<SettingsComponent>;
      let pageServiceSpy;

      beforeEach(async(() => {
        pageServiceSpy = jasmine.createSpyObj('PageService', ['setPageHeader']);

    TestBed.configureTestingModule({
      declarations: [
        SettingsComponent
      ],
      imports: [
        RouterTestingModule,
        MaterialModule
      ],
      providers: [
        { provide: PageService, useValue: pageServiceSpy}
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SettingsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

A: You just need this in your test code:
@Directive({
  selector: '[routerLinkActive]',
  exportAs: 'routerLinkActive'
})
export class RouterLinkActiveDirectiveStub {
}

Here exportAs is set to 'routerLinkActive'


text:
Q: setState not working after submit but data is updated in database I am new to react and Im  working on reactjs with laravel api.
I designed a form using reactjs and plan on submitting the data of the form to phpmyadmin database using laravel as the api.
The problem is if I submit the data, I use setState to empty the form data, but it doesnt; but the data gets entered into the phpmyadmin database. I even try to log the response from the api to the console, but there is no message on the console of the browser.
Here is my code on the react end:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Addstudent extends Component {
  state = {
    name: '',
    course: '',
    email: '',
    phone: '',
  };

  handleInput = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  saveStudent = async (e) => {
    e.preventDefault();

    const res = await axios.post(
      'http://localhost:8000/api/add-student',
      this.state
    );

    if (res.data.status === 200) {
      console.log(res.data.message);
      this.setState({
        name: '',
        course: '',
        email: '',
        phone: '',
      });
    }
  };

  render() {
    return (

Add Students

                  <Link to={'/'} className="btn btn-primary btn-sm float-end">
                    Back
                  </Link>

                  <form onSubmit={this.saveStudent}>

                      Student Name
                      <input
                        type="text"
                        name="name"
                        onChange={this.handleInput}
                        className="form-control"
                        placeholder="Enter Name"
                        value={this.state.name}
                      ></input>

                      Student Course
                      <input
                        type="text"
                        name="course"
                        onChange={this.handleInput}
                        className="form-control"
                        placeholder="Enter Course"
                        value={this.state.course}
                      ></input>

                      Student Email
                      <input
                        type="text"
                        name="email"
                        onChange={this.handleInput}
                        className="form-control"
                        placeholder="Enter Email"
                        value={this.state.email}
                      ></input>

                      Student Phone
                      <input
                        type="text"
                        name="phone"
                        onChange={this.handleInput}
                        className="form-control"
                        placeholder="Enter Phone"
                        value={this.state.phone}
                      ></input>

                      <button type="submit" className="btn btn-primary">
                        Save Student
                      </button>

                  </form>

    );
  }
}

export default Addstudent;

On the Laravel end Here is the code on the controller handling the post request:
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    public function store(Request $request){
        $student = new Student;
        $student->name =$request->input('name');
        $student->course =$request->input('course');
        $student->email =$request->input('email');
        $student->phone =$request->input('phone');

        $student->save();

        return response()->json([
            'status'=> '200',
            'message'=>'Student Added Successfully',
        ]);
    }
}

A: Your handleInput function is overwriting your state with only one property, you have to keep the old data:
this.setState(s => ({
  ...s,
  [e.target.name]: e.target.value,
}));

Otherwise you will never send all values to the API, assuming it is working correctly there
if (res.data.status === 200) {
  console.log(res.data.message);

This logging is great if everything works well, but you may want to log if things go wrong too, so you could notice that you're not sending all values to the database:
try {
   const res = await axios.post(
     'http://localhost:8000/api/add-student',
     this.state
   );
   // ... code using res
} catch(e) {
  console.error(e);
}


text:
Q: same DNS name internal and external server My internal domain name with the same name as the external domain.
when I'm tying to access to external domain from inside it is working properly with A record but my problem is the external IP changes everyday.
What is the easiest way to solve that issue ?
Thanks,

A:
My internal domain name with the same name as the external domain.

That is an unfortunate choice...

my problem is the external IP changes everyday.

Upgrade your internet subscription from consumer grade to a (small) business contract with both a static ip-address and a real SLA.
Alternatively use DynDNS to update a hostname with the correct ip-address whenever yours changes and point a CNAME-record to that hostname instead of the A-record.


text:
Q: How can I get a JSON object out of my ruby application into the terminal? I have a ruby program that I invoke via terminal. When I invoke a particular command, I want to get my JSON response object as a string in the terminal. How can I do this? I've tried storing the output (printed with say_ok) of the command in a bash variable, but have had no luck. I'm not sure what the correct approach is here, so any help is appreciated.
Ruby
say_ok response.body

Bash
JSONOBJECT=$(myrubyapp postandgetresponse)

echo "${JSONOBJECT}"

Edit:
Returning the object instead of say_ok seems to of have worked. I will update once verified.

A: If you want to capture script output from stdout to bash variable, you can do it like this:
% CAPTURE=$(ruby -e "puts 'hello'" | tee /dev/tty)
hello
% echo $CAPTURE
hello


text:
Q: Largest set of matrices that have unique root Does the set of all positive definite matrices is the largest set that one can get unique root?
for all matrices in the set $A \in \mathcal{P}(M_n(\mathbb C))$, for all n, the largest set that every matrix $B \in A$ have unique matrix $C \in A$ s.t $C^2=B$ is the set of all positive definite matrices?
and what if the matrix has unique nth root for all n ($C^n=B$)?

A: We can do better. Take $Z=\{B\in M_n(\mathbb{C})|spectrum(B)\subset T\}$, where $T=\{a+ib\in\mathbb{C}|b\geq 0$ and if $a\leq 0$, then $b>0\}$. Take $C=\exp(1/2\log(B))$ where $\log(.)$ is the principal logarithm.
EDIT. For the $n^{th}$ root, the answer is the same as above.


text:
Q: Defining a signed involution We define the displacement of $\pi$ as $\mathrm{disp}(\pi)=\sum_{i=1}^n|\pi(i)-i|$. I know that it's even. Could you help me to find a good signed involution of the set of permutation with displacement $2k$ that helps me (counting the fixed points) to solve this problem:
let $e_{n,k}$ (Respectively $o_{n,k}$) be the number of even (odd) permutations in $S_n$ with displacement $2k$, then

$e_{n,k}-o_{n,k}=(-1)^k\binom{n-1}{k}$

Thank you
(signed means that if a permutation is not fixed then if it is even the image is odd and if it is odd the image is even)
(using the involution we should get a recurrence for $f_{n,k}=e_{n,k}-o_{n,k}$ and then solve it)


text:
Q: How to send SGD commands to USB printer? I am trying to use SGD commands on Zebra 420 USB printer.
printf "! U1 getvar \"device.languages\"\r\n" | lpr -P myprinter -o raw

I expect this will print current lang value, but getting empty string. How to properly send command and receive response?
UPDATE: some dmesg related info
[    2.912815] usb 1-1.3: new full-speed USB device number 4 using dwc_otg
[    3.048399] usb 1-1.3: New USB device found, idVendor=0a5f, idProduct=0065
[    3.057429] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[    3.066719] usb 1-1.3: Product: ZTC ZM400-200dpi ZPL
[    3.073649] usb 1-1.3: Manufacturer: Zebra Technologies
[    3.080757] usb 1-1.3: SerialNumber: XXX999999
[    3.931237] udevd[156]: starting version 175
[    6.294509] bcm2835-rng 20104000.rng: hwrng registered
[    8.580407] gpiomem-bcm2835 20200000.gpiomem: Initialised: Registers at 0x20200000
[    8.934595] random: lpinfo urandom read with 87 bits of entropy available
[    9.215446] usblp 1-1.3:1.0: usblp0: USB Bidirectional printer dev 4 if 0 alt 0 proto 2 vid 0x0A5F pid 0x0065
[    9.235924] usbcore: registered new interface driver usblp

[   31.371525] usblp0: removed
[   31.441360] usblp 1-1.3:1.0: usblp0: USB Bidirectional printer dev 4 if 0 alt 0 proto 2 vid 0x0A5F pid 0x0065
[   31.835757] warning: process `colord-sane' used the deprecated sysctl system call with 8.1.2.

UPDATE 2: print to usb device
root@raspberrypi:/home/pi# printf "! U1 getvar \"device.languages\"\r\n" > /dev/usb/lp0


text:
Q: Unable to locate package `docker-ce` on a Ubuntu Cloud 18.04 LTS I'm trying to install Docker on a Ubuntu Cloud 18.04 LTS following official installation docs. On another Ubuntu 18.04 installation everything works fine, but it is a Ubuntu Workstaion 18.04. On a cloud version I've got error "Package 'docker-ce' has no installation candidate" after executing sudo apt-get install docker-ce. Repository recommended by documentation is installed. Any idea what should I do?
Some details:
sudo apt-get install docker-ce
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package docker-ce is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  docker-ce-cli:amd64

uname -a
Linux ubuntu02 4.15.0-65-generic #74-Ubuntu SMP Tue Sep 17 17:12:56 UTC 2019 i686 i686 i686 GNU/Linux

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic

Thanks for showing interest.

A: The Ubuntu 18.04 package for the Docker container runtime is docker.io.  You would run apt-get install docker.io to install it from the default Ubuntu repositories.
The docker-ce package comes from Docker, not from Ubuntu.  You would have to configure their repository to get that package.

A: To install docker-ce you should have the 64-bit version of Ubuntu Cloud (ubuntu cloud image 18.04).

OS requirements
To install Docker Engine - Community, you need the 64-bit version of one of these Ubuntu versions:
Disco 19.04
Cosmic 18.10
Bionic 18.04 (LTS)
Xenial 16.04 (LTS)
Docker Engine - Community is supported on x86_64 (or amd64), armhf, arm64, s390x (IBM Z), and ppc64le (IBM Power) architectures.


text:
Q: Should i use thread safe or non thread safe for my Singleton class for my purpose? I want to implement Singleton and found this acrticle from MSDN with several examples:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
I have application that host WCF service.
the application get String from Client, and sent this string to my Singleton.
And from Singleton class i am open my Job class that do my stuff (open process..).
The job class contain Event that each time process started to ends update my UI.
and Singleton class should subscribe to this event.
Also i am open new Singleton instance when my application start.
My service ServiceBehavior defined as ConcurrencyMode.Multiple and InstanceContextMode.PerSession so every client message create new instance:
[ServiceBehavior(
    ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.PerSession)]

so my only qustion is shold i use thread safe or non thread safe in my Singleton class ?

A: Yes, a singleton should be thread safe.

A: You should always opt for the thread-safe version when you are building something that can be modified. If it is a read-only collection then thread safety is not important.
Thread safety will incur a small performance cost usually due to locking, but it will save you a lot of potential pain later as race conditions are usually hard to debug.

A: Thread unsafe may end up with weird results, possible to create more than 1 instance, which violates the singleton pattern. Thread Safe singleton is a good way to go.
Take a look to Jon Skeet's article, with different approach like Thread Safety, lazy instantiation etc.
http://csharpindepth.com/articles/general/singleton.aspx


text:
Q: Check no dups in list and within number range I am attempting to check a list (of six numbers) for duplicates and that it falls within this number range (inclusive) 20 - 100.
I can get it to work for any number that is less than 20:
 for value in list_input:
        if len(list_input) != len(set(list_input)) or any(i <= 19 for i in list_input):
            return "Entered incorrect number combination, please try again"
        else:
            y = combination(81,6)
            return "Your chances of winning are 1:{:,}".format(int(y))

I tried this for line 2, but it doesn't work
if len(list_input) != len(set(list_input)) or any(100 < i <= 19 for i in list_input):

Am I just misunderstanding how List Comprehensions work?

A: Instead of using any, why not to use all:
for value in list_input:
        if len(list_input) != len(set(list_input)) or not all(20 <= i <= 100 for i in list_input):
            return "Entered incorrect number combination, please try again"
        else:
            y = combination(81,6)
            return "Your chances of winning are 1:{:,}".format(int(y))


text:
Q: How do you tell if a context manager is reusable or reentrant? The Python contextlib docs note that context managers can be single-use, reusable, or reentrant. Reentrant ones can be used in more than one with statement including nested ones; reusable but not reentrant ones can be used in more than one with statement but not nested. A couple of examples are mentioned.
https://docs.python.org/3/library/contextlib.html#reentrant-context-managers
The docs for other context managers don't always mention what they are, though. For example, the docs for the patch context manager in unittest.mock don't mention this at all.
In general, what would you look at in the source to determine if a context manager is single use, reusable or reentrant?

A: One good way is to look at the object being returned/modifed or context being set up by the __enter__ call, and then see what happens to that object/context in the __exit__ call. Usually understanding how the state is actually being changed in each of those will make it obvious what will happen if you nest or re-use that object.
For example, when you with open("somefile") as f: you're getting a file handle back. In the __exit__, you're closing that file handle. Of course, it doesn't make sense to re-open a file handle object once its closed, nor does it make sense to open an already open file handle. And of course, closing the inner file handle will also close the outer file handle, which will be problematic. This is why no one ever does this:
f = open("file.txt")
with f:
  # stuff
# File will get closed here

There's no point in using f after it's closed, so we always use:
with open("file.txt") as f:

threading.Lock and threading.RLock objects can be used as context managers, too. Doing this makes sense:
l = threading.Lock()
with l: # This acquires the lock
    # stuff
# Lock got released

with l: # Acquired again
    # more stuff
# Released again

This does not, because Lock will deadlock if you try to take it recursively
l = threading.Lock()
with l:
    #  stuff
    with l: # Uh-oh, we tried acquiring an already acquired Lock. We'll deadlock here.

But that will work fine with RLock(), which can be acquired recursively.
Another example from the stdlib: multiprocessing.Pool() can be be used as a context manager in Python 3.3+. Here's what the docs say:

Pool objects now support the context manager protocol. __enter__() returns the pool object, and __exit__() calls terminate().

terminate() says it does this:

Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected
  terminate() will be called immediately.

Clearly, that's a one-time use.
The patch context manager is temporarily patching some object, and then undoing the patch when it's done. Nesting definitely doesn't make sense there - why would you want to re-patch something that's already patched? However, patching, unpatching, and then patching again does make sense logically, so it should be reusable (which testing shows is the case).
I don't think there is really any well-defined set of things that you can say "look for this and you'll know a context manager is reusable/re-entrant/one-time" because a context manager can literally do anything. The best you can do is understand what context is being established when in __enter__, how it's being broken down __exit__, and then logically determine what the implications of reusing/re-entering that context is.


text:
Q: How to manage Ontology classes in Python I have a very simple Ontology which has only Classes and Subclasses.
I need a way to access the classes and subclasses name's knowing what is the relation between them (x is subclass of y, x is subsubclass of z, etc...).
I've been using the library Ontospy to open owl files in a structured way but couldn't find functions that helps me doing what I need.
Using an Ontology file (.owl) I want to create a window full of checkboxes illustrating the Ontology in a tree way just like this:

There is a method in the Ontospy library named "printCLassTree()" which prints all classes in a tree form using stdout.
if I could get the output of this method in a string or a list that would help me a lot.


text:
Q: Naming convention for List variables I have a question that may seem pretty trivial to many, but it's one that has made me think repeatedly about the readability of the code that I write.
Lets assume that I have a class that encapsulates details of an entity, such as an employee, called EmployeeDetails. (Note - I also have a class named Employee which exists at the DAO layer. I do not want to return any DAO level classes from my service methods, which is why I created the EmployeeDetails class to be returned from my service layer methods. I also wanted to avoid confusion between class names by keeping the service and DAO layer class names distinct).
I also have a service level method that, given a list of Employee numbers, returns a List<EmployeeDetails>. My question is this - what is the best coding convention for naming the return variable? I had two options in mind.

*

*employeeDtls - I do not like this because the person who reads my code may think that "employeeDtls" refers to an instance of EmployeeDetails instead of a list.

*employeeDtlsList - I do not like this because it seems "too wordy".

Does anyone follow any specific coding conventions for variables? What is the most widely used naming convention for list variables?

A: Well...let's consider what we're modeling here.
A general rule of thumb, is that if it's a collection, then it should be pluralized and scoped to the contents of what you expect.
So, that'd make your variable name List<EmployeeDetails> details or List<EmployeeDetails> employees.  If you can help it, try to avoid the compound name, unless that truly and concretely represents what it is you're getting back.
If you were using the Data Transfer Object model, and you had named it something along the lines of EmployeeDto, then the name of the variable would be more specific at employees, as you expect back some collection of something representing an Employee (at its core).

A: I usually name the return variable result, for all methods:
List<EmployeeDetails> result;

The reason is that it's obvious which list I'm adding to, and that it's gong to be returned, especially if there are multiple lists within the method.
This also conforms to good practice by naming things for what they represent, rather than what are they are. Your idea is a bit like naming an int variable as intVariable. Naming it simply result means you can change they type of the result, eg to Set<EmployeeDetails> without any refactoring of the name.

A: I would rather call the class EmployeeDetail so it is a singular noun which represent "detail information" of an employee.
Then the variable naming will be straight forward for its collection : employeeDetails
In case I really encounter a class named in plural form (for which I usually try to avoid), I usually use ~List as the variable name for the collection of such type.  Although it is a bit too verbose, at least it doesn't cause any confusion.

A: Use DTO (Data Transfer Object) pattern to carry the data of underlying entity.
In your case, EmployeeDetails should be EmployeeDTO
Take a look at discussion here


text:
Q: .NET C# Using TreeView in WinForms like tab control I want to use TreeView in my software so when user clicks a node, the content of the Form will be changed. Example in this picture, but also I want to grab user input from all forms.
WinForms TreeView example
https://youtu.be/9BdYzMDxl9M?t=46
TreeView -> Node -> User Click -> Display Form_X in the GroupBox
I tried but I could not find related resources on this topic so I posted this question.  Thank you for your help

A: Don't use forms as child controls. User controls exist specifically for that so use them. You add a user control to a project in the same way as you do a form, simply selecting a different menu option. You then design it and add code to it just as you would a form. Once you build your project, the user control will appear in the Toolbox and you can use it just like you would any other control. You then have a couple of options for how to handle switching controls via the TreeView.
If the number of controls is fairly small, you can add one of each to the GroupBox in the designer, so they all exist all the time. You would probably want to set the Dock property of each to Fill, so they all fill the parent GroupBox. In the Load event handler of the form, you can assign each user control instance to the Tag property of the corresponding TreeNode. When the user selects a node, you get the user control from its Tag property and call BringToFront on it, so the user will see it and it will hide all the other user controls, e.g.
private void Form1_Load(object sender, EventArgs e)
{
    var nodes = treeView1.Nodes;

    nodes[0].Tag = userControl1;
    nodes[1].Tag = userControl2;
    nodes[2].Tag = userControl3;
}

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    var userControl = treeView1.SelectedNode.Tag as Control;

    userControl?.BringToFront();
}

Because all the controls exist all the time, you can load all the data at the start and save all the changes at the end and not have to transfer any data when the selection changes.
If the number of controls is larger, you might want to show just one at a time. That becomes more complex because, when the selection changes, you have to make sure that any changes in the current user control are remembered, remove the existing control and then create and load the new control. Because the process is more complex, there are more options about exactly how to implement it. For that reason, I won't go into specifics here. If you want to go that way, you need to consider those options and how they relate to the specifics of your application and then decide how you want to implement the process. If you do that and encounter an issue along the way, that would be another question.

A: What have you tried? I am confident there are many ways to achieve what you describe. Since you mentioned a TabControl have you considered using a TabControl without the Tabs and manually switch to the proper tab page whenever the tree view node is clicked.
Something like…

private void Form1_Load(object sender, EventArgs e) {
  tabControl1.Appearance = TabAppearance.FlatButtons;
  tabControl1.ItemSize = new Size(0, 1);
  tabControl1.SizeMode = TabSizeMode.Fixed;
}

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
  if (e.Node.Name == "TabPage1") {
    tabControl1.SelectTab("TabPage1");
  }
  else {
    tabControl1.SelectTab("TabPage2");
  }
}


text:
Q: Getting error while creating CI pipeline for gitlab with aws I am creating a ci pipeline in gitlab with aws using below code to work for ci. I have to execute only 3 stages for it and I have posted for code for coverage only as I am getting error init
coverage:
stage: test
tags:
    - aws-runner
only:
    - Feature/CI
image: python:3.7-slim
coverage: '/TOTAL\s+\d+\s+\d+\s+(\d+%)/'
script:
    - pip install coverage moto mock pytest
    - MIN_COVERAGE=85
    - pip3 install --upgrade pip setuptools wheel
    - pip3 install -r requirements.txt
    - coverage run --omit 'utility/*' -m pytest tests/
    - coverage report -m
    - coverage html
    - COVERAGE=$(coverage report -m | grep -i "TOTAL" | awk '{print $4}' | sed 's/%//')
    - if [ "$COVERAGE" -lt "$MIN_COVERAGE" ]; then exit 1; else exit 0; fi
artifacts:
    expire_in: 7 days
    paths:
       - htmlcov/

This is the error for above code
 $ coverage run --omit 'utility/*' -m pytest tests/
 ============================= test session starts==============================
 platform linux -- Python 3.7.11, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 rootdir: /builds/test-backend
 collected 0 items
 ============================ no tests ran in 0.00s =============================
 ERROR: file or directory not found: tests/
 Coverage.py warning: No data was collected. (no-data-collected)
 Cleaning up file based variables
 00:02
 ERROR: Job failed: exit code 1

As I am new to this, Any suggestion?
How can I solve this?

A: I think you need to check the test directory exist or not and it should have .py files


text:
Q: "param is missing or the value is empty:" Paperclip no file selected - Rails I am building a photo gallery application that allows users to attach multiple photos to each of their galleries. I am using Paperclip to handle file uploads.
The below code works fine until [Upload] is clicked on the form with no file selected. As I understand it, it is getting stuck at the controller before it is handed over to the Photo model to run it's presence, file-type and file-size validations.
The error received when clicking [Upload] with no file selected is:
"param is missing or the value is empty: photo"
Extracted source has photo#photo_params line highlighted.
Gallery model:

class Gallery < ActiveRecord::Base
  belongs_to :user
  has_many :photos
end

Photo model:

class Photo < ActiveRecord::Base
  belongs_to :user
  belongs_to :gallery

  has_attached_file :photo,
    s3_permissions: :private

  validates_attachment :photo,
    presence: true,
    content_type: {
      content_type: [
        "image/jpeg", # JPEG/JPG
        "image/png" # PNG
        ] },
    size: { in: 0..5.megabytes }
end

Controller action (photos#create):

  def create
    @photo = Photo.new(photo_params)
    @photo.gallery_id = @gallery.id
    @photo.user_id = current_user.id

    if @photo.save
      flash[:success] = "Photo successfully saved."
      redirect_to gallery_path(@photo.gallery)
    else
      flash[:error] = "The photo upload failed! Make sure the file you're trying to upload is of a supported type (JPG, JPEG or PNG) and try again."
      redirect_to gallery_path(@photo.gallery)
    end
  end

Strong Params (photos#photo_params):

def photo_params
  params.require(:photo).permit(:photo)
end

Upload form:

<%= form_for Photo.new, url: gallery_photos_path(@gallery) do |f| %>
    <%= f.label :photo %>
    <%= f.file_field :photo %>

    <%= f.submit "Upload" %>
  <% end %>

I realise that using Model.new in the form is probably not a best-practice but because the form is loaded as a partial on galleries#show view, it was the only way i could get it going.
I am also thinking that having the model named :photo and the actual Paperclip attachment also named :photo may also be causing an issue. Is this correct?
Does anyone know what's going on here?

A: Yes i think like you mentioned you should rename your paperclip attachment though i'm not sure if it causes any issues, having code like photo_params.require(:photo).permit(:photo) cant be any good.
Additionally for your else condition in create, try redirecting to root_path first. I think your route may be wrong since your @photo instance variable is actually Photo.new.
Hope it helps a! Im not a rails expert. Cheers.

A: Looking at the error, I think it is validating presence of 'photo' in params.
As you have added 'presence: true' in  validates_attachment :photo block, you must provide that in params
OR
if you want to upload form without file you should remove 'presence: true' constraint.

A: def photo_params
    params.require(:photo).permit(:photo)

end
change the name of attribute it's getting confuse with modal and attribut name may be
def photo_params
params.require(:photo).permit(:photo_url)
end


text:
Q: Is there a way to impute or predict the NANs in this triangular dataframe? This DataFrame has values over the upper left triangle and the diagonal, with the rest of values being NANs
I don't want to use a looping linear regression model which would work on a sample size of 1.
I assume there is a simple way to do that.
Thanks


text:
Q: Python ggplot is not plotting dataframe I am trying to plot the following data frame. X and Y are lists. After I prepare those lists I construct the data frame via dictionary. But when I plot it doesn't actually plot.
df = pd.DataFrame({"day": day, "ndcg@k": x, "MAP@k": y})
df2 = pd.melt(df[['day', 'ndcg@k', 'MAP@k']], id_vars=['day'])
ggplot(aes(x='day', y='value', group='variable', shape='variable', colour='variable'), data=df2) + geom_line() + geom_point()

And my data looks like this (both before melt and after melt)
      MAP@k       day    ndcg@k
0  0.201919  20150203  0.245559
1  0.198214  20150204  0.241085

        day variable     value
0  20150203   ndcg@k  0.245559
1  20150204   ndcg@k  0.241085
2  20150203    MAP@k  0.201919
3  20150204    MAP@k  0.198214

A: It is working for me. Try following
import pandas as pd
from  ggplot import *

df = pd.DataFrame([{"day": 20150203, "ndcg@k": 0.245559, "MAP@k": 0.201919},
                   {"day": 20150204, "ndcg@k": 0.255559, "MAP@k": 0.191919},
                    {"day": 20150205, "ndcg@k": 0.2645559, "MAP@k": 0.181919},
                    {"day": 20150203, "ndcg@k": 0.275559, "MAP@k": 0.171919},
                    {"day": 20150204, "ndcg@k": 0.285559, "MAP@k": 0.161919},
                    {"day": 20150205, "ndcg@k": 0.295559, "MAP@k": 0.151919}])

df2 = pd.melt(df[['day', 'ndcg@k', 'MAP@k']], id_vars=['day'])
df2.day = pd.to_datetime(df2.day, format = '%Y%m%d')
ggplot(aes(x='day', y='value', group='variable', shape='variable', colour='variable'), data=df2) + geom_line() + geom_point() + scale_x_date(labels = date_format('%Y-%m-%d %H:%M'))


text:
Q: VBA New Database Connection How to change the code below to prevent what you see in the screenshot.
I am running a macro with the following code
Dim conn As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim thisSql As String

Set conn = New ADODB.Connection

Dim sConn As String
  sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=xyz;Database=xyz;UID=xyz;PWD=xyz"
conn.Open sConn

' this is creating multiple connections.
Set rec1 = New ADODB.Recordset
rec1.Open thisSql, conn

which runs a SQL Server query (which is around 20 lines long and contains 4 joins). Everything is fine except for the fact that after a couple times of running it my DB admin says that my query is loading up the DB too much.
Now, my query could be causing the problem, or it could be that Excel is starting to run multiple connections at once. Some evidence for this is the screenshot below and the fact that the load on the database appears to increase with time.
How do I establish a DB connection without constantly creating new connections?
Has anyone had similar problems working with Excel DB macros?

UPDATE
While the answers below were very useful (especially for someone starting out in VBA), it seems that the main reason my query was taking up load was a combination of multiple connections and having overlooked a line in my code:
    With Sheets("FVols").QueryTables.Add(Connection:=rec1, Destination:=Sheets("FVols").Range("A1"))
    .name = "data"
    .FieldNames = True
    .Refresh BackgroundQuery:=True <<<<<<<<<<<<<<<<<<<<<<<-----

End With

A: You only need to open the connection once. That literally means you can execute multiple queries on that one active connection. You must close the connection and free the reference (specially with ADODB) to avoid running into collisions and other connection related problems.
If you know the queries you are going to be executing you can create an array (or collection) and add queries to the queue.
While you already have an open connection to work with you can keep executing queries.
Scan through code there is not much difference between yours and mine so you should be able to see what is going on and where. Please, ask questions in the comments if anything is unclear
   Sub DbConnection()

    Dim cn As ADODB.Connection
    Set cn = New ADODB.Connection
    Dim rs As ADODB.Recordset

    Dim strConn As String
    strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="

    cn.Open strConn

    Dim queryArr, i
    queryArr = Array("SELECT * FROM [MyTable]", "SELECT * FROM [MyOtherTable]")

    For i = LBound(queryArr) To UBound(queryArr)
        ExecuteQuery queryArr(i), cn, rs
    Next i

    cn.Close
    Set cn = Nothing
End Sub

Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
    Set rs = New ADODB.Recordset
    With rs
        .ActiveConnection = cn
        .Open CStr(query)
        Sheets(1).Range("A1").CopyFromRecordset rs
        .Close
    End With
    Set rs = Nothing
End Sub

Now, you only need to execute the DBConnection() once and all the queries you listed in the array will be executed.
Alternatively, if your queries are created at run-time you can pass it to the DbConnection() as a parameter.
Sub DbConnection(queryQueue As Collection)

    Dim cn As ADODB.Connection
    Set cn = New ADODB.Connection
    Dim rs As ADODB.Recordset

    Dim strConn As String
    strConn = "Driver={SQL Server};Server=HELIUM\PRI; Database=sourcedata; UID=tabula; PWD=Tabula123!"

    cn.Open strConn

    For i = 1 To queryQueue.Count
        ExecuteQuery queryQueue.Item(i), cn, rs
    Next i

    cn.Close
    Set cn = Nothing
End Sub

Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
    Set rs = New ADODB.Recordset
    With rs
        .ActiveConnection = cn
        .Open CStr(query)
        Sheets(1).Range("A1").CopyFromRecordset rs
        .Close
    End With
    Set rs = Nothing
End Sub

Update:
You can declare your connection as a Global Variable. Now you can run the DBConnection() as many times as you like and you will not be creating a new connection each time. Instead you will be using the global connection object.
Option Explicit

Public cn As ADODB.Connection

Sub DbConnection()

    Set cn = New ADODB.Connection
    Dim rs As ADODB.Recordset

    Dim strConn As String
    strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="

    cn.Open strConn

    Set rs = New ADODB.Recordset
    With rs
        .ActiveConnection = cn
        .Open "SELECT * FROM [MyTable]"
        Sheets(1).Range("A1").CopyFromRecordset rs
        .Close
    End With
    Set rs = Nothing

    cn.Close
    Set cn = Nothing
End Sub

A: Are you releasing the connection variable when you've finished with it? i.e.
Set rec1 = Nothing

The connection won't close fully if not.


text:
Q: How do I set up AWS instance store? Firstly, although knowing about AWS for a long time, this is the first time i've ever used it.
I gather that EBS volumes are for persistent data storage and instance store volumes are for one time use. I'm using the instances for data mining so they are launched on spot instances and use a lot of I/O while for filling requests for the master.
I cant use EBS because the I/O costs a fortune and i dont need the instance to survive, it gets a job from the master server, processes the job and returns it, no data needs to be saved on the instance. I feel that i need to use Instance Store but there doesn't seem to be a way to save an AMI and load it as an instance store. How am i meant to set this up ? I cant log into the instances every time to set them up, plus it takes 10 minutes to install required dependency. I assumed i'd be able setup the instance store instance, then save, and just load copys of that. Can anyone tell me where I'm going wrong or what i should do in this situation.
Thank you!

A: I wasn't aware of EBS costing a fortune. While you can provision high IOPS you don't have to.
While you can save a snapshot of your system there is another method. You can use scripts to setup your EC2s automatically. You can supply a script via EC2 User-Data and have that install all your required dependancies. You can also take advantage of software like Puppet, Chef, SaltStack to automate things.

A: We have a similar usage profile. This is what we do

*

*Build an EBS-backed instance with just the OS/Application stuff.

*

*Attach an Instance store to the new Instance and mount it where the ephemeral data is supposed to go.

*Make an AMI out of it.

*When spinning up a new instance, select the options to attach the ephemeral store to the correct spot in the file-system.

This allows us to have very small OS/app volumes (10GB) and very large working volumes for the ephemeral stuff we don't care about. The trick here is to be sure to make your instance-launch script maps the instance store to the right block device so the mount-scripts in the OS can handle it.

A: I believe what you want to do is create your own AMI from an existing instance. Here's a brief overview of the steps:

*

*I often use Ubuntu's Amazon EC2 AMI Locator to find the AMI I want. e.g. search for instance-store precise us-east to find the instance-store backed releases of 12.04 in us-east-1

*Launch the instance, login as ubuntu and customize it as needed. Note: you must install java and the Amazon EC2 AMI Tools for the later steps.

*Upload your Amazon EC2 private key and X.509 certificate to /tmp/cert on the instance. If you don't have them, you'll need to create and upload your signing cert

*Use ec2-bundle-vol to create an image of the current system

*Use ec2-upload-bundle to place the image on S3 for registration

*Use ec2-register to turn the uploaded bundle into an AMI you can launch.

As an alternative, you can use a loopback device and ec2-bundle-image to install an OS from scratch.


text:
Q: My solr suggestions doesn't display results I updated my solr to 4.9.1 (I want to implement solr Suggester) and updated its solrconfig.xml
<searchComponent name="suggest" class="solr.SuggestComponent">
  <lst name="suggester">
    <str name="name">mySuggester</str>
    <str name="lookupImpl">FuzzyLookupFactory</str>
    <str name="dictionaryImpl">DocumentDictionaryFactory</str>
    <str name="field">cat</str>
    <str name="weightField">price</str>
    <str name="suggestAnalyzerFieldType">string</str>
    <str name="buildOnStartup">false</str>
  </lst>
</searchComponent>

<requestHandler name="/suggest" class="solr.SearchHandler" startup="lazy">
  <lst name="defaults">
    <str name="suggest">true</str>
    <str name="suggest.count">10</str>
  </lst>
  <arr name="components">
    <str>suggest</str>
  </arr>
</requestHandler>

And here is my sunspot.yml
development:
  solr:
    hostname: localhost
    port: 8982
    log_level: INFO
    path: /solr/development

But when accessing http://localhost:8982/solr/development/suggest?suggest=true&suggest.build=true&suggest.dictionary=mySuggester&wt=json&suggest.q=ac There is no result value :
{"responseHeader": {
     "status":0,"QTime":38
   },
   "command":"build",
   "suggest":{
     "mySuggester": {
        "ac":{
          "numFound":0,
          "suggestions":[]
      }
    }
  }
}

Am I missing something important?
I followed the documentation for the Solr Suggester component.
How can I display the suggestions result for my solr?
Thank you :)


text:
Q: OpenXML - Powerpoint Is there an UpdateLinks or LinkFormat.AutoUpdate using open.xml? I have a PowerPoint template that is currently linked to an excel documents for charts (using the copy paste link as excel Chart Object).
I am successfully able to update the links to a new excel document reference, however I do not see a way to programmatically call the updatelinks() function that is available via Microsoft.Office.Interop.PowerPoint.Presentation.
When I open up the document I see it prompt for auto update, but I would like to achieve these programmatically and then set the link format to AutoUpdate manual, but via openxml and not through the interopt. Is there a way to do it?
TIA
Iris


text:
Q: Detecting fullscreen on Mac I am writing an IM client for Mac (in Python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if not, I will play the sound.
How can I detect this? Is there some way to get the foreground window with Applescript and look at its dimensions? Or is there some other API call?

A: To check for full-screen, call CGDisplayIsCaptured(screenID) on each screen.
But I'm not sure if you're checking the right thing. For one thing, I could have one screen captured ("full screen") and a second screen uncaptured, what do you want to do in this case?
Also, does fullscreen really mean anything? If I'm using GarageBand to work on a song, I probably don't want to hear random sounds, regardless of whether or not anything's full screen. Or I could be running a Windows VM full-screen, but still want to be notified of IMs.

A: not entirely sure how to do this, but the apple docs say:

To track changes in the login
  session's presentation mode, you may
  handle the
  kEventAppSystemUIModeChanged Carbon
  event

A: The two solutions posted so far apply to "real" full-screen, but it's worth noting that many full-screen apps just put a window over the whole screen (or, as vasi points out, a whole screen). To be accurate, you'll have to check both.

A: In Mountain Lion (and probably earlier), you can track the presence of the menu bar by monitoring the distributed notifications com.apple.HIToolbox.hideMenuBarShown and com.apple.HIToolbox.hideMenuBarShown.  No menu bar usually == fullscreen mode.  This works across apps, so you can tell when, say, VLC goes fullscreen, or when someone switches to iCal in fullscreen mode.
To do this, register for these two notifications:
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
        selector:@selector(windowDidEnterFullScreen:)
        name:@"com.apple.HIToolbox.hideMenuBarShown"
        object:nil];

[[NSDistributedNotificationCenter defaultCenter] addObserver:self
       selector:@selector(windowDidExitFullScreen:)
       name:@"com.apple.HIToolbox.frontMenuBarShown"
       object:nil];

then create your own selectors to handle those cases.  frontMenuBarShown fires all the time, so to catch a real return from fullscreen, watch for the first 'didExit' that follows a 'didEnter'...


text:
Q: Require node.js module in an internal typescript module I want to port a a multi-file node.js project to a multiple file Typescript project compiling to a single .js by using Typescript internal modules. How I can require a node.js module from an internal Typescript module? Here is a sample application:
a.js:
var os = require('os')
exports.foo = os.hostname()

b.js:
var os = require('os')
exports.foo = os.hostname()

How do I port the code to Typescript?
I have no problems until I want to require:
a.ts:
/// <reference path="b.ts" />
console.log(b.foo)

b.ts:
module b {
    export var foo = 42;
}

How do I change the code so foo = os.hostname() works?

A: Unfortunately you cannot mix --out with --module at the moment. TypeScript does not give an error the but the generated javascript is wrong


text:
Q: Using url parameters i am using php $_GET function get the parameter from previous page. Once I retrieve that i have assigned that to a session variable.
if(isset($_GET['pId'])) {
    $_SESSION['packageId']=$_GET['pId'];
}

echo $_SESSION['packageId'];

if($_POST['btnSubmit']) {
    $docId=$_SESSION['docId'];
    $appInfoId=$_SESSION['appinfo'];
    $_SESSION['patient_name']=$clName;
    $_SESSION['dob']=$dob;
    $_SESSION['address']=$address;
    $_SESSION['contactno']=$contactNo;
    $_SESSION['email']=$email;
    $_SESSION['packageId']=$packageId;
    header('Location: BookingClientInfo.php');
    exit;
}

Problem:
When the page is submitted the session is getting clear. But the other sessions used in the page are working fine. Finally I have redirected the page to same URL to check and found that session is getting empty.