text:
Q: google kubernetes engine node idle timeout We use GKE in one of our service which is autoscaled. The workload is variable and based on the workload the cluster scales upto hundreds of nodes. However i see that when the workload goes down many of the nodes which are idle still are alive for very long time and hence increasing our bill. Is there a setting we can do where we can specify a time after which a node will be terminated and removed from the cluster?

A: The Kubernetes scaling-down process typically includes a delay as a protection from peak traffic spikes that can eventually occurs while performing the resize.
As well, there are several aspect about the autoscaler to consider. Please check the following docs for details:

*

*https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#how-does-scale-down-work

*https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#what-types-of-pods-can-prevent-ca-from-removing-a-node
Furthermore, when using the GKE autoscaler, there are some constraints to take into account:

*

*When scaling down, cluster autoscaler honors a graceful termination
  period of 10 minutes for rescheduling the node's Pods onto a different
  node before forcibly terminating the node.

*Occasionally, cluster autoscaler cannot scale down completely and an extra node exists after scaling down. This can occur when required system Pods are scheduled
  onto different nodes, because there is no trigger for any of those
  Pods to be moved to a different node. See I have a couple of nodes
  with low utilization, but they are not scaled down. Why?. To work
  around this limitation, you can configure a Pod disruption budget.

Disclaimer: Comments and opinions are my own and not the views of my employer.


text:
Q: How to get last modified time of file while using infile statement? I am going to analyze a batch of SAS program file and I am stucked in getting the last modified time of program files. I have thought about X command but it was too inefficient.
I just find when I use infile statement:
data test;
  infile 'D:\test.txt' truncover;
  input ;
run;

Log shows the last modified time:
NOTE: The infile 'D:\test.txt' is:
      Filename=D:\test.txt,
      RECFM=V,LRECL=32767,File Size (bytes)=7,
      Last Modified=2021/1/26 15:25:48,
      Create Time=2021/1/26 15:25:42

As you can see, log window shows the infomation of file as a NOTE. However, my wish output is a variable filled with Last Modified Time.
Is there some option to get it while using infile statement?
Surely, Other efficient ways are welcomed, too.

A: Use functions FOPEN and FINFO
Example:
Show all available information items and their value for a sample data file.
filename datafile 'c:\temp\datafile.txt';

data _null_;
  file datafile;
  put 'Me data';
run;

data _null_;
  fid = fopen('datafile');

  if fid then do;
    do index = 1 to foptnum(fid);
      info_name = foptname(fid,index);
      info_value = finfo(fid, info_name);

      put index= info_name= @40 info_value=;
    end;

    rc = fclose(fid);
  end;
run;

Will log information such as
index=1 info_name=Filename             info_value=c:\temp\datafile.txt
index=2 info_name=RECFM                info_value=V
index=3 info_name=LRECL                info_value=32767
index=4 info_name=File Size (bytes)    info_value=9
index=5 info_name=Last Modified        info_value=26Jan2021:06:29:47
index=6 info_name=Create Time          info_value=26Jan2021:06:28:23

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you do conditional order_by/regroup in Django? I have a model "status" with fields project_id and timestamp. project_id is sometimes null, if the status isn't associated with a project (more specifically, if the status happens before we know what project caused it).
I want to order an output table as follows:

*

*group statuses with the same project_id together

*don't group null project_ids together

*order these groups and singletons by the latest timestamp of each group/singleton

Can this be done? I can almost achieve it just by sorting by timestamp, then using regroup. That's "almost" right because one group of identical project_ids can be split up by intervening nulls.
I'm pretty sure it can be done in SQL (GROUP BY isnull(experiment_id, -id)), but does Django allow it?

A: for aggregation in django, you are better off doing raw sql as it is way faster than the generated orm sql. Raw sql Django docs


text:
Q: Can you help me convert this route to rails 3? I read a few websites and questions but all were far beyond my level except one site:
http://markconnell.co.uk/posts/2010/02/rails-3-routing-examples
I'm trying to follow Head First Rails which was made for Rails 2 and so far it's been going well enough. I've been able to find the conversions so far, this is really the first place since installation to stump me.
It says in the config/routes.rb file that it should read:
ActionController::Routing::Routes.draw do |map|
  map.connect '/ads/:id', :controller=>'ads', :action=>'show'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

First off my routes.rb file defaults that first line to be
Mebay::Application.routes.draw do

So my first attempt read:
Mebay::Application.routes.draw do
  map.connect '/ads/:id', :controller=>'ads', :action=>'show'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

When that failed I tried this:
Mebay::Application.routes.draw do'
map '/ads/:id' => 'ads#index'
end

Then I tried the same thing but adding |map| to the first line.
And finally, I tried changing it all to this:
ActionController::Routing::Routes.draw do |map|
map '/ads/:id' => 'ads#index'
end

None of these have worked though. Could someone please help me out here, I'm not sure what I'm doing wrong. I have another book, Ruby On Rails 3 by Hartl but in the Index it doesn't even show anything on Routes so don't even know where to look in there.
Thanks for any help you can offer me!
// EDIT - I also tried with it reading '/ads/':id thinking perhaps that is a mistake since it doesn't make sense to me why :id would be inside quotes.
// EDIT 2 - This is what Rake Routes returns:
WARNING: 'require 'rake/rdoctask'' is deprecated.  Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead.
at /Users/Dennis/.rvm/gems/ruby-1.9.2-p318@rails3tutorial/gems/rake-0.9.2.2/lib/rake/rdoctask.rb
WARNING: Global access to Rake DSL methods is deprecated.  Please include
...  Rake::DSL into classes and modules which use the Rake DSL methods
WARNING: DSL method Mebay::Application#task called at /Users/Dennis/.rvm/gems/ruby-1.9.2-p318@rails3tutorial/gems/railties-3.0.1/lib/rails/application.rb:214:in `initialize_tasks'
/ads/:id(.:format)                 {:controller=>"ads", :action=>"show"}
/:controller/:action/:id(.:format)
/:controller/:action/:id.:format

Error Message:

Routing Error
No route matches "/ads/3"

//EDIT 3 - This is what my 2 controller files look like:
ads_controller:
class AdsController < ApplicationController
end

application_controller:
class ApplicationController < ActionController::Base
protect_from_forgery
end

//EDIT 4 -
Tried in the ads_controller.rb file:
    class AdsController < ApplicationController
      def show;
      end
    end
Also tried in the same file:
class AdsController < ApplicationController
end
def show;
end

And each way I tried going to

*

*localhost:3000/mebay/ads/3

*localhost:3000/ads/3

*localhost:3000/show/ads/3

*localhost:3000/mebay/show/ads/3

Same error still "Routing Error. No Route Matches..."

A: ActionController::Routing::Routes.draw do
  match '/ads/:id' => 'ads#show'
  match ':controller/:action/:id'
  match ':controller/:action/:id.:format'
end

I thoroughly recommend reading the docs: http://apidock.com/rails/ActionDispatch/Routing

A: I also am using that book and going through for a difference between rails 2 and rails 3.
I got this to work. In routes.rb file all you need to do is add this between the do and the end:
resources :ads

The key is that your routes.rb file is only sending that resource to the right spot. The next place to look is the ads_controller.rb file where you will want to add this:
 #Get /ads/1
 #Get /ads/1.json

  def show
    @ad = Ad.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @ad }
    end
  end

The next part is adding the index which is a bit later in that chapter. You'll want to add this above that:
# GET /ads
# GET /ads.json
 def index
  @ads = Ad.all

        respond_to do |format|
          format.html # index.html.erb
          format.json { render json: @ad }
        end
      end

Basically if you look at the chapter 1 routes.rb and controller files you'll see that scaffold configures a rails 3 app like that. One more thing that confused me was I was only able to get the javascript to work by putting it in /app/assets/stylesheets and editing application.html.erb and setting the stylesheet link to look like this:
<%= stylesheet_link_tag    "application", :media => "default.css" %>

Enjoy

A: If you are using Rails 3 you don't want to do a Rails 2 tutorial. There are plenty of good rails 3 tutorials out there. For your question about routes, see the blog post below which might help you figure it out.
http://gregmoreno.wordpress.com/2010/08/12/rails-3-upgrade-part-2-routes/

A: Try making this your Routes file. I had the same problem while doing it from Chapter 2 of Head First Rails. But this resolved it for me
    Mebay::Application.routes.draw do

       controller 'ads' do
               match 'ads/:id' => :show
       end

    end


text:
Q: Improve Code Reuse (Python-style decorator for c#?) I'm moving from python to c#, and one of the things I miss is python-style decorators. If I had repeated code at the top of a load of functions (validation checking etc), I could create a decorator to do it.
I've seen that there are c# decorators of a sort, but they look like they work more on the class level. Although I am a bit confused by them.
Regardless - how would you go about improving code re-use/DRY in this function? All the stuff in the function is common, except the two places marked. Its callback driven Tcp requests to a server, with a block to stop multiple concurrent requests (check for Idle state).
    public void MyFunction(string apples, Action<TcpRequest> onSuccess=null, Action<TcpRequest> onError=null)
    {
        // Throw exception if already busy with an operation
        if (!state.Has(State.Idle)) { throw new OperationInProgress(); }

        // Define callback action
        Action<TcpRequest> callback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(State.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                /**
                 * Unique code here
                 */
            }
            // Request failed. Call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Remove idle state
        state.Remove(State.Idle);

        /**
         * Unique code here, that will later trigger the callback
         */
    }

EDIT: I wasn't really thinking of this as a code review task, but now I can see it is. Here is the whole class, showing how the states/vars interact. The Server class handles interactions between us (the client) and a webserver to handle game login, and create/join match.
I'm not fixed on any particular structure, but at some point I want to connect UI buttons to simple functions like Server.Login() and Server.JoinMatch(), without needing to spawn messy classes.
public class Server
{
    #region Fields
    public string playerName { get; private set; }
    public string playerID { get; private set; }
    public string playerToken { get; private set; }
    public string currentMatchID { get; private set; }
    private Patterns.State<ServerState> state = new Patterns.State<ServerState>();
    #endregion

    public Server()
    {
        state.Add(ServerState.Idle);
    }

    public void Login(string playerName, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
    {
        // Throw exception already busy with an operation
        if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }

        // Define login callback action
        Action<TcpRequest> loginCallback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(ServerState.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                // Store player data in class
                playerName = (string)request.requestJson["player_name"];
                playerID = (string)request.responseJson["player_id"];
                playerToken = (string)request.responseJson["player_token"];

                // Add the logged in state
                state.Add(ServerState.LoggedIn);

                // Call the onSuccess callback if provided
                onSuccess?.Invoke(request);
            }
            // Login failed, call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Remove idle state
        state.Remove(ServerState.Idle);

        // Perform request
        Request("login", callback: loginCallback, requestJson: new Dictionary<string, object> { { "player_name", playerName }, { "client_version", "test1" } });
    }

    public void CreateMatch(string matchName, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
    {
        // Throw exception already busy with an operation
        if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }

        // Define callback action
        Action<TcpRequest> callback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(ServerState.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                // Add the inLobby state
                state.Add(ServerState.InLobby);

                // Call the onSuccess callback if provided
                onSuccess?.Invoke(request);
            }
            // Request failed. Call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Remove idle state
        state.Remove(ServerState.Idle);

        // Perform request
        AuthenticatedRequest("match/create", callback: callback, requestJson: new Dictionary<string, object> { { "match_name", matchName } });
    }

    public void JoinMatch(string matchID, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
    {
        // Throw exception already busy with an operation
        if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }

        // Define callback action
        Action<TcpRequest> callback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(ServerState.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                // Add the inLobby state
                state.Add(ServerState.InLobby);

                // Set currentMatchID in class
                currentMatchID = (string)request.responseJson["match_id"];

                // Call the onSuccess callback if provided
                onSuccess?.Invoke(request);
            }
            // Request failed. Call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Perform request
        AuthenticatedRequest("match/join", callback: callback, requestJson: new Dictionary<string, object> { { "match_id", matchID } });
    }

    private void Request(string resource, Action<TcpRequest> callback = null, Dictionary<string, object> requestJson = null)
    {
        // Start async request, invoke callback when done
    }

    private void AuthenticatedRequest(string resource, Action<TcpRequest> callback = null, Dictionary<string, object> requestJson = null)
    {
        // Add login auth data into the requestJson dict or throw exception if we aren't logged in
        // Call Request()
    }
}

A: Depending wether the two unique code must always be used by pair or not I would choose a different approach.
If you want to enforce "pair usage", you can use an abstract class:
public abstract class MyClass
{
    public void MyFunction(string apples, Action<TcpRequest> onSuccess=null, Action<TcpRequest> onError=null)
    {
        // Throw exception if already busy with an operation
        if (!state.Has(State.Idle)) { throw new OperationInProgress(); }

        // Define callback action
        Action<TcpRequest> callback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(State.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                SomethingUnique1();
            }
            // Request failed. Call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Remove idle state
        state.Remove(State.Idle);

        SomethingUnique2(callback);
    }
    protected abstract void SomethingUnique1();
    protected abstract void SomethingUnique2(Action<TcpRequest> callback);
}

And then implement as many subclasses as needed:
public sealed class MyClassVariant1 : MyClass
{
    protected override SomethingUnique1() { /*...*/ }
    protected override SomethingUnique2(Action<TcpRequest> callback) { /*...*/ }
}

public sealed class MyClassVariant2 : MyClass
{
    protected override SomethingUnique1() { /*...*/ }
    protected override SomethingUnique2(Action<TcpRequest> callback) { /*...*/ }
}

If you can't enforce pair usage because one "something unique 1" may be used in pair with many "something unique 2" I would foster a decorative approach:
public sealed class MyClass
{
    private readonly Action somethingUnique1;
    private readonly Action<TcpRequest> somethingUnique2;
    public MyClass(Action somethingUnique1, Action<TcpRequest> somethingUnique2)
    {
        this.somethingUnique1 = somethinUnique1;
        this.somethinUnique2 = somethingUnique2;
    }
    public void MyFunction(string apples, Action<TcpRequest> onSuccess=null, Action<TcpRequest> onError=null)
    {
        // Throw exception if already busy with an operation
        if (!state.Has(State.Idle)) { throw new OperationInProgress(); }

        // Define callback action
        Action<TcpRequest> callback = delegate (TcpRequest request)
        {
            // Add idle state back in
            state.Add(State.Idle);

            // Check if the request succeeded
            if (request.OK)
            {
                somethingUnique1();
            }
            // Request failed. Call the onError callback if provided
            else { onError?.Invoke(request); }
        };

        // Remove idle state
        state.Remove(State.Idle);

        somethingUnique2(callback);
    }
}

And then
var variant1 = new MyClass(() => { /* ... */ }, (TcpRequest r) => { /* ... */ });
var variant2 = new MyClass(() => { /* ... */ }, (TcpRequest r) => { /* ... */ });

Here the approach is more composable and thus, less restrictive.


text:
Q: How can I compare the quality of different voice products? I want to know how I can compare the quality of different voice products, in order that it  gives the best audio quality rating for calls through the internet in average network conditions.
How exactly can I benchmark this? Are there benchmarks available on the internet?

A: The quality of each program will depend on the connection of each person involved in the conversation, as well as the available hardware - not limited to, but including:

*

*Microphone (a poor quality microphone will sound even worse after being compressed and decompressed)

*Poor speakers

*Lower end sound cards / chips can reduce audio quality.

If these factors are not a consideration (IE, each person involved has good quality hardware, stable connection, etc) then your best bet would be Skype.

A: Skype requires a lot of ports open to work.  Protocols are all closed.  It violates my mostly closed firewall setup severely.
GTalk uses very few ports, and uses open protocols.  It works well with my mostly closed firewall setup.  It will interwork with your own servers, so you can setup your own border server if needed.
I haven't used Live Messager as I mostly use Linux.
I would expect no significant call quality differences between any of the three services.  My choice would be based more on security considerations such as firewall requirements.
I tested GTalk to my wife when she was on a train using wireless.  Quality was fine for both voice and video.

A: This is a fairly subjective question - I can only provide subjective responses :-) but I've used all three (Skype, GTalk, WLM) a fair amount.
Skype's SILK codec is vastly improved over previous iterations but for me - even with over 2 Mbps of upstream bandwidth - it still takes a while to scale up to use all the available bandwidth, then it seems to want to lower in quality at the drop of a hat (or lost packet).
GTalk's quality could in theory be excellent; their plugin supports:

*

*PCMA

*PCMU

*G.722

*GSM

*iLBC

*Speex

but in real life I've only ever experienced the pleasure of a 16 Kbps Speex call. :-( Windows Live Messenger is pretty much the same quality wise - Skype edges it. However, Google Plus' Hangout (which uses the latest Vidyo codecs) is (at the moment at least) really good quality and pretty much on a par with Skype for pure audio quality. Looking forward to testing more as times goes on.
Skype is also quite tolerant (so it seems, from  a weekend of testing in a hotel with overpriced wifi) of 3G connections, at least with a VPN, HSDPA and an acceptable level of contention on the cell tower. to get a call for more than 3 seconds without almost 100% dropped packets I had to VPN through the connection (as expected, as I'm on the middle tier for my mobile broadband package it deprioritises Skype traffic). I had very acceptable latency of about 200-250ms; much better than I thought. Throughput was fairly steady too.
So at the moment, Skype pips it for call quality - but I very much expect Google/Vidyo to surpass that quality, particularly given the SQ and PQ of calls I've seen over standard broadband using the standard Vidyo-branded service.

A: The article Best Free Video Conference Software Review grades video and voice conferencing software for audio and video. It gives the following grades for audio :

Skype : 7 (The audio is very loud. The audio quality is also very good
  with very little to no feedback.)
GoogleTalk : 8 (The audio is very
  good with little feedback)
Live Messenger  : 4 (The audio stutters
  sometimes and has clipped speech. It also echos at times. )

A: This would be difficult to benchmark without sophisticated audio equipment. Most consumer level equipment, from the speakers to the headphones to the microphones, are very low quality, providing only enough data to basically transmit recognizable human speach.
You would need an accurate sound sample conveying a wide range of possible sounds in different frequencies and with different types of stops (consonant sounds), and you'd need a system that has a very good sound card electronically isolated from the rest of the system to prevent sample contamination. You would need very high quality, reference tuned inputs and outputs (microphones and speakers) and then a recording device that can compare the resulting sound output to the reference input and highlight any differences.
This becomes very expensive a long time before it becomes practical.
The cheap way to do this is to use the same computer and the same people to rehearse a set selection of dialog and rate it subjectively on clarity and comprehension.
Or, you can just go online and read what others who have more money and more time have done.

A: I think the best strategy to do this would be able using the same technique used to test telephony links. Here you have both conversation sides, called A (the caller) and B (the called one). The technique consists on inject on A side a wide and linear range of acceptable frequencies (for example from 3k to 15kHz) and analyze how this range of frequencies are heard on B side (on telephony and data links this are made by network analyzers). The best link would give exactly the same wide and linear levels of transmitted signal on B side (this is theorical, on phisical links you will never get this enviroment).
I dont know if there is already a software solution to test it, but it wolud be great to have some solution. This solution would be a software that generates a specific (and fixed) bandwidth signals, with all components on the same level on the transmiter side; and a frequency component reader on the reception side. The aplication compares the diferences between transmited and received signals and give you a "benchmark note" to the link (and consequently to the voip solution software used). My recomendation is (if you dont find any specific software that does that) is use Matlab to generate a linear audio source, transmit it over the voip link channel, receive and analyze it on the frequency domain. This would be a start to a benchmark software.


text:
Q: Issues with Laravel and Vue I am using Vue and Laravel together as a SPA. I am having an issue where the first time I click a link on the app I see a flash, and after that the page transitions are smooth.
I included a 15-second video demonstrating the issue here: https://drive.google.com/file/d/0BxrP6oa1_a_EcndHWWxBTHgzeEU/view?usp=sharing
The only plugins I am using is vue-router and vuetify.
Here is my entry file app.js
import Vue from 'vue';
import Vuetify from 'vuetify';
import VueRouter from 'vue-router';

import App from './views/app.vue';

Vue.use(Vuetify);
Vue.use(VueRouter);

window.Vue = Vue;

const Foo = { template: '
foo
' };
const Bar = { template: '
bar
' };
const Bit = { template: '
bit
' };
const Bat = { template: '
bat
' };

const routes = [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar },
    { path: '/bit', component: Bit },
    { path: '/bat', component: Bat }
];

const router = new VueRouter({
    routes // short for `routes: routes`
});

const app = new Vue({
    el: '#app',
    render: h => h(App),
    router
});

Here is my main template file app.vue
<template>
    <v-app id="example-2" standalone>
        <v-navigation-drawer persistent dark :mini-variant.sync="mini" v-model="drawer" overflow>
            <v-toolbar flat class="transparent">
                <v-list class="pa-0">
                    <v-list-tile avatar tag="div">
                        <v-list-tile-avatar>

                        </v-list-tile-avatar>
                        <v-list-tile-content>
                            <v-list-tile-title>John Leider</v-list-tile-title>
                        </v-list-tile-content>
                        <v-list-tile-action>
                            <v-btn icon @click.native.stop="mini = !mini">
                                <v-icon>chevron_left</v-icon>
                            </v-btn>
                        </v-list-tile-action>
                    </v-list-tile>
                </v-list>
            </v-toolbar>
            <v-list class="pt-0" dense>
                <v-divider></v-divider>
                <v-list-tile v-for="item in items" :key="item.title" route :to="item.path">
                    <v-list-tile-action>
                        <v-icon>{{ item.icon }}</v-icon>
                    </v-list-tile-action>
                    <v-list-tile-content>
                        <v-list-tile-title>{{ item.title }}</v-list-tile-title>
                    </v-list-tile-content>
                </v-list-tile>
            </v-list>
        </v-navigation-drawer>
        <v-toolbar fixed class="indigo darken-4" dark>
            <v-toolbar-side-icon @click.native.stop="drawer = !drawer"></v-toolbar-side-icon>
            <v-toolbar-title>Toolbar</v-toolbar-title>
        </v-toolbar>

            <v-container fluid>
                <router-view></router-view>
            </v-container>

    </v-app>
</template>

I also shared the full code here: https://github.com/andrewex/laravel-vue-test


text:
Q: Batch Maven Builds with 2 Separate versions I'm trying to build a whole bunch of maven projects in a batch script. There are 2 sets that use (require) different versions of maven. Meaning: half of the projects use Maven 3.1.1 and the other uses 2.2.1, but some of those projects that use maven 2 require some of the maven 3 projects.
I'm trying to do this all in one script as such:
 setx M2 %APACHE%\apache-maven-3.1.1\bin\
 rebuildCore
 setx M2 %APACHE%\apache-maven-2.2.1\bin\
 rebuildApp
 7z x "%workspace%\win32-app\target\win32-product-0.0-SNAPSHOT.zip" -o%Desktop% *.* -r -y > nul

The %APACHE% variable points to where the two maven installations are, %Desktop% points to my desktop, and %workspace% is my eclipse workspace.
rebuildCore and rebuildApp are 2 other batch scripts that build my projects, and those work fine.
The problem I am facing is that maven won't change what it points to at runtime after the command prompt has been started, and all windows have to be closed for it to refresh.
Is there any way to completely close all command prompt or powershell windows and run this without starting a new script? I know this seems unlikely, which is why I'm having problems with it.

A: This works if you use a symlink in your path (e.g. environment variable M2 points to C:\maven\bin; and C:\maven is a symlink pointing to C:\Program Files\Apache\apache-maven-x.x.x), such that you can delete the symlink or NTFS junction in the middle of the script, and recreate it to another version of Maven. Example of how I changed this:
cd C:\
rmdir maven
mklink /j maven "%APACHE%\apache-maven-3.2.1"
start /wait cmd /q /c rebuildCore.bat
cd C:\
rmdir maven
mklink /j maven "%APACHE%\apache-maven-2.2.1"
start /wait cmd /q /c rebuildApp
:: THIS LAST LINE EXTRACTS MY RCP APP FROM THE BUILT ZIP FILE TO A FOLDER ON MY DESKTOP
7z x "C:\Users\USER\workspace\app-win32-std-product\target\app-win32-std-product-2.4-SNAPSHOT.zip" -oC:\Users\USER\Desktop\ *.* -r -y


text:
Q: Display list/or table with Ruby on Rails from search result New to Ruby on Rails. I want to update the new.html.erb view to display search_result from album_controller.rb, after the search parameter is submitted. Can I create a hidden element and later display it through from the controller? search_results is an array of string arrays.
My goal to display a list of possible albums to choose from (obtained from the http get request), and then let the user choose which search result to carry on with.
new.html.erb

Search for Album

<%= form_with(url: "/albums/search", method: "get") do %>
  <%= label_tag(:q, "Search for: ") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>

album_controller.rb
require 'httparty'
require 'json'

class AlbumsController < ApplicationController

  def new
    puts "the new method was just called"
  end

  def search
    puts "inside search method"
    @search_param = params[:q]
    puts @search_param

    if params[:q] # if not null
      #perform artist and album search
      search_result = http_request(@search_param)
    end
  end

  def http_request(search_input)
    # search for album
    website = "http://ws.audioscrobbler.com/2.0/?"
    search_album = "method=album.search&album=" + search_input + "&"
    api_key = "api_key=&"
    format = "format=json&"
    limit = "limit=15"

    url = website + search_album + api_key + format + limit

    response = HTTParty.get(url)
    pretty_json = JSON.pretty_generate(response.parsed_response)
    obj = JSON.parse(pretty_json)

    returnArray = []
    for result in obj["results"]["albummatches"]["album"]
      tempArray = [result["name"], result["artist"], result["image"][3]["#text"]]
      returnArray.append(tempArray)
    end

    return returnArray
  end
end

routes.rb
Rails.application.routes.draw do
  get 'welcome/index'

  post "albums/new" #to later post to album db

  get "albums/search"  #search route in new.html.erb

  resources :albums

  root 'welcome#index'

end

A: In Rails you want to build skinny controllers that contain the minimum of code and the only public methods should be the actions that correspond to your routes. This is because controllers are notoriously hard to test and bloat becomes a problem real fast.
HTTP calls, batch processing and other such tasks do not belong in your controller. Especially not if they touch the application boundary. Instead you want to create a client object that handles the HTTP call and models that encapsulate the data and normalize it for your application.
So lets start with the HTTP call:
# app/clients/audio_scobbler_client.rb
class AudioScrobblerClient
  include Httparty
  format :json
  base_uri "http://ws.audioscrobbler.com/2.0/"

  def initialize(api_key:)
    @base_opts = {
      api_key: api_key,
      format: "json" # may be redundant
    }
  end

  def album_search(query, limit: 15)
    self.class.get(
      @base_opts.reverse_merge(
        method: 'album.search',
        limit: limit
      )
    )
  end
end

This gives you an object you can test separately from your controller and removes the mess of constructing query strings with string concatenation (never do this). It returns the JSON from performing the HTTP request and nothing more.
Then create a model that represents the search results in your application. Remember that persistence is not the only role of models in MVC.
# app/models/album.rb
class Album
  include ActiveModel::Model
  include ActiveModel::Attributes
  attr :artist, String
  attr :name, String
  attr :image, String
end

Now lets throw one more object into the the mix - a service object that does the API call and normalizes the values:
# app/services/audio_scrobbler_search.rb
class AudioScrobblerSearch
  def perform(query, **options)
    api_key = ENV["AUDIOSCROBBER_API_KEY"] # or use the encrypted secrets.
    json = AudioScrobblerClient.new(api_key: api_key).album_search(query, options)
    json.dig("results", "albummatches", "album").map do |result|
      # I have no idea what api response looks
      # like but I have no doubt that you can figure this part out
      Album.new(
         artist: result["name"],
         name: result["name"],
         image: result["image"]
      )
    end
  end
end

Then lets get rid of all the bloat in the controller:
class AlbumsController < ApplicationController
  # you don't really need the new action at all since a search form can just loop back on itself
  # GET /albums/search?q=believe
  def search
    @search_query = params[:q]
    if @search_query
      @albums = AudioScrobblerSearch.perform(query)
    end
  end
end

And list the albums in the view:

Search for Album

<%= form_with(url: "/albums/search", method: "get") do %>
  <%= f.label(:q, "Search for: ") %>
  <%= f.text_field(:q, value: @search_query) %>
  <%= f.submit("Search") %>
<% end %>

<% if @albums %>

        Image
        Artist
        Name

      <% @albums.each do |album| %>

          <%= tag.img src: album.image, alt: "Cover art for #{album.name}" %>
          <%= album.artist %>
          <%= album.name %>

      <% end %>

<% elsif @search_query.present? %>

No results to display :(

<% end %>


text:
Q: NestJS Mongoose not updating documents When i try to update a document its not working in mongoose. But in mongosh its working.
Can you help me why? Thanks!
Heres my code:
Query:
        this.messagesModel.updateMany(
          {
            _id: new Mongoose.Types.ObjectId(data.msgid),
          },
          {
            $set: {
              message: encryptedMessage,
            },
          }
        ).exec();

Messages schema:
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import mongoose, { Document } from "mongoose";

export type MessagesDocument = Messages & Document;

@Schema()
export class Messages {
  @Prop()
  msg: string;

  @Prop()
  chatid: mongoose.Types.ObjectId;

  @Prop()
  author: mongoose.Types.ObjectId;

  @Prop()
  isEdited: string;

  @Prop()
  sent_at: string;
}

export const MessagesSchema = SchemaFactory.createForClass(Messages);


text:
Q: R package for fixed length vectors I'd like to have fixed length/dimensions vectors/matrices in R. Pseudocode:
foo <- fixed_character(LETTERS, length = 26)
foo <- LETTERS[1:10] # throws an error, wrong length

bar <- fixed_matrix(NA, 6, 2)
bar <- matrix(1:12, 3, 4) # wrong dimensions

This would be useful for catching errors and writing robust code. Are there any packages on CRAN that do this?

A: I recalled that the rtype system allows you to check the dimensions of vectors and data frames on assignment. The vctrs package also seems relevant.


text:
Q: Properties of dry air and gas mixture While studying a heat exchanger, I have encountered a hydrogen rich fluid stream (enters at 90 Celsius and exits at 120 Celsius) which has composition given in the following form:
Air Humidity/Fluid composition: 1% (2.5 bar abs)/Mass fraction of hydrogen=0.02
For the heat exchanger analysis, I need to calculate several properties of this mixture like enthalpy, specific heat.
Property reference softwares like Coolprop and Refprop give data for gas mixtures, but not for air-gas mixtures.
How should I start to calculate the properties of this air-gas mixture?
I guess the humidity can be neglected safely because it is just 1%.


text:
Q: Where does Factory come from? I am trying to add items to splitbuttons and galleries. The issue is with the Factory. In the following OfficeRibbon code file Factory is unknown. It is also unknown in the addin code file.  I am missing a reference somewhere. I have also tried Globals.Factory still unknown.
RibbonButton rc = this.Factory.CreateRibbonButton();

I have the following using statements.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Ribbon;
//using Microsoft.Office.Tools.Excel.Extensions;

This code also fails in the ThisAddin.cs which has been renamed to ReqCommon.cs in my project.
My desired end goal is to dynamically add items to these two controls. Examples i have found here and elsewhere all seem predicated on this elusive Factory.
The project does reference Microsoft.Office.Tools.Common.v9.0.dll

A: If you are using the Ribbon Designer - it will automatically create this Factory for you (Globals.Factory.GetRibbonFactory()) - otherwise you need to create your own Factory by overriding CreateRibbonExtensibilityObject() in ThisAddin.cs (your ReqCommon.cs)
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
    Ribbon1 tempRibbon = new Ribbon1();
    tempRibbon.tab1.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office;
    tempRibbon.tab1.ControlId.OfficeId = "TabHome";
    return Globals.Factory.GetRibbonFactory().CreateRibbonManager(new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { tempRibbon });
}

The Ribbon Designer inherits from Ribbon.RibbonBase which contains the property RibbonBase.Factory which enables this.Factory to be used within it.


text:
Q: Lambda expressions are not supported in -source 6 when i package my code, i get this error Error:(13,48) java: lambda expressions are not supported in -source 6.
I tried installing different JDK, but doesnt change. I tried jdk 11, 1.8, 13.

A: You need to specify in the pom the java version your project uses. Add this section to your pom.xml to specify java 8 for instance
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


text:
Q: Spring.NET WCF AOP Performance Logging I have a MVC App where I inject my WCF service to the Controller using Spring.NET. Following is my configuration
MVC Client Web.Config
<wcf:channelFactory id="LoginService" channelType="App.Interfaces.Services.ILoginService, AppServiceInterfaces" endpointConfigurationName="EndPointLoginService"/>

<endpoint name="EndPointLoginService" address="http://localhost:xxx/LoginService.svc" contract="App.Interfaces.Services.ILoginService" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding1" behaviorConfiguration="ServiceEndpointBehavior" />

WCF Service Web.Config
<object id="LoginService" type= "App.Services.LoginService, AppLoginService" singleton="false">
</object>

<service name="LoginService" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding1" contract="App.Interfaces.Services.ILoginService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>

Login Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="LoginService" Factory="Spring.ServiceModel.Activation.ServiceHostFactory" %>

The above work perfectly fine. Now I wanted to implement Performance Logging for the above
So I added the following in the WCF Service Web.Config
<object id="performanceLoggingAroundAdvice" type="AOP.Advice.PerformanceLoggingAroundAdvice, AOP" singleton="false" scope="request"/>

where I have a project called AOP.
and
<object id="LoginService" type= "App.Services.LoginService, AppLoginService" singleton="false">
<property name="InterceptorNames">
  <list>
    <value>performanceLoggingAroundAdvice</value>
  </list>
</property>

But I get an error..saying Initialization of Login Service failed. Can someone help me with the configuration.

A: Resolved it by adding the following in my Service layer config
<object type="Spring.Aop.Framework.AutoProxy.TypeNameAutoProxyCreator, Spring.Aop">
  <property name="TypeNames">
  <list>
    <value>App.Services.LoginService</value>
  </list>
</property>
<property name="InterceptorNames">
  <list>
    <value>performanceLoggingAroundAdvice</value>
  </list>
 </property>
</object>

and removed the existing propery Interceptornames property config
<property name="InterceptorNames">
  <list>
    <value>performanceLoggingAroundAdvice</value>
  </list>
</property>

From
<object id="LoginService" type= "App.Services.LoginService, AppLoginService"
singleton="false">
<property name="InterceptorNames">
  <list>
    <value>performanceLoggingAroundAdvice</value>
  </list>
</property>
</objects>


text:
Q: Determine if click event source comes from thead I've been at this for awhile now with no luck so I thought I'd throw something up on SO.
I need the function of a click event in and Angular directive to execute only if the source comes from the tbody not the thead. I've tried a number of routes to get this information, but I can't seem to get the syntax right.
Any help/guidance would be greatly appreciated. Here is my latest/best attempt. Will give you and idea what I'm going for:
/* Linker for the directive */
var linker = function (scope, elm, attrs) {
    window.setTimeout(function(){
        elm.find('table tbody tr.uib-weeks td button span.text-info').closest('tr').find('button').addClass('chosenReportWeek');
    }, 1000); // This is a hack until we can find the proper load/render event

    elm.on('click', function(event) {
        if(event.target.parent.indexOf('thead') === -1){
            elm.find('table tbody tr.uib-weeks button.active').closest('tr').find('button').addClass('chosenReportWeek');
        }
    });
};

A: Correct syntax below:
if($(event.target).closest('thead').length === 0)


text:
Q: Using the MSQL XDEVAPI In Node JS, can I chain multiple calls together? Example, I'm trying to check to see if a value exists in a table and then if no duplicates exists write the values in the same table, but its not working. Let me know if chaining the calls is possible if not, would I just pass the variable and then do another call to the DB, also I'm having trouble closing the connection to a single session, any help would be appreciated.
  mysqlx.getSession({
    user: 'robot',
    password: 'password',
    host: 'localhost:8080',
    port: '33060'
})

    .then (function(session){
var v_table = session.getSchema('nms2019local').getTable('v_table')

for (let k=0; k<s_key.length; k++){
 v_table
.select(['s_key', 'accounts'])
.where('s_key like :accounts')
.bind('s_key',s_key[k])
.execute()
.then(function(s_keyDuplicates, session){

    let s_keyDuplicatesCheck = s_keyDuplicates.fetchOne()
    console.log(s_keyDuplicatesCheck)
    if (s_keyDuplicatesCheck === undefined){

        for (let n = 0; n<s_key.length; n++){
            return v_table
            .insert(['s_key'])
            .values([s_key[n]])

        }
    }
//     else{

//     let s_key_final = [];
//     s_keyDuplicatesArray = s_keyDuplicates.toArray()
//    for (var m in s_key){
//        if(!s_keyDuplicatesArray.includes(s_key[m])) s_key_final.push(s_key[m])
//    } console.log(s_key_final)
//    for (let l = 0; l<s_key_final.length; l++){
//              return v_table
//              .insert(['s_key'])
//              .values([s_key_final[l]])
//    }

// }
})

}

})

.catch(function(err){
console.log('the following error occured: ' + err.message)

})

A: What exactly do you mean by chaining? From a quick look, I would say the only problem is that you are not calling execute() with insert(), and thus, the values are never sent to the server. I'm not sure about the async flow though. Would have to check.
Also, I'm not sure if the s_key column is supposed to contain unique values, but if that is the case you are probably better off creating a unique key constraint and using an SQL "upsert" strategy like ON DUPLICATE KEY UPDATE.
Disclaimer: I'm the lead developer of the MySQL X DevAPI Connector for Node.js


text:
Q: DataFrame append() method does not append data I created a method that suppose to append many dataframes (df) into one(base_df) in a for loop. It doesn't bring any errors,just base_df stays empty. df dataframe has data. Please help. Thank you.
#concatenate all files into one dataframe.
def concatenate_all_in_one( bucket, prefix):

    response = s3_client.list_objects(Bucket=bucket, Prefix=prefix)
    content_list = response['Contents']
    base_df = pd.DataFrame()
    for item in content_list:
        try:
            df = get_df_by_bucket_and_key(bucket, item['Key']) #this works fine
            print("this is df name of the file", item['Key'] )
            print("this is df info", df.head())
            base_df = base_df.append(df,ignore_index = True )
        except Exception as e :
            print(e)
            print("Did not append", item['Key'])

    print("This is base_df info", base_df.info())
    return base_df ```


text:
Q: Add/remove class while traversing through list-items I don't quite understand why this isn't working.  I'm trying to make it so .on() click will removeClass() .active-title from a list-item; Then addClass() .active-title to the next() list-item.
$(".next").on({
    click: function(){
        $('.active-title').removeClass(function(){
          $(this).next().addClass('active-title');
    }
  });
});

Demo:
Link to JSFiddles Demo

Final Solution Demo in JSFIDDLES

A: You have some errors in your code
      }
   });
});

supposed to be
      }); <--- closing of removeClass
   } <-- closing for click function
});

Try this
$(".next").on({
    click: function () {
       // Find the actuve element
        var $active = $('.active-title', 'ul');
       // If the next element exists the get the element
       // otherwise get the first li from the ul
        var $nextElem = $active.next('li').length ? $active.next('li')
                                                  : $('ul').find('li:first');
        // Add and remove class
        $active.removeClass('active-title');
        $nextElem.addClass('active-title');

    }
});

Check Fiddle


text:
Q: Error refreshing state: state snapshot was created by Terraform v0.15.0, which is newer than current v0.12.18 Issue happens when trying run terraform plan command.
Error refreshing state: state snapshot was created by Terraform v0.15.0,
which is newer than current v0.12.18; upgrade to Terraform v0.15.0
or greater to work with this state

A: The same reply to this ticket https://stackoverflow.com/posts/69575643/ Which I expect to be related.
Happened to me, my deployment (CICD) failed and left a lock in the TF state.
So I just went and manually removed the lock from my local
terraform init -backend-config="key=prod/app1.tfstate"
terraform force-unlock -force xxxxx-8df6-a7e8-46a8-xxxxxxxxxxxx
Then I try to redeploy from CI/CD and get that error, because my local was higher version than terraform running in the CI/CD.
In the end, I did this to restore to the previous state:

*

*S3: find the state file, restore the old version (versioning enabled in this bucket)

*Run this again: terraform init -backend-config="key=prod/app1.tfstate" -reconfigure
To get the response below with the previous digest value:

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Error refreshing state: state data in S3 does not have the expected content.

This may be caused by unusually long delays in S3 processing a previous state
update.  Please wait for a minute or two and try again. If this problem
persists, and neither S3 nor DynamoDB are experiencing an outage, you may need
to manually verify the remote state and update the Digest value stored in the
DynamoDB table to the following value: ebf597a8a25619b959baaa34a7b9d905

*Update the dynamo item with the digest above

*Run deployment again

A: Actually this happens, when there is a difference in terraform version. Consider below example
Initial state snapshot is created for terraform version "v0.15.0" and current terraform state update is done with version "v0.12.18"(which is older than the state snapshot)
In order to make it work we need allow terraform state to work with specific list of terraform version.

terraform {   required_version >= "=0.12.18" }

This will make terraform state files to work with versions above than "0.12.18"


text:
Q: Remap the middle click action of Logitech T400 wireless mouse I want to remap the functionality of the front part of middle click and back part of middle click on the Logitech Zone Touch Mouse T400 model.
According to the answer in this question, I tried the commands but I don't understand what to exactly swap.
Here is the output for the command xinput list-props id# (10 being the device id)
 nirmik@nirmik:~$ xinput list-props 10
Device 'Logitech Unifying Device. Wireless PID:4026':
    Device Enabled (134):   1
    Coordinate Transformation Matrix (136): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    Device Accel Profile (256): 0
    Device Accel Constant Deceleration (257):   1.000000
    Device Accel Adaptive Deceleration (258):   1.000000
    Device Accel Velocity Scaling (259):    10.000000
    Device Product ID (251):    1133, 50475
    Device Node (252):  "/dev/input/event6"
    Evdev Axis Inversion (653): 0, 0
    Evdev Axes Swap (655):  0
    Axis Labels (656):  "Rel X" (144), "Rel Y" (145), "Rel Horiz Wheel" (650), "Rel Dial" (651), "Rel Vert Wheel" (652)
    Button Labels (657):    "Button Left" (137), "Button Middle" (138), "Button Right" (139), "Button Wheel Up" (140), "Button Wheel Down" (141), "Button Horiz Wheel Left" (142), "Button Horiz Wheel Right" (143), "Button Side" (645), "Button Extra" (646), "Button Forward" (647), "Button Back" (648), "Button Task" (649), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643), "Button Unknown" (643)
    Evdev Middle Button Emulation (658):    0
    Evdev Middle Button Timeout (659):  50
    Evdev Third Button Emulation (660): 0
    Evdev Third Button Emulation Timeout (661): 1000
    Evdev Third Button Emulation Button (662):  3
    Evdev Third Button Emulation Threshold (663):   20
    Evdev Wheel Emulation (664):    0
    Evdev Wheel Emulation Axes (665):   0, 0, 4, 5
    Evdev Wheel Emulation Inertia (666):    10
    Evdev Wheel Emulation Timeout (667):    200
    Evdev Wheel Emulation Button (668): 4
    Evdev Drag Lock Buttons (669):  0

And the output of the next command xinput get-button-map 10 is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Now what do I exactly swap to change the middle click to front part of middle click = middle click action. From/instead of front part of middle click = super button

A: Try imwheel.
sudo apt-get install imwheel

You can configure your buttons using imwheel and it's recommended by the Ubuntu wiki.

A: I used this way:

*

*Install xbindkeys and xdotool
sudo apt-get install xbindkeys xdotool

*Rebind the Super key to middle mouse button by xbindkeys config
$ cat ~/.xbindkeysrc
"xdotool click 2"
  c:133

*Add xbindkeys to start with X
$ echo xbindkeys > ~/.xinitrc

*Disable opening Dash on Super key
$ sudo apt-get install compizconfig-settings-manager

Then press Alt + F2 and type about:config
On tab "Launcher" you can disable or change "Key to show the Dash..."

*Start xbindkeys for this session or reboot.

A: I don't know if this will really help, since I can't try it.  If it works, let me know.
If you're running 12.04, you can use btnx.  It will ask for the btnx-config, which you can get here
You can also change the button mapping with xmodmap. For instance, to swap the left with the right mouse button:
xmodmap -e 'pointer = 3 2 1'

To revert it, simply set 1 2 3 or use 'default' according to the manpage.
You may also take a look at How to configure extra mouse buttons in Ubuntu 13.10 for more info.


text:
Q: Connect Django Amazon Lightsail Mysql Explanation: I have 2 instances of Amazon Lightsail. One has MYSQL and the other has CentOs.  I have my app Django with apache mod_wsgi, for connecting Django(instance 1) to Mysql(instance 2) using the endpoint from  Amazon:
ls-846d543ff0bab456d8a9309bd9585f11072f.cqaexlou8v8h.us-east-1.rds.amazonaws.com

and I get this error:
(1045, u"Access denied for user 'toor'@'localhost' (using password: YES)")

my settings:
DATABASES = {
    'default':{
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'my_db',
        'SERVER':'ls-846d543ff0bab456d8a9309bd9585f11072f.cqaexlou8v8h.us-east-1.rds.amazonaws.com',
        'PORT': '3306',
        'USER': 'toor',
        'PASSWORD': 'q1w2e3r4t5' ,
    }
}

I created a user using mySQL Workbench like this:
create user toor identified by 'q1w2e3r4t5';
grant all on my_db.* to 'toor'@'%';
flush privileges;

and try this code:
grant all on my_db.* to toor@localhost identified by 'q1w2e3r4t5' with grant option;

I create this user by Mysql Workbench with instance2(mysql amazon Lightsail)
please some one suggest..!!

A: The solution was :
change SERVER by HOST:
on the setup Django only change this:
'SERVER':'my_server'

by:
'HOST':'my_server'

is very strange but with this change i can connect to my server mysql amazon.

A: Where is MySQL running:
Localhost alongside Django?
An instance you hand built and installed MySQL on?
A Lightsail database instance?
My suspicion is that your 'SERVER':'host_amazon' parameter is incorrect. As I'd expect it to either be localhost, the internal IP of your custom built instance, or the endpoint of your Lightsail database (something like: ls-7d2174226335104ebdb71cfebe89d1c8f060c799.cdekwlh0imih.us-west-2.rds.amazonaws.com)
How did you create the user? What server did you connect to?


text:
Q: 'Access Denied' when attempting DirSync with S.DS I am trying to set up a DirSync control. Previously I have [successfully] used the methods found in the System.DirectoryServices.Protocols, but I found that the results it returned were only partial objects - I wasn't able to have it return the homeDrive attribute from a user even if I defined it in the SearchRequest's Attributes property.
Thus, I'm attempting to set up DirSync following some of the documentation and examples using System.DirectoryServices instead. I was successful in connecting to my test server (only accessible by IP), and I was successful in targeting just one OU and searching for a user, as such:
byte[] cookie = null;
root = new DirectoryEntry(
  "LDAP://[MyIPHere]/OU=test ou,DC=company,DC=com", "username", "password");

//Section A - Use this section for a regular search
DirectorySearcher src = new DirectorySearcher(root);
src.SearchScope = SearchScope.Subtree;
src.Filter = "(&(objectClass=user)(sAMAccountName=myuserhere)";

//Section B - Use this section for a DirSync
//src.DirectorySynchronization = new DirectorySynchronization(
    DirectorySynchronizationOptions.IncrementalValues, cookie);
//src.Filter = "(&(objectCategory=person)(objectClass=user))";

//Execute the code whichever section is used
SearchResultCollection result = src.FindAll();

int count = result.Count;
Console.WriteLine(count.ToString());

foreach (SearchResult res in result)
{
    //do things
}

However, when I try to use section B instead of section A, I get an error on the line where I'm setting the int count. (I have tried passing no parameters to the constructor of src.DirectorySynchronization as in the example, same result):

COMException was unhandled
Access is denied.

I only get the error when I try to access the properties of the result object, or try to iterate. If I set a breakpoint on the int count line and look at the result object, I see the following in the value column of the result's Count:

'result.Count' threw an exception of type
'System.Runtime.InteropServices.COMException'

I have ensured that my account has the Replicating Directory Changes security access both for the specified OU and the test domain at large (and all other security access possible). I have also tried using a separate domain admin account.
I have the same issue if I try running this on our production domain, passing no credentials when constructing the DirectoryEntry object.
Considering that I can successfully retrieve other search results, what is it about this DirectorySynchronization that is causing the access issues, and why isn't it happening when I call src.FindAll()?
(I'm open to other options, but I'd like to avoid the USNChanged tracking method for now due to it returning the full objects back, and requiring additional coding on my end.)

A: The base of a DirSync search must be the root of a directory partition, i.e "DC=company,DC=com" in your case.
See http://msdn.microsoft.com/en-us/library/ms677626(v=vs.85).aspx
"Base of the search" in the table.
Some more good C# example for DirSync:
http://msdn.microsoft.com/en-us/magazine/cc188700.aspx#S1
See section "Finding Your Way with DirectorySearcher".
If you want to track changes only on a OU/container, yes, you will have to use USNChange.


text:
Q: Solving a Logistic model equation with harvesting I have the following Logistic model equation (left out the values for the constants for simplicity), which I'm unable to solve for $P(t)$.
$\dfrac {dP} {dt} = kP  \left (1- \dfrac P {P_\infty} \right)-H$
If the harvesting constant, $H$ was not present, then the ODE could be solved by Bernoulli's equation. The problem is that I am not sure how to start solving this specific type of differential equation.
Can someone point me in the right direction?
Thank you for your time!

A: The equation is in separated variables:
$$
\frac{dP}{k\,P  \left (1- \dfrac P {P_\infty} \right)-H}=dt.
$$

A: There are in fact three cases to consider for the logistic model with harvesting.  Multiplying out the expression on the right side of the differential equation produces  $$ \frac{dP}{dt} \ \ = \ \ -\frac{k}{M} \ P^2 \ + \ k P \ - \ H \ \ , $$
where I am replacing $ \ P_{\infty} \ $ with $ \ M \ \ , $ since the former label can be misleading in the harvesting model, as we shall see.  We may solve the quadratic polynomial for its zeroes, which will give us the equilibrium solutions of the differential equation (if they exist).  For $ \ P^2 \ - \ MP \ + \ \frac{HM}{k} \ = \  0 \ \ , $ we obtain
$$ P \ \ = \ \ \frac{M \ \pm \ \sqrt{M^2 \ - \ \frac{4HM}{k}}}{2} \ \ . $$
How we factor the right side of the differential equation then depends upon the "size" of the harvesting term.
$ \mathbf{{M^2 - \frac{4HM}{k}}  \ > \ 0 \ \Rightarrow \ H < \frac{kM}{4} \ \ - \ } $ ("subcritical harvesting"):  we have two equilibrium solutions smaller than $ \ M \ $ , the "carrying capacity" in the standard logistic model, that we could call $ \ M_{+} \ $ and $ \ M_{-} \ $ ; the differential equation becomes $ \frac{dP}{dt} \ \ = \ \ -\frac{k}{M} · (P - M_{+}) · (P - M_{-}) \ \ , $ which is separable and can be solved by using partial-fraction decomposition; we in turn have three cases for the initial condition, $ \ P_0 < M_{-} \ \ , \ \ M_{-} < P_0 < M_{+} \ \ , \  $ and $  \ P_0 > M_{+} \ \ ; $ we find that $ \ M_{+} \ $ is the "attractor" (stable) equilibrium solution and $ \ M_{-} \ $ is the "repeller" (unstable) equilibrium
$ \mathbf{ H > \frac{kM}{4} \ \ - \ } $ ("over-harvesting"):  the polynomial $ \ P^2 \ - \ MP \ + \ \frac{HM}{k} \ $ cannot be factored in real numbers, so there is no   equilibrium solution; the equation is separable, but we must use "completion-of-squares" to write $ \frac{dP}{dt} \ \ = \ \ -\frac{k}{M} · \left(P - \frac{M}{2} \right)^2  \ - \ \left(\frac{4H \ - \ kM}{4} \right) \ \ ; $ we will have an "arctanh-type"  solution, with the population falling to zero ("and beyond") regardless of the initial condition
$ \mathbf{ H = \frac{kM}{4} \ \ - \ } $ ("critical harvesting"):   the differential equation is again separable, and can be written as $ \frac{dP}{dt} \ \ = \ \ -\frac{k}{M} · \left(P - \frac{M}{2} \right)^2   \ \ ; $ there is a single critical solution which is a peculiar equilibrium solution sometimes called "semi-stable": $ \frac{M}{2} \ $ is an attractor for $ \ P_0 > \frac{M}{2} \ $ , but is a repeller for $ \ P_0 < \frac{M}{2} \ \ ; $ this can be thought of as the "merger" of the two equilibria in the subcritical case
Note that in all three of these models, a population at a sufficiently low level (or any over-harvested population) will "crash" to zero, since $ \ \frac{dP}{dt} < 0 \ $ at $ \ P = 0 \ $ ; the population will become abruptly extinct, rather than disappearing gradually.


text:
Q: How can I download my uploaded file on Bonita using a Link I have created my submission form in Bonita and I have added all my variables. Here below is a photo of my submission form

Here is the Validation Form

I want to be able to get the file uploaded on the first form, to the validation form, so I can be able to download it as a link.
But when I tried to reference it, I get an error message when I tried to click on the link

How can I reference the file correctly? Any Ideas?

A: Note: You would need to press the fx button in the URL field and provide the input like '/bonita/portal/' + context.file_ref.url
Also there are couple of cases to check in your question:

*

*If you are saving the input file to a process "Document", then you can fetch as '/bonita/portal/' + context.file_ref.url
where
file is the name of the process document.

*I understand from your first image that you have the file is child inside a complex contract input. But as you cannot save a file inside a business object, you can instead save the document URL in the process and while loading, you can simply use
'/bonita/portal/' + context.submit_ref.File
where submit is the name of the business variable and File is the attribute where you saved the document URL


text:
Q: An exception occurred processing JSP page /index.jsp at line 51 I am writing code for uploading file using struts. below is the error i am facing,
org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 51
48:
49:

50:

51:
52:      Dataset
53:
54:

root cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Exception creating bean of class com.aml.model.DatasetForm: {1}

Tell me the solution for this problem.

A: Finally my program has successfully ran. The only mistake i done in my project is to include the mismatched java runtime environment in my project. I have installed jdk1.7 and i had used the 1.4 complient version of the facet in my eclipse ide. After changing the java compiler path to 1.4 version in my project properties i got my error cleared in my project. Thank you.


text:
Q: Average a subset of a matrix in a loop in matlab I work with an image that I consider as a matrix.
I want to turn a 800 x 800 matrix (A) into a 400 x 400 matrix (B) where the mean of 4 cells of the A matrix = 1 cell of the B matrix (I know this not a right code line) :
B[1,1] =mean2(A[1,1 + 1,2 + 2,1 + 2,2])

and so on for the whole matrix ...
B [1,2]=mean2(A[1,3 + 1,4 + 2,3 + 2,4 ])

I thought to :
1) Reshape the A matrix into a 2 x 320 000 matrix so I get the four cells I need to average next to each other and it is easier to deal with the row number afterwards.
Im4bis=reshape(permute(reshape(Im4,size(Im4,2),2,[]),[2,3,1]),2,[]);

2) Create a cell-array with the 4 cells I need to average (subsetted) and calculate the mean of it. That's where it doesn't work
I{1,160000}=ones,
for k=drange(1:2:319999)
    for n=1:160000
        I{n}=mean2(Im4bis(1:2,k:k+1));
    end
end

I created an empty matrix of 400 x 400 cells (actually a vector of 1 x 160000) and I wanted to fill it with the mean but I get a matrix of 1 x 319 999 cells with one cell out of 2 empty.
Looking for light
My Input Image:

A: Let A denote your matrix and
m = 2; %// block size: rows
n = 2; %// block size: columns

Method 1
Use blockproc:
B = blockproc(A, [m n], @(x) mean(x.data(:)));

Example:
>> A = magic(6)
A =
    35     1     6    26    19    24
     3    32     7    21    23    25
    31     9     2    22    27    20
     8    28    33    17    10    15
    30     5    34    12    14    16
     4    36    29    13    18    11
>> B = blockproc(A, [m n], @(x) mean(x.data(:)))
B =
   17.7500   15.0000   22.7500
   19.0000   18.5000   18.0000
   18.7500   22.0000   14.7500

Method 2
If you prefer the reshaping way (which is probably faster), use this great answer to organize the matrix into 2x2 blocks tiled along the third dimension, average along the first two dimensions, and reshape the result:
T = permute(reshape(permute(reshape(A, size(A, 1), n, []), [2 1 3]), n, m, []), [2 1 3]);
B = reshape(mean(mean(T,1),2), size(A,1)/m, size(A,2)/n);

Method 3
Apply a 2D convolution (conv2) and then downsample. The convolution computes more entries than are really necessary (hence the downsampling), but on the other hand it can be done separably, which helps speed things up:
B = conv2(ones(m,1)/m, ones(1,n)/n ,A,'same');
B = B(m-1:m:end ,n-1:n:end);

A: Method 1
Using mat2cell and cellfun
AC = mat2cell(A, repmat(2,size(A,1)/2,1), repmat(2,size(A,2)/2,1));

out = cellfun(@(x) mean(x(:)), AC);

Method 2
using im2col
out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2);

Method 3
Using simple for loop
out(size(A,1)/2,size(A,2)/2) = 0;
k = 1;
for i = 1:2:size(A,1)
    l = 1;
    for j = 1:2:size(A,2)
        out(k,l) = mean(mean(A(i:i+1,j:j+1)));
        l = l+1;
    end
    k = k+1;
end

Test on input image:
A = rgb2gray(imread('inputImage.png'));

%// Here, You could use any of the method from any answers
%// or you could use the best method from the bench-marking tests done by Divakar
out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2);

imshow(uint8(out));

imwrite(uint8(out),'outputImage.bmp');

Output Image:

Final check by reading the already written image
B = imread('outputImage.bmp');

>> whos B

Name        Size              Bytes  Class    Attributes

B         400x400            160000  uint8

A: One approach based on this solution using reshape, sum & squeeze -
sublen = 2; %// subset length
part1 = reshape(sum(reshape(A,sublen,[])),size(A,1)/sublen,sublen,[]);
out = squeeze(sum(part1,2))/sublen^2;

Benchmarking
Set #1
Here are the runtime comparisons for the approaches listed so far for a input datasize of 800x 800 -
%// Input
A = rand(800,800);

%// Warm up tic/toc.
for k = 1:50000
    tic(); elapsed = toc();
end

disp('----------------------- With  RESHAPE + SUM + SQUEEZE')
tic
sublen = 2; %// subset length
part1 = reshape(sum(reshape(A,sublen,[])),size(A,1)/sublen,sublen,[]);
out = squeeze(sum(part1,2))/sublen^2;
toc, clear sublen part1 out

disp('----------------------- With  BLOCKPROC')
tic
B = blockproc(A, [2 2], @(x) mean(x.data(:))); %// [m n]
toc, clear B

disp('----------------------- With  PERMUTE + MEAN + RESHAPE')
tic
m = 2;n = 2;
T = permute(reshape(permute(reshape(A, size(A, 1), n, []),...
      [2 1 3]), n, m, []), [2 1 3]);
B = reshape(mean(mean(T,1),2), size(A,1)/m, size(A,2)/m);
toc, clear B T m n

disp('----------------------- With  CONVOLUTION')
tic
m = 2;n = 2;
B = conv2(ones(m,1)/m, ones(1,n)/n ,A,'same');
B = B(m-1:m:end ,n-1:n:end);
toc, clear m n B

disp('----------------------- With  MAT2CELL')
tic
AC = mat2cell(A, repmat(2,size(A,1)/2,1), repmat(2,size(A,2)/2,1));
out = cellfun(@(x) mean(x(:)), AC);
toc

disp('----------------------- With  IM2COL')
tic
out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2);
toc

Runtime results -
----------------------- With  RESHAPE + SUM + SQUEEZE
Elapsed time is 0.004702 seconds.
----------------------- With  BLOCKPROC
Elapsed time is 6.039851 seconds.
----------------------- With  PERMUTE + MEAN + RESHAPE
Elapsed time is 0.006015 seconds.
----------------------- With  CONVOLUTION
Elapsed time is 0.002174 seconds.
----------------------- With  MAT2CELL
Elapsed time is 2.362291 seconds.
----------------------- With  IM2COL
Elapsed time is 0.239218 seconds.

To make the runtimes more fair, we can use a number of trials of 1000 on top of the fastest three approaches for the same input datasize of 800 x 800, giving us -
----------------------- With  RESHAPE + SUM + SQUEEZE
Elapsed time is 1.264722 seconds.
----------------------- With  PERMUTE + MEAN + RESHAPE
Elapsed time is 3.986038 seconds.
----------------------- With  CONVOLUTION
Elapsed time is 1.992030 seconds.

Set #2
Here are the runtime comparisons for a larger input datasize of 10000x 10000 for the fastest three approaches -
----------------------- With  RESHAPE + SUM + SQUEEZE
Elapsed time is 0.158483 seconds.
----------------------- With  PERMUTE + MEAN + RESHAPE
Elapsed time is 0.589322 seconds.
----------------------- With  CONVOLUTION
Elapsed time is 0.307836 seconds.


text:
Q: How to duplicate an already initialised map in openlayers 3 How can i duplicate an already initialised map state?
I would like to save the hassle of re-initialising the same map then copying the layers over.

A: You can reuse the map object on different  tags just by changing the target div when you want to use it on different pages.
    map.setTarget('map-holder');

If you want to display both maps at the same time then you can try this example
https://openlayersbook.github.io/ch03-charting-the-map-class/example-05.html.
One map cannot have two targets at the same time as far as I know. Hope that helps.


text:
Q: How can I break the link of git config .insteadOf  I set my url to other url with git config .insteadOf , and now I want to break the link of it. But I don't know how to do that and I can't find it at the reference page.

A: All your git config changes go to ~/.gitconfig, so you should be able to edit it, the relevant part looks like this:
[url "git@github.com"]
        insteadOf = gh

so, maybe try removing these lines?

A: You can remove the section [url "git@github.com"] with:
git config --global --remove-section url."git@github.com"

That is safer than trying to edit manually the git config file.
Reference page: git config#--remove-section.


text:
Q: Multiple jQuery Sliding Content Boxes jQuery beginner here.
I'm working on a site with with two links. Each link slides out content a div with content below. The problem I'm having is that I can't figure out how to toggle between both when the user clicks the other link.
So when the user clicks LINK-A it slides out CONTENT-A, while CONTENT-A is showing if the user clicks LINK-B CONTENT-A should slide back before CONTENT-B slides out.
Hope this makes sense, really hope someone can help me!

A: Ahhh-hah, without seeing your code I'm thinking you might find use in the .not selector.
http://api.jquery.com/not-selector/
$("#foo .bar").not(this).hide();

This will basically grab anything BUT the thing you pass it, then do whatever to it (in this case hide). The nice thing about this is that doing it like so makes your UI expandable, if you plan to add more panels/windows later on.
Hopefully this gets you where you need to go. :)

A: HTML--
Link A - Link B

Content A

Content B

CSS--
Each content div is absolutely positioned inside of the container div so it can be animated in and out of view:
#container {
    position : relative;
    width    : 500px;
    height   : 200px;
}
#content-a {
    position   : absolute;
    top        : 0;
    left       : 0;
    width      : 100%;
    height     : 100%;
    background : red;
}
#content-b {
    position   : absolute;
    top        : 0;
    left       : -100%;
    width      : 100%;
    height     : 100%;
    background : green;
}

JS--
//cache the content area selectors since they will be used multiple times
var $content_a = $('#content-a'),
    $content_b = $('#content-b');

$('#link-a').on('click', function () {

    //when the `a` link is clicked, animate `b` content off-screen
    $content_b.stop().animate({
        left : '-100%'
    }, 500, function () {

        //then animate the `a` content on-screen after the `b` content's animation completes
        $content_a.stop().animate({
            left : 0
        }, 500);
    });
});

//then do the same (but in reverse) for the `b` link
$('#link-b').on('click', function () {
    $content_a.stop().animate({
        left : '-100%'
    }, 500, function () {
        $content_b.stop().animate({
            left : 0
        }, 500);
    });
});

Here is a demo: http://jsfiddle.net/4eN84/

A: You just need a basic accordion set up.
HTML...
A header for content a

Some content A here

A header for content b

Some content B here

CSS...
.opened { display: block; }
div { display: none; height: 200px; background: #600; }
a { display: block; }

jQuery...
 $(".slider").click(function() {
            var dropD = $(this).attr("href");
            if ($("div#" + dropD + " .opened").length) {
                $("div.opened").slideToggle(300).removeClass("opened");
            } else {
                $("div.opened").slideToggle(300).removeClass("opened");
                $("div#" + dropD).slideToggle(300).addClass("opened");
            }
        return false;
        });

jfiddle example HERE

A: Here, a nice solution:
DEMO IN ACTION
HTML:

Open 1

Box 1

Open 2

Box 2

Open 3

Box 3

jQ:
$('.box').hide();

$('.button').click(function(){
  var box = $(this).next();
  box.is(':visible') ? box.slideToggle() : ($('.box').slideUp(), box.slideDown());
});

Just to explain the ternary operators:
statement ? isTrue : isFalse ;
As you can see, it toggles already opened boxes and also - hides the opened one if you click again on it!


text:
Q: How to make a code that prints a text and makes it stay in a window? So, if you don't really know what do I mean, there's a small explanation. I'm also new in C++ so I need help with some things, so yeah. There's the explanation.
If you make a code, for example
cout << "Hello world!";```
-- I forgot how to make it fully good, but that's an example

Then it prints and closes extremelly fast. So, how can I make it so that it DOESN'T dissapear?

A: I am assuming you are talking about console window that closes fast.
In order to prevent that there are multiple ways of doing it. But i will write two simplest ways of doing so.

*

*Add header at the top of your C++ program
#include <stdlib.h>

Then in the end of main function just before return 0 write this line of code
system("pause");

*Another way of doing this is to get any character input before return 0. So write these lines of code
 Console.WriteLine("Press any key to exit...");
 Console.ReadKey();

A: One of the simplest solutions is to use std::getchar() or
std::cin.get(). The program will wait for user input.
However, if there are already characters in the input buffer, then the program, roughly speaking, will ignore and will not wait for input from the user.
If the program is specific to Windows, then one of the most common solutions is to use std::system("pause").
For std::system(), you must also include the cstdlib header.
But it would still be better to set a breakpoint at the end of the program or, if your IDE allows (for example Visual Studio), then enable the option that leaves the console opened even after exiting. For example, VS allows you to run a program in non-debug mode, which does not close the console. To run the program in this mode, you can press the key combination Ctrl + F5.
However, in this case, in the project settings there should be Subsystem option in the System section in the Linker. And the value of Subsystem should be /SUBSYSTEM:CONSOLE.


text:
Q: Custom directive using ngModelController not updating UI value I am trying to create a directive that formats a decimal value to a time value h:mm. If a user enters a time value the model should be updated with the decimal representation. If a user enters a decimal value his input should be replaced with the formatted value.
I am using the directive as follows:
<input type="text" hour-input ng-model="vm.hours"/>

Here is the relevant code:
app.directive('hourInput', hourInput);

function hourInput() {
  var directive = {
    link: link,
    restrict: 'A',
    require: 'ngModel'
  };

  return directive;

  function link(scope, element, attrs, ngModelController) {
    // model -> view
    ngModelController.$formatters.push(function (value) {
      return formatTime(value);
    });

    // view -> model
    ngModelController.$parsers.push(function (value) {
      var result;
      if (!/^\d?[\d,\.]*$/.test(value)) {
        result = parseTime(value);
      } else {
        result = parseFloat(value);
      }
      return result;
    });
  }
}

function parseTime(value) {
  // code removed for brevity
  return hours + minutes / 60;
}

function formatTime(value) {
  // code removed for brevity
  return result;
}

Here is the plunker. The interaction with the model is working. However the formatted time is not updated in the UI.

A: ngModelController.$parsers parses your value with every keystroke. Since you do not know when the user is ready with entering the value, you can't really parse the value on every update.
Assuming you want to allow the values

*

*5

*5.

*5.5

*5:30

the parser is not the way you want to go.
I think that when you attach the function on the blur or change event you get the desired behavior.
Something like
element.bind('blur', function () {
      element.val(formatTime(element.val()));
    });


text:
Q: How can I toggle databases in Django? Django's settings.py file has a DATABASES dictionary that stores configuration information for any number of database backends:
# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'test': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testing',
        'USER': 'bert',
        'PASSWORD': '***',
        'HOST': 'remotemysql.com',
        'PORT': '3306',
    },
    'dev': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'development',
        'USER': 'ernie',
        'PASSWORD': '***',
        'HOST': 'remotemysql.com',
        'PORT': '3306',
    },
    ...
}

I would expect the Django authors to have included a method to easily switch among these configuration options, such as a separate variable somewhere
USE_THIS_DB = 'test';

in order to easily switch between testing, development, production, etc. databases.
I can't find this option.  The only information I can find about switching databases is to manually rename the different configuration options in DATABASES so that the one I want to use is called default, which seems unnecessarily clunky, error-prone, and non-portable.
Is there no way to more elegantly switch Django among different databases at startup?

A: Why not just DIY in Python ?
# settings.py
DATABASES = {
    'test': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testing',
        'USER': 'bert',
        'PASSWORD': '***',
        'HOST': 'remotemysql.com',
        'PORT': '3306',
    },
    'dev': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'development',
        'USER': 'ernie',
        'PASSWORD': '***',
        'HOST': 'remotemysql.com',
        'PORT': '3306',
    },
    'sqlite': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
}

USE_THIS_DB = 'test'

DATABASES['default'] = DATABASES[USE_THIS_DB]


text:
Q: How to get hobbies in student lists with subquery mysql well, i have 100 student lists and every student has more than a hooby.
i have 2 tables,
table name = students
attribute = student_id,name,dob,address
and
table name = hobbies
attribute = hobby_id, student_id, hoby_name.
how do i get result like below.
.student_id | name   | dob        | address   | hobby.
 1          | Jordan | 12-12-1998 | 23 avenue |reading, dota2, football
 2          | Bela   | 13-01-1997 | 12 hills  |swimming, badminton
 3          | Jack   | 01-02-1999 | 07 clinton|dota2

once i try to use subquery it says "subquery returns more than 1 row".
thank u guys.

A: select sa.student_id,name,dob,address, GROUP_CONCAT(hoby_name)
from students_attribute sa
left join hobbies_attribute ha
on sa.student_id = ha.student_id
group by sa.student_id

This will provide to required result.


text:
Q: Force compatibility IE10 on localhost How can I make my localhost in IE10 use the compatibility mode defined in meta?
Windows thinks that the users who use localhost don't want compatibility but we do, and we want to force it on our clients. It works fine when we visit the hostname, the problem is on localhost. Also fine for Chrome and Firefox.
Greetings
Jeff

A: site on intranet wa working good but my localhost site was not properly working with ie 10 but this solution was worked for me;
    <meta http-equiv="X-UA-Compatible" content="IE=10">

A: Adding the
<meta http-equiv="X-UA-Compatible" content="IE=6">

instead of the
<meta http-equiv="X-UA-Compatible" content="IE=8">

did the trick for localhost. And make sure it's in all the frames.


text:
Q: Fibonacci sequence time and space complexity This is not the most efficient way to get Fibonacci sequence numbers but I am learning Big O and would like confirmation and explanation of the space and time efficiency of the code below. The code is in Python and I wrote it such that I use a list and append to it and just return the last value.
The append method takes O(1) time as shown here but I am doing the operation almost n times so would I get O(n) for time complexity?
With regard to space complexity, should I consider the space used as an arithmetic series because the list would have to be moved elsewhere if the number entered is larger than what is given to the function stack at the beginning?
The code in this question is for the recursive approach.
def getFib(position):
  if position == 0:
    return 0
  if position == 1:
    return 1

  list_ = [0, 1]
  previous = 1

  for pos in range(2, position+1):
    list_.append(list_[pos-1] + list_[pos-2])

  return list_[position]

if __name__ == "__main__":
  print(getFib(0))
  print(getFib(1))
  print(getFib(2))
  print(getFib(3))
  print(getFib(4))
  print(getFib(5))
  print(getFib(6))
  print(getFib(7))
  print(getFib(8))
  print(getFib(9))

A: time complexity: O(n) because you are executing n times your loop that has a constant time complexity.
space complexity: O(n) because you are storing n numbers in your list.
Of course, you didn't need to store all the numbers but only the last two values. That would have reduced the space complexity to O(1).


text:
Q: How to save multiple outputs after reading multiple inputs in Python i am reading .png images from a folder and doing some operations and i want to save those images in an order like Img1.png, Img2.png, Img3.png.... i tried to use this code :
cv2.imwrite("Img{}.png".format(i),Image)

but it keeps overriding single image.
below is the code:
def main(path):
    i=0
    image = cv2.imread(path)

    #do some operations on image

    cv2.imwrite('Img{}.png'.format(i),image)
    i=i+1
    cv2.waitKey(0)

The path contains multiple .png images so when main executes it resets the value of 'i' and output is overridden.

A: I suppose it's because of the type of formatting. The old python uses '%s %s' % ('one', 'two')format, did you try this formatting?

A: I suppose that path - space separated:
path = "im1.png  imre.png  lena.jpg"

it seams so:
path_lst = path.split(' ')
for i, path_i in enumerate(path_lst):
    image = cv2.imread(path_i)
    #do some operations on image
    cv2.imwrite('Img{}.png'.format(i),image)

all works. Idk - why they gave me "-" =D


text:
Q: Retornar valor DataLayer Boa tarde.
tenho uma procedure que faz alguns comandos e retorna
0 = sucesso;
1 = sem sucesso;
 alter PROCEDURE [dbo].TesteRetorno
    (
        @DS_NOME_ARQUIVO_SINCRONISMO AS VARCHAR(200) = null
    )

    AS

    if exists(select top 1 ID_USUARIO from BCS_USUARIO where ID_USUARIO = 'brisa')
    begin

    return 0

    end

    else
return 1

gostaria de usar esse retorno no meu código C#.
    ParameterCollection oP = new ParameterCollection();
    oP.Add("@DS_NOME_ARQUIVO_SINCRONISMO", "", DbType.String);

    var retorno = DataLayer.ExecuteNonQuery("TesteRetorno", oP).ToString();

Mas nunca recebo nada de retorno;
segue a classe do DataLayer
#region Assembly brsBiblioteca.dll, v1.0.3.0
// C:\Users\ctorres\Documents\Projetos\FSLexMark\Legado\FRAMEWORK v3.5\LEXMARK\SAP\MigracaoSAP_V4\Packages\brsBiblioteca.dll
#endregion

using System;
using System.Data;

namespace Biblioteca.Data
{
    public sealed class DataLayer
    {
        public DataLayer();

        public static void ExecutarCommand(string pstrCommandText, ParameterCollection phtParameters);
        public static void ExecutarCommand(string pstrCommandText, ParameterCollection phtParameters, string strConexao);
        public static void ExecutarCommand(IDbConnection objConnection, IDbTransaction objTransaction, string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static DataSet ExecuteDataset(string pstrCommandText);
        public static DataSet ExecuteDataset(string pstrCommandText, ParameterCollection phtParameters);
        public static DataSet ExecuteDataset(string pstrCommandText, ParameterCollection phtParameters, string strConexao);
        public static DataSet ExecuteDataset(IDbConnection conn, IDbTransaction tran, string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static DataSet ExecuteDatasetNoTransaction(string pstrCommandText);
        public static DataSet ExecuteDatasetNoTransaction(string pstrCommandText, ParameterCollection phtParameters);
        public static DataSet ExecuteDatasetNoTransaction(IDbConnection conn, string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static DataSet ExecuteDatasetNoTransaction(string pstrCommandText, ParameterCollection phtParameters, string strConexao);
        public static int ExecuteNonQuery(string pstrCommandText);
        public static int ExecuteNonQuery(string pstrCommandText, ParameterCollection phtParameters);
        public static int ExecuteNonQuery(string pstrCommandText, ParameterCollection phtParameters, string strConexao);
        public static int ExecuteNonQuery(IDbConnection objConnection, IDbTransaction objTransaction, string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static object ExecuteScalar(string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static object ExecuteScalar(string pstrNomeStoredProcedure, ParameterCollection phtParameters, int Timeout);
        public static object ExecuteScalar(IDbConnection conn, IDbTransaction tran, string pstrNomeStoredProcedure, ParameterCollection phtParameters);
        public static object ExecuteScalar(IDbConnection conn, IDbTransaction tran, string pstrNomeStoredProcedure, ParameterCollection phtParameters, int TimeOut);
        public static IDbCommand GetCommand();
        public static IDbConnection GetConnection();
        public static IDbConnection GetConnection(string pstrConnectionString);
        public static IDbDataAdapter GetDataAdapter(IDbCommand cmd);
        public static DbType GetDbType(DbType pDbType);
        public static System.Data.OracleClient.OracleType GetOracleType(DbType pDbType);
    }
}


text:
Q: how to store values in database at hierarchical view In my project i need to create restaurant menu card,i want to insert values given below
-menus(like dinner,lunch,breakfast)
  .
   -menu_group(like soup,juice)
    .
    .
       -menu_item
              apple-juice...................... $10
              milk_shake_apple................. $15
       -menu_item

    -menu_group

-menu

which one is best custom field or taxonomy? or is there any plug in to use

A: I would suggest a custom hierarchical taxonomy; call it 'menu'.
Top level terms (menus), have child terms (menu groups). Each child term has one or more posts (menu items) associated with it. Posts have custom fields (price) attached to them.
Note that you will need some custom code (a category walker) to display the menu items for each menu group on the front-end.


text:
Q: ASP.NET MVC Removed Controller QueryString Action When I use the default route:
routes.MapRoute(
"Default", //
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

The app finds the method below:
public ActionResult News(DateTime? FromDate, DateTime? ToDate)
{
    IList<Model.MonthGroupNewsEntry> monthGroupNewsEntries = new services.NewsEntryService(new Data.SqlNewsEntryRepository()).GetMonthGroupNewsEntries();
    IList<Model.NewsEntry> newsEntries = new Services.NewsEntryService(new Data.SqlNewsEntryRepository()).GetNewsEntriesWithinDateRange(FromDate,
    return View(new Models.NewsViewModel(monthGroupNewsEntries, newsEntries));
}

From:
<%= Html.ActionLink(b.MonthName + " " + b.Year.ToString() +  " (" + b.EntryCount.ToString() + ")", "News", new { FromDate = b.FromDate, ToDate = b.ToDate}) %>

But when I attempt to remove the controller from the url using below:
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

I get a 404 resource not found error.
Note : The other methods in the class work fine but these either have no parameters or "id", it's only the method that's called with the two DateTime? parameters that fails when I remove the controller from the URL.
Thanks for the updated answer, however - the only change I make is to remove the "{controller}/" text from the "routes.MapRoute" in the above - there is no chance of any spelling mistake etc., this is also using MVC 3.
Further : using Charx's suggestion:
routes.MapRoute(
"SpecificAction",
"{action}/{FromDate}/{ToDate}",
new { controller = "ControllerName", id = UrlParameter.Optional } );

I no longer get a 404 error, but it gave a "400 - bad request" due to the '/'s in the date, so I reformatted the date as dd-MM-YYYY:
<%= Html.ActionLink(b.MonthName + " " + b.Year.ToString() +  " (" + b.EntryCount.ToString() + ")", "News", new { FromDate = b.FromDate.ToString("dd-MM-yyyy"), ToDate = b.ToDate.ToString("dd-MM-yyyy")}) %>

It no longer 404's, the FromDate is recognised fine but the ToDate comes through as null.
Final : I changed the type of the two dates to strings and cast them to datetime in the method - now both parameters come through fine - I guess it was perhaps looking for the time element of the first parameter and therefore ignored the second.
Only outstanding thing now is that the methods requiring an "id" parameter now seems to use it as a querystring (NewsEnrty?ID=5) rather than "NewsEntry/5" if anyone can answer this then thanks - otherwise question answered - thanks again Chanx.

A: Ok, when you edit your question I get the initial answer you want to have. I also create simple solution to test your problem and it works well also for News controller action. There are no way how dates could affect routing. But you need to check firstly - maybe you made some mistakes. Check for routing once again, chech controller name, retype it, chech that proper action placed n prpper controller. If you still will have the problem create a small project for your problem and putit on dropbox or somewhere else where I can get it and test, because for now I can't reproduce your issue. Also, I;m working with MVC 3.

A: Edited. If you want to still be able to identify the action to call in your URL, then you must specify your Specific Action route and be sure to identify the correct Controller the actions are on:
routes.MapRoute(
"SpecificAction",
"{action}/{FromDate}/{ToDate}",
new { controller = "ControllerName", id = UrlParameter.Optional } );

routes.MapRoute(
"Default", //
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );