text:
Q: how to append the error class next to textbox in jquery I just want to ask on how to display error message next to textbox if the user doesn't enter anything and press submit required attribute should throw the desired error next to the textbox and not below it

A: You can check for the empty inputs and add an error span next to it:
$("input").filter(function () {
  return $(this).val().trim().length == 0;
}).after('You need to fill this!');

Snippet

$(function () {
  $("input").filter(function () {
    return $(this).val().trim().length == 0;
  }).after('You need to fill this!');
});
* {font-size: 10pt; font-family: Segoe UI;}
.error {background: #f99; border: 1px solid #f00; padding: 3px; color: #fff; font-size: 85%;}

<input value="Filled" />

<input placeholder="Not filled" />

<input value="Filled" />

<input value="Filled" />

<input placeholder="Not filled" />

<input value="Filled" />


text:
Q: Attempt to modify HTMLTableRowElement.prototype I have two methods, working nicely in couple of pages, but when it comes to a Greasemonkey script they fail for some reason, throwing an 'is not a function' error.
The very same code, while attached normally to the page, works perfectly.
HTMLTableRowElement.prototype.hideRow = function(){this.style.display = 'none'};
HTMLTableRowElement.prototype.showRow = function(){this.style.display = ''};

Error is appearing upon calling for one of these functions. Any clues?

A: That code doesn't work from a Greasemonkey script due to the GM script being in a different scope and (nominally) in a sandbox. See "Why is window (and unsafeWindow) not the same from a userscript as from a script tag" for more information and for workarounds (@grant none (maybe), or script injection, or unsafeWindow).
However, unless you are trying to alter existing code added by/to the page, don't do things that way.
Use jQuery's .hide(), .show(), or .toggle().

Or create a class using GM_addStyle(), EG:
GM_addStyle (".GM_hide {display: none !important;}");

and use DOM functions to add or remove the class as desired. EG:
//--- Select the 2nd row of the first table
var someRow = document.querySelector ("table tr:nth-of-type(2)");

someRow.classList.add    ("GM_hide");
someRow.classList.remove ("GM_hide");
someRow.classList.toggle ("GM_hide");

redpajama_set_name: RedPajamaStackExchange


text:
Q: shouldOverrideUrlLoading is not detecting Hash url change for inside view in html5 I am working on web + android project but thing is that i can not able to get url from shouldOverrideUrlLoading.
I think this is because there is nested html view and dynamic data assigning into html container.
There is sliding menu in html web view its same like facebook , gmail type sliding menu but its in html.
when you tap any item of that menu i cant get url ..( i want to just determine which button or menu item is tap by user).
if i try simple a href link than it works i get shouldOverrideUrlLoading url.
****I think my web developer loading one index page and into that he put one div tag and he just change the content of div tag when you move from one page to another and thats why i don't get url in shouldOverrideUrlLoading is there any other way to retrieve user click on button or item****
IS there any way to track loading of nested html pages.
Here is Index page of nested html , css , js
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="msapplication-tap-highlight" content="no">
        <title>Application</title>

        <link rel="stylesheet" href="css/all.css">

This is sliding menu

Accueil

Votre compte

Proposer une vidéo

Vidéos

Populaires

+ commentées

Dernières vidéos

Concours

Tous

En cours

Terminé

Secteurs

            {{#secteurs}}

{{nom_secteur}}

            {{/secteurs}}

Android code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myWebView = (WebView) findViewById(R.id.webview1);
    myWebView.setWebChromeClient(new WebChromeClient());
    HelloWebViewClient webViewClient = new HelloWebViewClient();
    myWebView.setWebViewClient( webViewClient);
    myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    WebSettings webSettings = myWebView.getSettings();

    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.loadUrl("file:///android_asset/index.html");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class HelloWebViewClient extends WebViewClient{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url){
        Log.i("shouldOverrideUrlLoading", url);
        return true;
    }
}

A: Put this code before load url
    webView.setWebViewClient(new Callback());
    webView.setWebChromeClient(new webChromeClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setSavePassword(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setSupportMultipleWindows(true);
    webView.getSettings().setAppCacheMaxSize(1024*1024*16);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    webView.getSettings().setAppCachePath(appCachePath);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setRenderPriority(RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    String databasePath = "/data/data/" + getApplicationContext().getPackageName() + "/databases/";

    webView.getSettings().setDatabasePath(databasePath);
    //webView.getSettings().setGeolocationEnabled(true);
    webView.getSettings().setSaveFormData(true);
    webView.getSettings().setPluginsEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    JavascriptInterface javasriptInterface = new JavascriptInterface(MainActivity.this);
    webView.addJavascriptInterface(javasriptInterface, "Print");

private class Callback extends WebViewClient{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        AppLog.logString(TAG+"shouldOverrideUrlLoading");
        AppLog.logString(TAG+"url: "+url);

        view.loadUrl(url);
        }
        return true;
        //return (false);
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        AppLog.logString(TAG+"onPageStarted");
        AppLog.logString(TAG+"url: "+url);

        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        AppLog.logString(TAG+"onPageFinished");
        AppLog.logString(TAG+"url: "+url);

        super.onPageFinished(view, url);
    }
 }
 private class webChromeClient extends WebChromeClient{
     @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
         AppLog.logString(TAG+"onExceededDatabaseQuota");
         quotaUpdater.updateQuota(5 * 1024 * 1024);
     }
     @Override
     public void onProgressChanged(WebView view, int newProgress) {
        MainActivity.this.setProgress(newProgress * 1000);
     }
 }

Applog.logString is nothing it's log.d so change it this is working for me very well


text:
Q: implementing abstract classes vs interfaces I am new to using interfaces and abstract classes.  The team I am working with came up with an implementation of what they call a base class that will be implemented by all view model classes.  This is what they came up with:
public interface IBaseViewModel<T>
{
    #region public properties
    string Message { get; set; }
    string SaveType { get; set; }
    bool IsVisibleMessage { get; set; }
    bool IsVisibleDecision { get; set; }
    bool IsApiSuccess { get; set; }
    Guid EntityId { get; set; }
    string EntityQDSId { get; set; }
    string EntityType { get; set; }
    #endregion

    #region public methods
    Task Init();
    Task Init(Guid Id);
    Task<T> Create();
    Task<T> Get(Guid Id);
    Task<T> Get(string Id);
    Task<IEnumerable<T>> GetList(Guid Id);
    Task<IEnumerable<T>> GetList(string Id);
    Task<T> Insert(T t);
    Task<T> Update(Guid Id, T t);
    Task<T> Delete(Guid Id);
    void Dispose();
    #endregion
}

public abstract class BaseViewModel<T> : IBaseViewModel<T>, IDisposable
{
    public Guid EntityId { get; set; }
    public string EntityQDSId { get; set; }
    public string EntityType { get; set; }

    public string Message { get; set; }
    public string SaveType { get; set; }
    public bool IsVisibleMessage { get; set; }
    public bool IsVisibleDecision { get; set; }
    public bool IsApiSuccess { get; set; }

    public virtual Task Init()
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task Init(Guid Id)
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<T> Create()
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<T> Get(Guid Id)
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<T> Get(string Id)
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<IEnumerable<T>> GetList(Guid Id)
    {
        return Task.FromResult<IEnumerable<T>>(default);
    }

    public virtual Task<IEnumerable<T>> GetList(string Id)
    {
        return Task.FromResult<IEnumerable<T>>(default);
    }

    public virtual Task<IEnumerable<T>> GetForGrid(Guid Id)
    {
        return Task.FromResult<IEnumerable<T>>(default);
    }

    public virtual Task<T> Insert(T t)
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<T> Update(Guid Id, T t)
    {
        return Task.FromResult<T>(default);
    }

    public virtual Task<T> Delete(Guid Id)
    {
        return Task.FromResult<T>(default);
    }

    public virtual void ProcessDto(T t)
    {
    }

    public virtual void Dispose()
    {
    }
}

Below is the implementation:
      public interface IAccountBillViewModel<T> : IBaseViewModel<AccountBillGroup>
{

}

public class AccountBillViewModel<T> : BaseViewModel<AccountBillGroup>, IAccountBillViewModel<AccountBillGroup>
{

}

In researching this question I found several comments like the one below
https://stackoverflow.com/a/479154
[@Alex][1]
My points:

*

*Since there was only code signatures and no implementations of any code in the abstract class and because you can inherit from multiple interfaces, why use an abstract class instead of a interface?

*The inheritance slot will be left open in case we wanted to inherit from another class in the future.

Their points:

*

*The properties only need to be implemented in the base class and those properties will be available in all implementations without declaring the properties again.

*Only those methods that need to be used in the implementation need to be overridden.  If an interface was used all the methods would have to be implemented in every implementation.

Is there value in choosing to go with an abstract base class when there is not implementations, only method signaatures?

A: I would prefer using interfaces, as class may implement multiple interfaces.
Abstract classes make more sense when you have some default behavior that can be re-used in inheriting classes.


text:
Q: Has anyone tried to use IPython with the Hylang syntax? You can use Hylang with this magic:
In [1]: %%script hy
(print "Hello, Cuddlefish!")
   ...:
=> Hello, Cuddlefish!
=> hy 0.9.12

In [2]:

I want to use it directly:
In [1]: (print "Hello, Cuddlefish!")
Hello, Cuddlefish!

Int [2]:

A: Try out my hymagic module. You can install it using
$ pip install hymagic

Load the magic using
%load_ext hymagic

Use %hylang for one line and %%hylang for a whole cell. For example
%hylang (+ 1 2 3)

and
%%hylang
(defn hello []
   (print "hello world"))
(hello)

A: One can instead install the hy kernel, where there's no need to prefix

%hylang

at the start of every cell.

A: (Late to the party answer)
The Hy kernel mentioned in other comments (hy_kernel) isn't maintained anymore.
The actively developed one is now Calysto Hy, based on the Metakernel.


text:
Q: How do I configure (or debug) default gestures on Ubuntu 22.04 Since upgrading to Ubuntu 22.04 I've noticed a peculiarity. 3 finger swipe down shows the activities overview, as expected, but 3 fingers swipe up doesn't work well or consistently.
It actually works the very first time I do it and then after that just shows the "Activities" button on the top menu bar. If I do it any time after that it just hides my desktop icons but doesnt actually show me the overview. However swiping down consistently works. Any advice on how I can either

*

*configure it

*debug it

*fix it

Thanks
PS: I have already seen How configure gestures on Ubuntu 22.04 lts but I want to actually fix this issue


text:
Q: Are these two measurable maps equal in distribution? Related : Is the set of discrete measures measurable?
Let $(X,\mathfrak{M})$ be a measurable space and $Prob(X,\mathfrak{M})$ be the set of probability measures on $(X,\mathfrak{M})$.
Define $A_{t,B}:=\{\mu\in Prob(X,\mathfrak{M}): \mu(B)\leq t\}$ for each $t\in [0,\infty]$ and $B\in \mathfrak{M}$.
Let $\mathscr{C}$ be collection of all such $A_{t,B}$ and $\sigma(\mathscr{C})$ the smallest $\sigma$-algebra generated by $\mathscr{C}$.
Let $(\Omega,\mathscr{F},P)$ be a probability space and $G,H:(\Omega,\mathscr{F})\rightarrow (Prob(X,\mathfrak{M}),\mathscr{C})$ be measurable functions.
My question is the following:

*

*If $G_*P=H_*P$ and $G_x$ is discrete almost everywhere, then is $H_x$ discrete almost everywhere too?

*Let $D$ be the set of discrete measures on $(X,\mathfrak{M})$. Then, is $D\in \sigma(\mathscr{C})$?
If $2$ is true, then this implies that $1$ is true. But I don't know how to prove $D$ is measurable in this case.. How do I prove $1$?
(Note that in my past post, I tried to show that $D$ is measurable with respect to the product $\sigma$ algebra, but as written in the comment there, I realized that this $\sigma$ algebra is too small! So I tried to enlarge the $\sigma$-algebra on $P(X,\mathfrak{M})$ in this post.. I think this direction is correct. If $D$ is not even measurable with respect to $\sigma(\mathscr{C})$, how much should we enlarge the sigma-algebra to make $D$ measurable..?)


text:
Q: Why is my c++ clock() based function returning a negative value? I am still new to C++, is the clock function absolute (meaning it counts how long you sleep for), or is it how much time the application actually executes for?
I want a reliable way to produce exact intervals of 1 second.  I am saving files, so I need to account for that.  I was returning the runtime for that in milliseconds, and then sleeping for the remainder.
Is there a more accurate or simpler way to do this?
EDIT:
The main problem I am having is that I am getting a negative number:
double FCamera::getRuntime(clock_t* end, clock_t* start)
{
    return((double(end - start)/CLOCKS_PER_SEC)*1000);
}

clock_t start = clock();
doWork();
clock_t end = clock();

double runtimeInMilliseconds = getRuntime(&end, &start);

It's giving me a negative number, what's up with that?
Walter

A: clock() returns the number of clock ticks elapsed since the program was launched. If you want to convert the value returned by clock into seconds divide by CLOCKS_PER_SEC (and multiply for the other way around).
There is just one pitfall, the initial moment of reference used by clock as the beginning of the program execution may vary between platforms. To calculate the actual processing times of a program, the value returned by clock should be compared to a value returned by an initial call to clock.
EDIT
larsman has been so kind to post other pitfalls in the comments. I have included them here for future reference.

*

*On several other implementations, the value returned by clock() also includes the times of any children whose status has been collected via wait(2) (or another wait-type call). Linux does not include the times of waited-for children in the value returned by clock().

*Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 [as mandated by POSIX] this function will return the same value approximately every 72 minutes.
EDIT2
After messing around a while here is my portable (Linux/Windows) msleep. Be wary though, I'm not experienced with C/C++ and will most likely contain the stupidest error ever.
#ifdef _WIN32

#include <windows.h>
#define msleep(ms) Sleep((DWORD) ms)

#else

#include <unistd.h>
inline void msleep(unsigned long ms) {
    while (ms--) usleep(1000);
}

#endif

A: You missed * (pointer) ,
Your argument is pointer (address of clock_t variable)
so, Your code must be modified::
return((double(*end - *start)/CLOCKS_PER_SEC)*1000);

A: Under windows, you can use:
VOID WINAPI Sleep(
  __in  DWORD dwMilliseconds
);

In linux, you will want to use:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);

Notice the parameter difference - milliseconds under windows and seconds under linux.

A: My approach relies on:
int gettimeofday(struct timeval *tv, struct timezone *tz);
which gives the number of seconds and microseconds since the Epoch. According to the man pages:
The tv argument is a struct timeval (as specified in <sys/time.h>):

           struct timeval {
               time_t      tv_sec;     /* seconds */
               suseconds_t tv_usec;    /* microseconds */
           };

So here we go:
#include <sys/time.h>

#include <iostream>
#include <iomanip>

static long myclock()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (tv.tv_sec * 1000000) + tv.tv_usec;
}

double getRuntime(long* end, long* start)
{
    return (*end - *start);
}

void doWork()
{
    sleep(3);
}

int main(void)
{
    long start = myclock();
    doWork();
    long end = myclock();

    std::cout << "Time elapsed: " << std::setprecision(6) << getRuntime(&end, &start)/1000.0 << " miliseconds" << std::endl;
    std::cout << "Time elapsed: " << std::setprecision(3) << getRuntime(&end, &start)/1000000.0 << " seconds" << std::endl;

    return 0;
}

Outputs:
Time elapsed: 3000.08 miliseconds
Time elapsed: 3 seconds


text:
Q: Rails setup production server on Ubuntu I spent the last few days trying to find some tutorial on how to properly set up a production server for rails with RVM + Apache + Passenger + MySQL + Auto Deploy (Capistrano if possible).
No luck so far, I've read at least 6 - 7 tutorials..
I was wondering if a tutorial that starts from scratch (clean Ubuntu install) to deploy actually exists.
Thanks


text:
Q: Unable to detect http headers I've setup my api into web server, currently im unable to retrieve data using my app key but able to do so using postman, please do help
const httpOptions = {
      headers: new HttpHeaders({
        'APP_KEY': 'ABCDEFGHJ'

      })
    };

    this.http.get('<my_api_link>', httpOptions).subscribe((res) => {
      this.Result = JSON.stringify(res);
      console.log('Result', this.DataResult);
    }, (err) => {
      console.error(err.status);
      console.error(err.error); // Error message as string
      console.error(err.headers);
    });

Error message was unable to find app key

A: Try to set headers this way
const httpHeaders = new HttpHeaders()
  .set('APP_KEY', 'ABCDEFGHJ');

this.http.get('<my_api_link>', httpHeaders)

A: Try this :
var token = 'ABCDEFGHJ';
const myHeaders = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': token });
this.http.get('<my_api_link>', { headers: myHeaders });

Or
let headers = new HttpHeaders();
headers = headers.set('APP_KEY','ABCDEFGHJ');

A: Modifying your code snippet :
const httpOptions = {
  headers: new HttpHeaders().set('APP_KEY', 'ABCDEFGHJ')
};

this.http.get('<my_api_link>', httpOptions).subscribe((res) => {
  this.Result = JSON.stringify(res);
  console.log('Result', this.DataResult);
}, (err) => {
  console.error(err.status);
  console.error(err.error); // Error message as string
  console.error(err.headers);
});

A: import {HttpClient} from '@angular/common/http';
constructor(private _httpClient: HttpClient) {
// some code
}


text:
Q: When to flush Pyserial buffers? I am working with Pyserial and have a question regarding best practices surrounding flushing the input and output buffers. Currently I reset the output buffer before sending a command and reset the input before reading the reply. It seems I occasionally miss the start of a reply so I am considering modifying my program to reset the input buffer before I send my command. I am also considering linking my send and receive functions so that the send always calls the receive and hopefully tightens up the loop.
    def send_cmd(self, cmd_to_send):
        self.ser.reset_output_buffer()
        self.ser.write(cmd_to_send)

    def receive_cmd(self):
        self.ser.reset_input_buffer()
        # Read logic below

Considering transitioning to something like this
    def send_cmd(self, cmd_to_send):
        self.ser.reset_output_buffer()
        self.ser.reset_input_buffer()
        self.ser.write(cmd_to_send)
        self.receive_cmd()

    def receive_cmd(self):
        # Read logic below

A: In the port configuration, the key timeout let you wait some time in each communication with the port.
I usually  use this parameter to prevent problems with the port buffer. Try this and maybe it is unnecessary to flush.

A: This post gets decent traffic so I just want to let everyone know I never found the answer to this question. I tried a variety of configurations but ultimately flushing seems to rely more on the hardware itself than the software. I did end up transitioning to the code I mentioned and it seemed to help, albeit slightly. So I would recommend something like this:
def send_cmd(self, cmd_to_send):
    self.ser.reset_output_buffer()
    self.ser.reset_input_buffer()
    self.ser.write(cmd_to_send)
    self.receive_cmd()

def receive_cmd(self):
    # Read logic below

If anyone can supply a better answer, I would still appreciate it :)
Edit: I also was reading bytes individually, as I needed to. You may have more success using readlines() as Eduardo mentioned in the other answer.

A: def send_cmd(self, cmd_to_send):
    self.ser.reset_output_buffer()
    self.ser.reset_input_buffer()
    self.ser.time.sleep(0.1)
    self.ser.write(cmd_to_send)
    self.ser.time.sleep(0.1)
    self.receive_cmd()

def receive_cmd(self):
    # Read logic below


text:
Q: Why so little reaper cheese in top-tier SC2 games? I'm very often executing the following build in platinum/diamond league games (EU server):
SCV
Supply Depot
Refinery
Barracks
Saturate the refinery fully
Barracks
Barracks
Reaper
Supply depot
3xReaper
...into...
Command Center or Factory, then Command Center

I can measure the execution by the moment, when the last reaper is queued. If it's around 2:01, it's totally perfect, 2:04-2:06 is OK, 2:11 is accetable, later - it becomes non-efficient.
Note, that I mostly play on 2v2-3v3s, which may be an important thing.
This build is designed to punish greedy players, who start with base-first. 4 reapers are enough to take out a Queen, Stalker and easily a bunch of Marines. They seem enough even to take out a Siege Tank if it has no support or is supported only by SCVs. Marines, low-speed zerglings and no-charge Zealots stand no chance over such a small army. Not to say, that from what I remember, 4 reapers one-shots workers.
The advantage of such an assault is that it may be performed head-on. Even if you don't sneak Reapers in the mineral line by cliffs, you can simply engage forces and very often leave such a battle without losing a single reaper. If you then manage to produce additional reapers to increase your army to 6 or 8 of them, this is ususally a game-over.
Now the interesting thing is counter for such early one-base all-in cheese. Firstly, static defenses totally kills Reapers. One Spine Crawler, Photon Cannon or Bunker built near mineral line ends up this atack and forces me to go to mid-game transition (most likely to bio, having 3 barracks built already). However, static defenses are rarely seen in pro-player matches, because they consume resources and are - well - static, so immobile.
Also, this build is highly effective against Terrans and Protoss, but not-so-much against Zerg, because Queen - though possible to kill with 4 reapers - takes a lot of time, which gives Zerg oportunity to, say, queue a Spine Crawler or two (one is not enough, because it can be killed by those reapers before hatching).
You can take a look at pro-player matches TvX - just check, what their opponents have at around 2:50-3:00. This is the moment when 4 reapers run into the base. Even having 1 reaper some of the pro players manage to kill a Zergling, when Zerg have a Queen and 4 Zerglings - now imagine, what could have happened if there were 4 reapers instead of 1.
It is also not effective against non-greedy players, who stands on one base longer, because at that point they usually already have like 2 Stalkers, a bunch of Zerglings (and Zergling Speed already queued up) or a sieged Tank, which shuts down such an attack completely.
One more thing - this requires enormous amounts of micro to perform properly, because you have to babysit Reapers very carefully. This leaves me - as a definitely non-pro player - often in situation when I have CC, 3 barracks, a lot of money and no defences, when opponents retaliate. I believe though, that on pro-level players are able to micro/macro this scenario properly.
I actually executed this build successfully numerous times on 1v1s as well, though in Gold League.
So the question: why such Reaper-heavy opener is not executed on top-tier matches? We see zergling push every now and then, massing Adepts at the early stages, but Terrans barely ever use full potential of Reapers and their grenades.

A: Heavy reapers opening have been tried especially in the past, but also recently. Check for example Reynor vs Clem
As for other kind of cheeses, they don't work very well at the highest level because players know how to scout, how to read what they find and how to react accordingly.
If a player scout no 2nd CC and 3 rax, the player knows for sure some form of aggression is coming and from rax without a tech lab attached, it can only be either marines or reapers which are easily dealt with in the same way. The player would then change whatever strategy he/she intended to go for to counter this early aggression, possibly dropping bunkers/spine crawlers/cannons/shield batteries, going heavy on marines or stalkers or queens and lings.
This rush is pretty easy to defend, no matter the race. I would be surprise this would work from diamond up.
Your fallacy is to take as an example of your thesis random TvX games and comparing their army at the 3 minutes mark with yours, in a totally unrelated game. If a player, after scouting, confirms that the opponent is not going for any kind of aggression and doesn't want to be aggressive from the start himself/herself, the player will invest in the economy and that's why you see few units in the player base.

A: I think two reasons:

*

*1v1 is very different (and much more "figured out") than 2v2 and above.
The whole game changes once you have multiple people on a team - in 1v1, there are things you just can't do because a good enough opponent always beats it. In 2v2 some of those things become viable because your opponent can cover for you, especially if you coordinate.
Example: when 1v1 pros do 2v2 games, we often see the protoss player mass phoenixes to the exclusion of other units, in a way that they couldn't get away with in 1v1, because their teammate covers for the things mass phoenix is weak to.

*You almost answered your own question here:

Firstly, static defenses totally kills Reapers. One Spine Crawler, Photon Cannon or Bunker built near mineral line ends up this atack and forces me to go to mid-game transition (most likely to bio, having 3 barracks built already). However, static defenses are rarely seen in pro-player matches, because they consume resources and are - well - static, so immobile.

Early static defense happens rarely at the pro level because it's only good for shutting down over-committed rushes, but it's so good at that job that people don't do those rushes, because they know their opponent will just scout it and shut it down.
The key point is that when you build two extra rax (300 minerals) and three extra reapers (150 minerals and 150 gas), to execute a rush which requires a lot of attention and actions, you turn static defense into a good investment instead of a bad one for your opponent.
For comparison:

*

*a photon cannon only sets them back 150 minerals (plus another 150 if they had to rush their forge out), and only takes about four actions to start and then builds itself, while the player spends the rest of their APM on something that will exploit the fact that your factory, starport, and other upgrades and tech are significantly delayed.

*a shield battery costs 150 (and doesn't require changing your build to get a forge sooner than you might've otherwise), and reaper wall at the jump-up ledge into the main, on most maps, is free (you were going to build those buildings anyway, unless the jump up ledge is unusually wide). Meanwhile, does four reapers win against a stalker or adept patiently waiting for you by a shield battery placed in the right position?

*Terran pays 25 minerals for a bunker (since they get back 75 of the 100 when they salvage the bunker later), and if you had two SCVs building two barracks for 150 each, they can afford to lose the mining time of one or two SCVs building one or two bunkers for 100 (with a 75 rebate) each. They can also just build their CC in the safety of the main base and not float it to the natural until they're ready, so maybe they don't even need to bunker the second mineral line, might just be able to wait until they've got the units out to shut it down.

*Zerg is already building multiple queens as part of their build, and if your reapers get there before the queens pop then first thing a zerg pro thinks is probably "oh nice, my opponent set themselves back significantly to pull this off" so they can afford to just pull back and lose a little bit of mining time, or sacrifice those first four lings (only 100 minerals), or whatever losses you can force out of a great player until the queens come out.
Bear in mind, at the highest levels your opponent probably saw it coming, or at least saw something aggressive coming. Protoss scouts with their 16th probe or so. Terran does something similarly timed. Zerg sends their first overlord to peak into your main and natural and then pulls it back just enough to not lose it but to still see stuff coming, and might even risk sacrificing that overlord if what you're doing smells really weird (except in your case their gamble would pay off because you don't yet have something to shoot up, so if they take that risk they win a free view of your base). Basically high-level players time their scouting specifically to discriminate if you're doing something they need early defense against - if they see no factory or multiple rax, they immediately know you're up to something that probably justifies a small static defense investment.

A: Actually, when Reapers were stronger than in LotV, it worked in pro level 1v1. This kind of build, which was present in WoL, was called 컵라면 사신 (cupramyeon sashin, lit. "instant noodle Reaper cheese") in Korea. Since Reapers were specialized in harassment, instant noodle Reaper cheese could either award the Terran a premature victory, and even if they fail, bruh, they have MULEs, which could be used to recover the loss and make the next encounter even, or worse, favor the Terran.
Obviously this was not fair, and instead of directly nerfing Reapers, Blizzard instead decided to delay such Terran cheeses by requiring them to build a Supply Depot prior to a Barracks. And you see the present Reapers, who could easily be thwarted off if you have enemy intel.


text:
Q: Is this the correct behavior of a ObservableCollection and Linq? Hi I just ran into a sync problem, and have replicated it in this small example.
class MyClass
    {
        public int Number { get; set; }
    }

static void Main(string[] args)
        {
            var list = new ObservableCollection<MyClass>
                           {
                               new MyClass() {Number = 1},
                               new MyClass() {Number = 2},
                               new MyClass() {Number = 3}
                           };

            var count = from i in list where i.Number == 1 select i;
            Console.WriteLine("Found {0}", count.Count());

            list[2].Number = 1;
            Console.WriteLine("Found {0}", count.Count());
        }

This will output
Found 1
Found 2

This is not what I expected, would have guessed it would return 1 both times.
It there anyway to avoid this action and still use a observable collection?
I'm trying to implement a method to reorder, but this makes it hard to select the correct item.
UPDATE
An easy solution would of cource be to modify it like this
int found = count.Count();
            Console.WriteLine("Found {0}", found);

            list[2].Number = 1;
            Console.WriteLine("Found {0}", found);

A: This is due to the lazy evaluation of your LINQ query and has nothing to do with the ObservableCollection. If you change your LINQ query to the following line:
(from i in list where i.Number == 1 select i).ToList();

you will see the behavior you expect.
The ToList() addition makes sure your LINQ query is evaluated at that moment. Otherwise, it is evaluated only when necessary. Because you call Count() twice, the query is evaluated twice but on different data.

A: You encountered one of the pitfalls of LINQ. The variable count in your example isn't the result of a query, it is the query. Every time you change something in the underlying collection, the change will be reflected in subsequent calls.


text:
Q: Mean calculation within bins I am trying to calculate mean within each bin.
Everything works okay, but I get 'nan' mean value in the first bin. I suppose it is not correct. Can you help me to find a mistake?
Here is my code:
data = np.array([-90,-1,2,3,5,6,8,10,121])

bin_s = np.array([-np.inf, 1, 3, 5, 8, 9, +np.inf])

dig = np.digitize(data, bin_s)
sol = np.bincount(dig, data) / np.bincount(dig)
sol

Code and result

A: Numpy's bincount returns the populations of individual bins. However, if some bins are empty, the corresponding value will be zero, thus the division by np.bincount(dig) will fail. A quick fix would be
 sol = np.bincount(dig, data) / np.array([max(1, v) for v in np.bincount(dig)])

i.e., to divide by 1 instead of 0 for such bins since in this case we know that the bin is empty and thus the corresponding value in np.bincount(dig, data) is also zero (however, this would depend on how you want to interpret the mean of an empty bin). This will give:
[  0.  -45.5   2.    3.    5.5   8.   65.5]

The first element here is not phony, but it corresponds to the zero bin index which would aggregate data smaller than min(bin_s). However, since this number is in your case -np.inf, there are no such data. But it might happen that even some intermediary bins turn out to be empty. For example if you take as the input data:
data = np.array([-90,-1,2,3,10,121])

Then np.bincount returns [0 2 1 1 0 0 2], so one needs to handle the other zeros as well, not only disregard the first element...
Also, you might consider binned_statistic provided by scipy which does this directly:
import numpy as np
from scipy.stats import binned_statistic as bstat

data = np.array([-90,-1,2,3,5,6,8,10,121])

stat = bstat(data, data, statistic = 'mean', bins = [-np.inf, 1, 3, 5, 8, 9, +np.inf])
print(stat[0])

A: The first bin is phony, disregard it:
np.bincount(dig, data)[1:] / np.bincount(dig)[1:]
#array([-45.5,   2. ,   3. ,   5.5,   8. ,  65.5])


text:
Q: How to convert an xml format to similar mongodb structure? I have the following xml
<Employees>
    <employee>
        <personal-details>
            <last-name>A</last-name>
            <first-name>Mahendran</first-name>
        </personal-details>
    </employee>
</Employees>

To insert the same into mongodb I used it in the following way:
employees = {"employee" :
    { "personal-details" :
        { "last-name" : "A",
          "first-name" : "Mahendran",
        }
    }
}

db.employees.insert(employees)

Question:
Now I have a changed xml format.
<Employees>
    <employee id="I-1111">
        <personal-details>
            <last-name>A</last-name>
            <first-name>Mahendran</first-name>
        </personal-details>
    </employee>
</Employees>

NOTE: I have added "id" attribute to employee.
How to modify the existing mongo structure to incorporate this.

A: See http://docs.mongodb.org/manual/core/write-operations/#update. Accordingly you can do this.
db.employees.update(
    { last-name: "A" },
    { $set: { id: "I-1111" }
);

Note that it will only update one document unless you use multi true.


text:
Q: Regex - Find which group is not matching the pattern I'm quite new to regex and I'm trying to validate a file path to see if it matches my regex pattern, which represents the correct form of the file path.
This is the regex pattern:
string expression = (^P:)\\([A-Z]{3})\\(\d{6})\\(Revit)\\(Model)

And I'm matching it in my C# program simply by
Match match = Regex.Match(toCheck, expression);

Now this works with the correct folder path, such as P:\SYD\121174\Revit\Model.
But, if I input a path that is almost right, such as P:\SYD\121174\ Rhino \Model (difference in bold) I was hoping to get from the match object which group is wrong, so I could report it back to the user.
I tried something like this:
            foreach (Group group in match.Groups)
            {
                if (!group.Success)
                {
                    failingGroup = group.Index;
                }
            }

but then I understood that if the string isn't matching, then I don't get any group back.
Is there a way to get which group is not matching?

A: Your regex would become super long:
(?:(^P:)|[^\\]+)\\(?:([A-Z]{3})|[^\\]+)\\(?:(\d{6})|[^\\]+)\\(?:(Revit)|[^\\]+)\\(?:(Model)|[^\\]+)

Here is a more prettified version:
(?:(^P:)|[^\\]+)\\
(?:([A-Z]{3})|[^\\]+)\\
(?:(\d{6})|[^\\]+)\\
(?:(Revit)|[^\\]+)\\
(?:(Model)|[^\\]+)

Essentially, for each group, I added an alternative to match [^\\]+. This will match anything else other than a slash. So if the path says Revi rather than Revit, group 4 ((Revit)) would not match, but the second alternative, which is not in a group ([^\\]+), would. Now, the regex will still match even if one group failed, and you will have to check every group's Success to know if the path is the one you wanted:
var failedGroups = match.Groups.Cast<Group>().Where(x => !x.Success).ToList();
var success = !failedGroups.Any();

I personally don't like such a long regex, I would use a super permissive regex like this:
^([^\\]+)(?:\\([^\\]+)){4}

And check each group and capture in turn:
if (match.Groups[1].Value != "P:") {
    // Group 1 in your original regex is wrong!
}
if (!Regex.IsMatch(match.Groups[2].Captures[0].Value, "^[A-Z]{3}$")) {
    // Group 2 in your original regex is wrong
}
if (!Regex.IsMatch(match.Groups[2].Captures[1].Value, @"^\d{3}$")) {
    // Group 3 in your original regex is wrong
}
if (match.Groups[2].Captures[2].Value != "Revit") {
    // Group 4 in your original regex is wrong
}
if (match.Groups[2].Captures[3].Value != "Model") {
    // Group 5 in your original regex is wrong
}

EDIT: You seem to want to allow a path with fewer than 5 components. You can just make the {4} quantifier into a {0,4} (even more permissive now), and check if group 2 has 4 captures:
^([^\\]+)(?:\\([^\\]+)){0,4}

if (match.Groups[2].Captures.Count == 4) {
    if (match.Groups[1].Value != "P:") {
        // Group 1 in your original regex is wrong!
    }
    if (!Regex.IsMatch(match.Groups[2].Captures[0].Value, "^[A-Z]{3}$")) {
        // Group 2 in your original regex is wrong
    }
    if (!Regex.IsMatch(match.Groups[2].Captures[1].Value, @"^\d{3}$")) {
        // Group 3 in your original regex is wrong
    }
    if (match.Groups[2].Captures[2].Value != "Revit") {
        // Group 4 in your original regex is wrong
    }
    if (match.Groups[2].Captures[3].Value != "Model") {
        // Group 5 in your original regex is wrong
    }
} else {
    // the path is shorter than expected
}

A: I am familiar with regex groups, but it will be nice to demonstrate such validation  with almost only C#. You can use this function to detect the problem after you received no match from your full regex pattern.
Please see comments inside the code:
private string FindPathProblem(string path)
{
    // check path start with p:\
    if (!path.StartsWith(@"P:\"))
    {
        return "description of the problem in group1";
    }

    // issolate [A-Z]{3}
    string group2 = path.Substring(3, path.IndexOf("\\", 3

    // check the length is 3
    if (group2.Length != 3)
    {
        return "description of the problem in group2";
    }

    // check that all 3 characters are english chars
    Regex r = new Regex("[A-Z]{3}");
    if (!r.IsMatch(group2))
    {
        return "description of the problem in group2";
    }

    // isolate 6 characters (group 3)
    string group3 = path.Substring(7, path.IndexOf("\\", 7

    // check the legth is 6
    if (group3.Length != 6)
    {
        return "description of the problem in group3";
    }

    // check all characters are numbers
    int param = 0;
    var isnumeric = Int32.TryParse(group3,out param);
    if (isnumeric == false)
    {
        return "description of the problem in group3";
    }

    // check for the existance of Revit
    string group4 = path.Substring(14, 5);
    if (group4 != "Revit")
    {
        return "description of the problem in group4";
    }

    // check for the existance of Model
    string group5 = path.Substring(20, 5);
    if (group5 != "Model")
    {
        return "description of the problem in group4";
    }
    return "OK";
}


text:
Q: Null value error, I am using Django rest framework and when I want to get enrolled data inside login response it gives me null instate of the values I want to get enrolled courses for individual student with login I put enrolled model inside the login response put it will give me null instate of courses here is me output and code
output:
{
    "token": "4b6d75942dbbbcc484fb6c556b1ce6ebf2c73142",
    "user": {
        "id": 14,
        "username": "enrolltestt",
        "mobile_no": "07746505150",
        "is_student": true,
        "device_id": ""
    },
    "is_student": true,
    "enrolled": [
        {
            "course": null,
            "student": null,
            "is_active": false
        }
    ]

here is my views.py
class CustomAuthToken(ObtainAuthToken):
    def post(self,request,*args,**kwargs):
        serializer=self.serializer_class(data=request.data, context={'request':request})
        serializer.is_valid(raise_exception=True)
        user=serializer.validated_data['user']
        token,created=Token.objects.get_or_create(user=user)
        enrolled=StudentCourseEnrollSerializer(context=self.get_serializer_context()).data,
        return Response({
            'token':token.key,
            'user':UserSerializer(user, context=self.get_serializer_context()).data,
            'is_student':user.is_student,
            'enrolled':enrolled
        })

models.py
enteclass User(AbstractUser):
is_student=models.BooleanField(default=False)
is_teacher=models.BooleanField(default=False)
mobile_no=models.CharField(max_length=200)
device_id=models.CharField(max_length=200,blank=True)

USERNAME_FIELD = 'username'

def __str__(self):
    return self.username

class Meta:
    verbose_name_plural="1.User"

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None,
created=False,**kwargs):
if created:
    Token.objects.create(user=instance)

#student course enrollment
class StudentCourseEnrollment(models.Model):
course=models.ForeignKey(Course,on_delete=models.CASCADE,related_name='enrolled_courses')
student=models.ForeignKey(User,on_delete=models.CASCADE,related_name='enrolled_student')
is_active=models.BooleanField(default=False)
enrolled_time=models.DateTimeField(auto_now_add=True)r code here

can someone help me


text:
Q: Keep original page number on autorefresh I am working on a spreadsheet which is also accessible through a browser via Excel Web Access. When the Excel spreadsheet is edited via the Excel application, I want the browser window to refresh and show the changes made.
It is currently refreshing from the script below but there is an issue. If the browser window is set to page 9 of the spreadsheet for example, and the Excel spreadsheet is modified to make a change to page 14, when the browser refreshes Excel Web Access it changes the page to 14. I want it to stay on page 9, but if I click on to page 14 I can see the changes. Does this make sense? Any pointers in the right direction would be much appreciated.
<script type="text/javascript" language="javascript">
var reloadTimer = null;
var sURL = unescape(window.location.pathname);

function setReloadTime(secs)
{ if (arguments.length == 1)
   { if (reloadTimer) clearTimeout(reloadTimer);
       reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat(secs)*1000));
   }
   else
   { reloadTimer = null;
     location.reload(true);
     window.location.replace( sURL );
   }
}

setReloadTime(300);
</script>


text:
Q: How to change the 'Sheet1' name to a custom spreadsheet name like "AAA BBB"? I'm very new to vba that's why I rely so much on internet search. What I'm trying to do now is I want to make an Advanced Filter using a ComboBox where a user will type a keyword and it will be automatically be displayed on the ListBox (Extracting data as the user type).
Since I don't don't know to do it, I searched for tutorials online and I found this code from https://www.razakmcr.in/2017/10/ms-excell-listbox-search-by-textbox-vba.html. <- that's what I'm trying to do exactly. But I noticed that his sheet is named to default 'Sheet1'. I have a sheet named "DATA STOCK" and I've tried to change Sheet1 to "DATA STOCK" but I got an error. I want to try his code because it may be a huge help.
Here is his code:
Private Sub TextBox1_Change()

Me.TextBox1.Text = StrConv(Me.TextBox1.Text, vbProperCase)
Dim i As Long
Me.ListBox1.Clear
On Error Resume Next

For i = 1 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A"))
    a = Len(Me.TextBox1.Text)
    If Left(Sheet1.Cells(i, 1).Text, a) = Left(Me.TextBox1.Text, a) Then
        Me.ListBox1.AddItem Sheet1.Cells(i, 1).Value
        Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value
    End If
Next i
End Sub

What I did is for example: For i = 1 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A")) to For i = 1 To Application.WorksheetFunction.CountA(("DATA STOCK").Range("A:A"))
Anyway, here is my code for the WHOLE ComboBox that serves as an Advanced Filter:
Private Sub cmbSearch_Change()

    Me.cmbSearch.Text = StrConv(Me.cmbSearch.Text, vbProperCase)
    Dim i As Long
    Me.listHeader.Clear
    On Error Resume Next
    For i = 1 To x
    a = Len(Me.cmbSearch.Text)
    If Left("DATA STOCK").Cells(i, 1).Text, a) = Left(Me.cmbSearch.Text, a) Then
    Me.cmbSearch.AddItem Sheet1.Cells(i, 1).Value
    Me.cmbSearch.List(listHeader.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value
    End If
    Next i

    'THE FF CODE WILL DISPLAY THE VALUE ON THE LISTBOX FROM THE COMBOBOX SELECTION
    x = Sheets("DATA STOCK").Range("A" & Rows.Count).End(xlUp).Row
        For y = 2 To x
            If Sheets("DATA STOCK").Cells(y, 1).Text = cmbSearch.Value Then
                cmbSchema.Text = Sheets("DATA STOCK").Cells(y, 1)
                cmbEnvironment.Text = Sheets("DATA STOCK").Cells(y, 2)
                cmbHost.Text = Sheets("DATA STOCK").Cells(y, 3)
                cmbIP.Text = Sheets("DATA STOCK").Cells(y, 4)
                cmbAccessible.Text = Sheets("DATA STOCK").Cells(y, 5)
                cmbLast.Text = Sheets("DATA STOCK").Cells(y, 6)
                cmbConfirmation.Text = Sheets("DATA STOCK").Cells(y, 7)
                cmbProjects.Text = Sheets("DATA STOCK").Cells(y, 8)

                UserForm1.listHeader.RowSource = "A" + CStr(y) + ": H" + CStr(y)
                Exit For
            End If
        Next y

End Sub

Can you help me how to create an Advanced Filter?

A: Sheet1 in this example is the code name of the sheet.
Your DATA STOCK sheet also has a code name, and most likely it's not DATA STOCK. Look it up in the project tree and use instead of Sheet1.

Alternatively, use Worksheets("DATA STOCK") in place of Sheet1, but then your code will rely on users not renaming the sheet.


text:
Q: Compactness of composition of operators Let $V$ be a Hilbert space with inner product $(\cdot, \cdot)_V$, and let $L:V \to V^*$ be defined by
$$\langle Lv_1,v_2 \rangle = (v_1, v_2)_V$$
i.e., $L$ generates the cannonical given inner product on $V$.
Let $T:V \to V$ be a (possibly nonlinear) continuous operator.
If $T$ is compact, so is $L \circ T$.
Is it possible for $L \circ T$ be compact without $T$ compact? Does anyone know any theorems guaranteeing such a compactness without assuming compactness for $T$?


text:
Q: Access value of object array Angular 2 In my Angular 2 application, I have a calculation which receives data from different forms through a service.
I need to access to a value in an object array.
data: [{ "income": 12000 },
       { "income": { "name": "per Year", "value": 1/12 } },
       { "income": 120 },
       { "income": { "name": "per Month", "value": 1 } }] ]`

If I want to access to the income=12000 I have to use data[0].income.
How can I access to the "value":1/12?

A: array.find( item => item.income == 1200)
If you want to filter all items with income = 1200 than replace find() with filter()


text:
Q: How do I select objects I click on in ArcGIS (.Net) I have a MapView in my xaml code, which contains several GraphicsLayer. The first layer is the actual map, and the second is small SimpleMarkerSymbol representing locations.
What do I do to be able to click on them?
I use the trigger MapViewTapped which gives me MapViewInputEventArgs with coordinates of my click, and I have my MapView. According to the developer guide, I should be able to do the following:
var objectIDs = await lyr.HitTestAsync(MyMapView, myClick.Position);

lyr.SelectGraphics;

However, nothing is found. Note: the link uses FeatureLayer instead of GraphicsLayer.
Unlike FeatureLayer, GraphicsLayer does not have a setter in its SelectGraphics property.
So - how do I click on an marker and have it returned?

A: I found a solution, which works for me:
var layer = Map.Layers[MyLayer] as GraphicsLayer;
var selectedId = await layer.HitTestAsync(mapView, eventargs.Position);
selectedId.IsSelected = true; //Nothing found sets selectedId = null
var unitsFound = layer.SelectedGraphics.ToList();

This gives a list of all units found at the point you clicked. But it only gives you the coordinates.
But match this with the list of units added to your map, and you can find potential units you clicked:
var foundUnits = new List<MyUnitClass>();

foreach (var unit in unitsFound)
{
    var unitCoord = (MapPoint) unit.Geometry;
    foundUnits.Add(layer.MyAddedUnits.FirstOrDefault(
        x => x.Information.Coordinate.Latitude == unitCoord.Y &&
             x.Information.Coordinate.Longitude == unitCoord.X));
}

return foundUnits;

It is also explained on their website to some extent.


text:
Q: Pandas: convert all columns in dataframe to string I have dataframe
 0     1     2
12     34   23
10     12    0

Desire output
upd_string
12, 34, 23
10, 12, 0

I try
df_upd = pd.DataFrame()
df_upd['upd_string'] = df[df.columns.values.tolist()].apply(str)

But it returns
ValueError: no results

A: First cast to strings if numeric and then apply join:
df.astype(str).apply(', '.join, axis=1)

for new DataFrame:
df_upd = pd.DataFrame({'upd_string': df.astype(str).apply(', '.join, axis=1)})
print (df_upd)
   upd_string
0  12, 34, 23
1   10, 12, 0


text:
Q: Vagrant disable Guest Additions I would like to disable VirtualBox Guest Additions. I do not use them for folder syncing, etc. and for the box I am working on (e.g., centos/7), they fail to build anyway. Is there some way to tell vagrant not to try to install them at vagrant up?

A: In your Vagrantfile, add the following param
Vagrant.configure("2") do |config|
    ....
    config.vbguest.auto_update = false
    ....
end

A: Users might not have the vagrant-vbguest plugin, and you could wrap its use in a conditional to avoid confusion.
Vagrant.configure("2") do |config|
  ....
  if Vagrant.has_plugin?("vagrant-vbguest")
    config.vbguest.auto_update = false
  end
  ....
end


text:
Q: AWS auto scaling group - codedeploy should run after userdata script in ec2 instance is completed I have configured an auto scaling group using launch configuration with userdata script to install nodejs while launching the instance. And codedeploy application is configured for the auto scaling group to deploy an app from s3 bucket.
when a new instance is launched by the autoscaling group codedeploy and userdata seems to be run in parallel and deployment is failing as nodejs is not available.
is there a way to make sure that codedeploy is run only after userdata is completed?
can we configure multiple lifecycle hooks? i have seen a lifecycle hook is created for codedeploy. can we modify this to run only after userdata is completed?


text:
Q: how to call an event from a form using a control (button, for example)? Is it possible? I need to call the Form1_FormClosing here:
ContextMenu trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Close", delegate {
    Form1_FormClosing(????)
});

I need it because I'm using the CancelEventArgs from _FormClosing event:
private void Form1_FormClosing(object sender, CancelEventArgs e)
{
    if (th != null && th.ThreadState == System.Threading.ThreadState.Running)
    {
        if (MessageBox.Show("the process is running, you want stop it?", "app", MessageBoxButtons.OKCancel) == DialogResult.OK)
        {
            AbortProccess();                     }
        else
        {
            e.Cancel = true;
        }
    }
}

I hope this is clear,thanks in advance.

A: There are a few things you could do.
First, you could just close the form using myForm.Close() as this will indirectly call the FormClosing event. Also, you could move everything within the FormClosing event into a separate method instead of in the event itself. You can then call that method from the event and from your MenuItem. If you don't want to do either of those, you could try using this as the delegate:
//CancelEventArgs can also take a boolean which dictates if
//it should be cancelled
Form1_FormClosing(this, new CancelEventArgs());

A: ContextMenu trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Close", delegate {
     this.Close();
});

A: This is technically possible, just call the OnFormClosing() method.  But that doesn't actually close the form, it should only ever run when the form actually closes.  Pretending that the form is closing when it is not actually closing is going to lead to disappointment.
So just call the Close() method instead.


text:
Q: WPF DataGrid - Change value row by row in "real time" I'm creating this DataGrid:
DataTable _dt = new DataTable("MyDataTable");
_dt.Columns.Add("ID", typeof(int));
_dt.Columns.Add("File", typeof(string));
_dt.Columns.Add("Folder", typeof(string));
_dt.Columns.Add("Status", typeof(string));
_dt.Columns["ID"].AutoIncrement = true;
_dt.Columns["ID"].AutoIncrementSeed = 1;
_dt.Columns["ID"].AutoIncrementStep = 1;

FilesGridView.SelectionMode = DataGridSelectionMode.Extended;

FilesGridView.ItemsSource = _dt.DefaultView;

and then populating it with a list of file paths.
When I hit the Process button, I want to loop through all the rows in the grid and change the value of the Status column, row by row.
So I've written this:
private void ProcessButton_Click(object sender, RoutedEventArgs e)
{
    foreach (DataRowView row in FilesGridView.ItemsSource)
    {
        row["Status"] = "Processing...";
        System.Threading.Thread.Sleep(2000);    //letting 2 sec pass as a test
    }
}

but what happens is that it starts calculating and after 2 seconds * the iterations in the loop are elapsed, the table changes all at once.
What I was looking for was that entering the foreach loop, it was changing the displayed value first row, then waiting 2 sec and changing the displayed value of the second row, and so on.
What am I missing? How do I achieve that?

A: If you need to display the progress on updates while the loop is running, you just need a bit of asynchronous programming.
Just make your event handler method asynchronous and run the loop inside a Task, like this:
private async void Process_OnClick(object sender, RoutedEventArgs e) {
    await Task.Run(async () => {
        foreach (DataRowView row in this.FilesGridView.ItemsSource) {
            row["Status"] = "Processing...";
            await Task.Delay(2000);
        }
    });
}

I tested the code in this project. Check the MainWindow. Add some items during execution in the DataGrid and then press the button.


text:
Q: Store any template of class in another class If you want to store any templated class in another class, is there a way of doing that without extending from a non-templated base class. Example
class definition:
class BaseA
{
    ...
}

class Storage
{
public:
    baseA* toStore;//pointer to baseA
}

template <typename... Type>
class ExtendedA : public baseA
{
    ...
}

using class:
Storage a;
one.toStore = ExtendedA<int, char, etc...>();

This is the only way that I can think of storing a templated type in a non-templated class. Are there other ways to do this?

A: The only way to store and use a templated type, where the template is unknown, is to set up the classes in the same way as the example from the question.
Have a non-templated base class.
Extend that base class, and template the extension.
A pointer to the base class can now be stored, and used, even if it happens to be the templated extended class.


text:
Q: Is there a way to use a TestNG DataProvider outside of one's Test classes? A TestNG test class can become pretty bloated if every test uses its own DataProvider. Is there anyway to import these from another Java class (ie: one where constants are already declared)? I could not find any existing documentation.

A: You can create Data Providers in an another class (not in the same class having test methods) like below and refer it using dataProviderClass in Test annotation
import org.testng.annotations.DataProvider;

public class DataProviderClass  { //Data Provider class

    @DataProvider(name = "data-provider")
    public static Object[][] dataProviderMethod() {
      return new Object[][] { { "1" }, { "2" } };
    }
}

TestClass.java
import org.testng.annotations.Test;

public class TestClass {

     @Test(dataProvider = "data-provider", dataProviderClass = DataProviderClass.class)
     public void testMethod(String data) {
        System.out.println("Data is: " + data);
     }
}


text:
Q: insertion of foreign key asp.net mvc i have 3 models
public class UsersModel
    {
        [Key]
        public int UserId { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
        public string Name { get; set; }

        //20150090
        public int? student_ID { get; set; }

        [Display(Name = "transcript")]
        public string transcript { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
        public string Department { get; set; }

        [Required]
        [Display(Name = "Phone")]
        [DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
        [Range(999999999, 9999999999)]
        public int Phone { get; set; }

        public int type { get; set; }

    }

student
 public class StudentsModel
    {
        [Key]
        [Display(Name ="ID")]
        public int StudentID { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]//20150090
        public string student_ID { get; set; }

        [Required]
        [Display(Name = "Skills")]
        public string Skills { get; set; }

        [Required]
        [Display(Name = "Gpa")]
        [Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
        public float Gpa { get; set; }

        [Required]
        [Display(Name = "Leader")]
        public string Leader { get; set; }

        [Required]
        [Display(Name = "transcript")]
        public string transcript { get; set; }

        [ForeignKey("UserId")]
        public int UserId;
        public UsersModel Users { get; set; }

        [ForeignKey("IdeaId")]
        public int? IdeaId;
        public IdeaModel Idea { get; set; }

    }

Idea
public class IdeaModel
    {
        [Required]
        [Key]
        public int IdeaId { get; set; }

        [Required]
        public string IdeaName { get; set; }

        [Required]
        public string IdeaDescription { get; set; }

        [Required]
        public string tools { get; set; }

        public int? SetWith { get; set; }

        [Required]
        public int Prof1 { get; set; }

        public int Prof2 { get; set; }

        public int Prof3 { get; set; }
    }

when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
        {
            if (ModelState.IsValid)
            {
                var user= db.Users.Add(reg.users);
                var idea = db.Idea.Add(reg.idea);
                var stu = db.Students.Add(reg.students[0]);

                db.SaveChanges();

                return View("RegisterLeaderPost");
                //return Registerfinish();

            }
}

this model have the three models
 public class regall
    {
        public List<StudentsModel> students { get; set; }
        public UsersModel users { get; set; }
        public IdeaModel idea { get; set; }
    }

A: You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;


text:
Q: c++ thread function clarification #include <iostream>
#include <iostream>

static const int num_threads = 5000;

void thread_fun() {
   ...
}

int main() {
    std::thread t[num_threads];

    //Launch threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(thread_fun);
    }

    //Join threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}

When the 5000 threads start to run and execute void thread_fun(), how will the thread_fun() be handled?

*

*Will there only be one copy of thread_fun() in the stack of the main program where 5000 threads access it?

*Will 5000 copies of thread_fun() be created on the stack of the main program and each thread will have access to its own copy of thread_fun()?

*Will thread_fun() be loaded into each of the 5000 threads' own stack and not in the main program stack?
I'm starting to learn c++ threads and was wondering on how this situation is handled.

A: Every thread has it's own stack and every time a thread calls a function, all the local variables (called  from the inside of stack) and states will be separately stored inside of thread stack.

All the global and dynamically allocated variables are stored in separate sections  of process memory.Note: Never call it program memory,since the memory is created when a program becomes a process, I mean when a program starts to run only then is this memory structure is created(See Image).
Now three questions may arise:
1) What if I call a global variable from the Thread ?
The answer to this is that all the global data is stored inside of the "Initialized Section" of the program memory.(See Image)
2) What if I dynamically allocate some data ?
The answer to this is that almost all the memory which is dynamically allocated (using malloc , new etc.) is stored inside of "heap" section of the program memory (See Image).This heap section can grow dynamically as it's not fix that how much memory will a program allocate during it's runtime. See the Image. Here our heap can go dynamically upwards.(Note:In some diagrams heap may be shown as growing dynamically downwards but it  doesn't matter).
3) How is data stored in stack of Thread and is it dynamically allocated ?
Let's consider a normal function call. As a program calls a function,  all the local variables it uses is stored inside of the "stack" portion of the process memory(See Image). This stack grows dynamically! Yes it does , the reason being that a function may execute some recursive calls and it's independent on our program/input how many recursive calls will be executed.
Similar procedure is followed for the threads. As a thread is created, some part of the stack is reserved for the thread in form of "thread stack" in process memory(see Image).
Now let's answer your questions:
Ans 1) No.Actually the way you asked he question is wrong. There won't be   "one copy of thread_fun() in the stack of the main program". All the code of thread_fun() will be stored inside of "text" section of the process memory but will be called 5000 times. And every time it is called by a distinct thread, a new thread stack is created where all the values of the local variables and states are stored.
Ans 2) Read Ans 1
Ans 3) Read Ans 2 :P
Please try to memorize and learn the stuff in Image and read books like Linux Programming Interface and http://pages.cs.wisc.edu/~remzi/OSTEP/ to make your concepts stronger. Hope that helps :)
Image is taken from the book Linux Programming Interface.

A: First of all, C++ threads are very thin (too thin in my own opinion) layer on OS threads - pthreads for Posix systems, or Windows threads for Windows. The question is not really about C++ threads, but about threads in general - and actually hardware architecture in general.

*

*Will there only be one copy of thread_fun() in the stack of the main program where 5000 threads access it?

This depends on what you mean by 'stack'. If you are talking about application stack memory, than the question does not make sense. Functions are not allocated on stack. Functions are code, and code actually can not be allocated this way at all. However, if by 'stack' you mean 'stack trace', than yes, 5000 threads will produce 5000 stack traces (when looked into with routine like pstack) and each of those 5000 stack traces will have thread_fun in it.

*Will 5000 copies of thread_fun() be created on the stack of the main program and each thread will have access to its own copy of thread_fun()?

See above. Code will never be allocated on stack. There is only one instance of thread_fun CODE. There might be multiple instances of different data points manipulated by thread_fun.

*Will thread_fun() be loaded into each of the 5000 threads' own stack and not in the main program stack?

I do not understand this question.

A: Short answer to all those questions is no.   Code is not stored on the stack.  There is only one copy of thread_fun, it exists in a code segment.  The OS will allocate internal data structures it will use to schedule the threads on the cpu (a stack per thread, thread local storage, storage for the registers and instruction pointer, etc).
What you have the the stack of main() is the array of std::thread type.

A: As you suspect, there will be one copy of thread_fun which will be executed by concurrent threads. The normal way to parameterise a thread function is to use a thread function object (such as the return type from std::bind).
As for 5000 threads... you'll be lucky! 200 is pushing the limits on most systems. If you need that much concurrency you'll want to research the "asynchronous programming model".


text:
Q: Determining order of accuracy of a method
Consider IVP $y'(x) = - \lambda y(x)$ and $y(0) = 1 $ , $\lambda  > 0$
and the numerical method  $$ y_n = y_{n-2} + \frac{1}{3} h [
 f(x_n,y_n) + 4 f(x_{n-1},y_{n-1}) + f(x_{n-2},y_{n-2}) ]$$
$$y_0 = 1$$
Find the accuracy of this method. For small $h$, discuss stability of
the method. As $h \to 0$, to what solution does the numerical mthod
converge?

Attempt
Let $y(t)$ be the exact solution ${\bf restricted} $ to the grid $(y(t_n) = Y_n$) and upon subtituting into the method, we obtain
$$ T_k = Y_n - Y_{n-2} - \frac{1}{3} h [
 f(x_n,Y_n) + 4 f(x_{n-1},Y_{n-1}) + f(x_{n-2},Y_{n-2}) ]$$
Now, we perform taylor expansion as follows
$$ Y_{n-2} = Y_n -2h Y'_n + \frac{ (2h)^2 }{2} Y''_n +...$$
$$ f(x_{n-1},Y_{n-1} ) = Y'_{n-1} = Y'_n - h Y''_n + \frac{h^2}{2} Y'''_n + ... $$
$$ Y_{n-2}' = Y'_n - 2h Y''_n + 2 h^2 Y'''_n + ... $$
So, upon substitution into equation above we obtain
$$ T_k = \frac{h}{3} Y'_n - \frac{4 h^3 }{3} Y_n'' + O(h^4) $$
method is consisten as $T_k \to 0$, but I only get first-order accuracy. Is this correct? Im suspicious as implicit methods are usually higher order schemes. For stability, we have
$$y_n = y_{n-2} - \frac{h}{3} \lambda [ y_n + 4 y_{n-1} + y_{n-2} ] $$
or
$$ \left( 1 + \frac{h \lambda }{3} \right) y_n = - \frac{4 h \lambda }{3} y_{n-1} - \left( \frac{\lambda h }{3} -1\right) y_{n-2} $$
Am I on the right track?


text:
Q: Python3 - loop through list with mulitple dictionaries sorry I am rather a beginner when it comes to python.
I have a list like this:
"list": [
    {
      "id": 12345,
      "name": "test"
    },
    {
      "id": 12453,
      "value": "value1",
      "field": "test",
    }
    ]

When looping through several of such lists I want it to print the "name" key from the upper dictionary but only if the condition is met that "value": "value1", is present  but this is in a different dictionary.
I tried with stuff like: if 'value' in event.keys():
but I cant manage to only print this "name" key if the other condition is met. any suggestions?

A: Below one way of doing it, it is going through all key/value of all dictionnaries so it's probably not efficient but will adapt to several possibility.
I don't know if name can be in the list several times, the below code will keep the last occurrence if it happens.
I made it a function so that you can use it easily on several similar lists. It returns None if the criteria was not met, the value of name if it was.
def get_valid_name(dict_list, target_value):
    keep_name = False
    current_name = None
    for d in dict_list:
        for key, val in d.items():
            if key == "name":
                current_name = val
            elif key == "value" and val == target_value:
                keep_name = True
    return current_name if keep_name else None

for l in [original_list]:
    result = get_valid_name(l, "value1")
    if result is not None:
        print(result)


text:
Q: How to generate access token for LinkedIn? I simple want to do "share with linkedIn" from my iOS application."

How to generate access toke before sharing on linked In, how to
  generate it ?

here is my code for posting in linked In. But its not working because I have not access token.
// For positing on linked In

    [[LISDKAPIHelper sharedInstance] apiRequest:@"https://api.linkedin.com/v1/people/~/shares?format=json" method:@"POST" body:[bodyTxtView.text dataUsingEncoding:NSUTF8StringEncoding]
                success:^(LISDKAPIResponse *response)
                 {
                     NSLog(@"success called %@", response.data);
                }
              error:^(LISDKAPIError *apiError) {
                   NSLog(@"error called %@", apiError.description);

                    dispatch_sync(dispatch_get_main_queue(), ^{
                        LISDKAPIResponse *response = [apiError errorResponse];
                                                  NSString *errorText;
                              if (response)
                              {
                                    errorText = response.data;
                               }
                               else
                               {
                                   errorText = apiError.description;
                                }
                        NSLog(@"error called %@", errorText);
                 });
          }];

A: Sample code is given in SDK (inside sample app) which was downloaded from https://developer.linkedin.com/downloads

A: you  can use this class may be help you!!
  apikey = @"75pxdmwh5ghbil";
    secretkey = @"j3iYOXotT37VhPbM";
consumer = [[OAConsumer alloc] initWithKey:apikey
                                    secret:secretkey
                                     realm:@"http://api.linkedin.com/"];

requestTokenURLString = @"https://api.linkedin.com/uas/oauth/requestToken";
accessTokenURLString = @"https://api.linkedin.com/uas/oauth/accessToken";
userLoginURLString = @"https://www.linkedin.com/uas/oauth/authorize";
linkedInCallbackURL = @"hdlinked://linkedin/oauth";

requestTokenURL = [[NSURL URLWithString:requestTokenURLString] retain];
accessTokenURL = [[NSURL URLWithString:accessTokenURLString] retain];
userLoginURL = [[NSURL URLWithString:userLoginURLString] retain];


text:
Q: Applying Domain Name to EC2 Instance I want to host a new subdomain on an Ec2 Instance(ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com) like blog.somesite.com
I have the DNS settings on a 3rd party host(like Godaddy) that look like:

site ip addr as shown above, is the value of the ec2 server e.g. xxx.xxx.xx.xx and not
ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com

If I try to do an mxtoolbox lookup on DNS for blog.myapp.com, it seems to have properly propogated the A-Record, do I need a CNAME record instead of A-Record?
If I try to access blog.myapp.com via browser, it is just a never ending connection. If I access myapp.com , it has always been working fine.
On my ec2 box, I'm running nginx, does something need to be configured on nginx too?
Sorry about the newbieness - still learning.
Thank you!

A: To start with, you should assign an elastic IP to your instance. IP addresses will change if the instance is ever stopped. With an elastic IP, you can re-associate the ip address to the instance if you need to stop it.
If you are setting up a DNS record for the apex, it needs to be an A record (Apex records is your domain with no subdomain).
For the domain blog.yourdomain.com you can set up either an A or CNAME record.
You will likely need to configure your host within nginx to respond to requests with your domain name.
You will also need to make sure port 80 is open on your security group, and system firewall if your OS has one configured.


text:
Q: Use AOT for build, JIT for serve Currently, I use AOT compilation in my whole Angular project.
However, I'd like to use JIT for any config within the serve architect. How can I achieve this?
I tried:
{
  "projects": {
    "fooProject": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "aot": true,
            "buildOptimizer": true
          },
          "configurations": {},
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "fooProject:build",
            "optimization": false,
            "sourceMap": true,
            "vendorChunk": false
          },
          "configurations": {},
        }
      }
    }
  }
}

In which case I get an error:
An unhandled exception occurred: The 'buildOptimizer' option cannot be used without 'aot'.

Apparently the AOT-related options (such as buildOptimizer) are not removed before the compilation is started.

A: You need to override the buildOptimizer and aot options in your serve object. This is because you use the browserTarget:fooProject:build. This will get the settings defined in the fooProject.build object, and -merge- these with the serve options. So the options object is not overwritten, but merged together.
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "fooProject:build",
    "optimization": false,
    "sourceMap": true,
    "vendorChunk": false,
    "buildOptimizer": false,
    "aot": false
   },
   "configurations": {},
}


text:
Q: SQL select results not appearing if a value is null I am building a complex select statement, and when one of my values (pcf_auto_key) is null it will not disipaly any values for that header entry.
select c.company_name, h.prj_number, h.description, s.status_code, h.header_notes, h.cm_udf_001, h.cm_udf_002, h.cm_udf_008, l.classification_code
from project_header h, companies c, project_status s, project_classification l
where exists
  (select company_name from companies where h.cmp_auto_key = c.cmp_auto_key)
  and exists
  (select status_code from project_status s where s.pjs_auto_key = h.pjs_auto_key)
  and exists
  (select classification_code from project_classification where h.pcf_auto_key = l.pcf_auto_key)
  and pjm_auto_key = 11
  --and pjt_auto_key = 10
  and c.cmp_auto_key = h.cmp_auto_key
  and h.pjs_auto_key = s.pjs_auto_key
  and l.pcf_auto_key = h.pcf_auto_key
  and s.status_type = 'O'

How does my select statement look? Is this an appropriate way of pulling info from other tables?
This is an oracle database, and I am using SQL Developer.

A: Assuming you want to show all the data that you can find but display the classification as blank when there is no match in that table, you can use a left outer join; which is much clearer with explicit join syntax:
select c.company_name, h.prj_number, h.description, s.status_code,  h.header_notes,
  h.cm_udf_001, h.cm_udf_002, h.cm_udf_008, l.classification_code
from project_header h
join companies c on c.cmp_auto_key = h.cmp_auto_key
join project_status s on s.pjs_auto_key = h.pjs_auto_key
left join project_classification l on l.pcf_auto_key = h.pcf_auto_key
where pjm_auto_key = 11
and s.status_type = 'O'

I've taken out the exists conditions as they just seem to be replicating the join conditions.
If you might not have matching data in any of the other tables you can make the other inner joins into outer joins in the same way, but be aware that if you outer join to project_status you will need to move the statatus_type check into the join condition as well, or Oracle will convert that back into an inner join.
Read more about the different kinds of joins.


text:
Q: How to link two or more projects in Eclipse? I am trying to develop my application in different Eclipse Java projects where each will contain a certain feature. Then I want to combine them in one complete Java project.
However, I have a problem when linking the sources.
The sub-projects can correctly refer to parent-project classes but some of the source files that are accessed by the parent projects cannot be identified in the sub-projects.
I have a workspace/ParentProject/src/main/resources/file, where in the ParentProject I am accessing with "src\main\resources\" from within Java.
However, at runtime the ChildProject throws an exception that they cannot access the file : 'file:/E:/Eclipse%20workspace/ChildProject/src/main/resources/file'
So, when using a method of the ParentProject from the ChildProject, the classpath is somewhat transfered to the ChildProject. My question is how to resolve this.
I hope I made it clear what the problem is and will be really appreciative for any help.
Regards,
Petar
Btw: It is explained there How to link project in eclipse but I still have the error, that the child project cannot access resources accessed by the parent project.

A: Right click the Parent project and click properties.  Then click Java Build Path on the left hand side.  Next click the projects tab.  Make sure the Child project is selected as a required project, if it is not Add the Child project.
You should also do this for the Parent Project.

A: Although I am not entirely sure what you need to do, it sounds to me that you are trying to create circular dependencies, which is an anti-pattern. You want to avoid creating dependencies where project a depends on project b, but project b also depends on project a. If you provide more details on your use case and what you are trying to create I will be happy to provide some guidance as to how you could structure your dependencies.
Hope this helps.


text:
Q: What is the right way to set up and running with code blocks and wxwidgets c++ library I struggled for 4 hours to set it up and after installation I am not able to get wxWidgets application started.
I get an error wx/setup.h no such file or directory found.
I have tried 10 articles from google an none of them seem to resolve the problem.
Has anyone setup the WxWidgets library with CodeBlocks successfully?

A: It's difficult to say what the problem is when you don't say when exactly do you get the error. My guess would be that you're trying to build your application without having built wxWidgets first. In this case, it's not going to work as you must build wxWidgets, which will create setup.h file in the correct location as a side effect, first. If I'm wrong and you get the error while building wxWidgets itself, please show how do you do it, exactly. In any case, make absolutely sure to not copy any setup.h files around to get rid of the error, this won't help and can result in other, much more mysterious, problems in the future.
And, to answer your rhetoric question, yes, many people have set up wxWidgets with CodeBlocks successfully. You just need to follow the build instructions instead of random articles found by the web search.


text:
Q: opneUrl react-native linking call, mailto I am trying to open a url ( "tel:061245124" or "mailto:test@test.com") and it says that i can handle url, also tried without the tel: or mail to but it crashes with a red screen.
Urls like "http://test.com" work.
What am I doing wrong?
    handlePress(url) {
    console.tron.log('Trying to access url')
    console.tron.log(url)
    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
        console.tron.log('Can\'t handle url: ' + url)
      } else {
        return Linking.openURL(url)

      }
    }).catch(err => console.error('An error occurred', err))
  }

A: The code works perfectly the problem was the iOS simulator, it needs to be tested on a device.


text:
Q: Replace the name of environment variable by it's actual value from environment in a text file I am trying to automate Active Directory installation on Windows Server 2008 using windows powershell. I created a text file with .tmpl extension and added:
[DCINSTALL]
ReplicaOrNewDomain=_ReplicaOrNewDomain__

Then I created an answer file in a text format:
[DCINSTALL]
ReplicaOrNewDomain=$env:ReplicaOrNewDomain

Now I want to be able to write a script in PowerShell which will use the template file to get the value of variable ReplicaOrNewDomain from environment and replace $env:ReplicaOrNewDomain by that value in the text file so that I can use that answer file for AD installation.

A: You have a few options to do this. One is Environment.ExpandEnvironmentVariables. This uses a %variable% syntax (instead of $env:variable), so it would be simpler if you only want to substitute environment variables:
gc input.tmpl | foreach { [Environment]::ExpandEnvironmentVariables($_) } | sc out.ini

A more complete expansion of PowerShell expressions can be achieve via ExpandString. This is more useful if you want to insert actual PowerShell expressions into the template:
gc input.tmpl | foreach { $ExecutionContext.InvokeCommand.ExpandString($_) } | sc out.ini

A third option would be something like a customized templating scheme that uses Invoke-Expression, which I implemented here.

A: You can do that with a simple replacement like this:
$f = 'C:\path\to\your.txt'
(Get-Content $f -Raw) -replace '\$env:ReplicaOrNewDomain', $env:ReplicaOrNewDomain |
  Set-Content $f

or like this:
$f = 'C:\path\to\your.txt'
(Get-Content $f -Raw).Replace('$env:ReplicaOrNewDomain', $env:ReplicaOrNewDomain) |
  Set-Content $f

Note that when using the -replace operator you need to escape the $ (because otherwise it'd have the special meaning "end of string"). When using the Replace() method you just need to use single quotes to prevent expansion of the variable in the search string.
However, why the intermediate step of replacing the template parameter _ReplicaOrNewDomain__ with a different template parameter $env:ReplicaOrNewDomain? You would make your life easier if you just kept the former and replaced that with the value of the environment variable ReplicaOrNewDomain.

A: One thing that I like to do with my template files is something like this.
[DCINSTALL]
ReplicaOrNewDomain={0}
OtherVariable={1}

Then in my code I can use the format operator -f to make the changes.
$pathtofile = "C:\temp\test.txt"
(Get-Content $pathtofile -Raw) -f $env:ReplicaOrNewDomain, "FooBar" | Set-Content $pathtofile

It can help if you have multiple things that you need to update at once. Update your file with as many place holders as you need. You can use the same one multiple times if need be in the file.
[DCINSTALL]
ReplicaOrNewDomain={0}
SimilarVariable={0}

Caveat
If your actual file is supposed to contain curly braces you need to double them up to the are escaped.

A: You can use the ExpandString function, like this:
$ExecutionContext.InvokeCommand.ExpandString($TemplVal)

(assuming $TemplVal has the template string).


text:
Q: How can i make a function for a certain textfield? This code allows the users to type in certain characters only:
let allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.";
func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
                                  replacementString string: String)
    -> Bool
{
    let set = NSCharacterSet(charactersInString: allowedChars);

    let filtered = string
        .componentsSeparatedByCharactersInSet(set)
        .joinWithSeparator("");
    return filtered != string;

}

How can i make it so that it allows a just one textfield called "txtField1"?

A: You can check whether your textField is the one currently selected in your shouldChangeCharactersInRange method because as you can see in the parameters of this method you have access to the property textField which correspond to the current textField that you are selecting, so just check this at the beginning :
if texField == txtField1 {
  // Do your stuff
 } else {
 // Do something else
}

A: Assign a value to the tag on your textfield that is unique to it (for example, 1).
txtField1.tag = 1

Then, update your method like this:
func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
                                  replacementString string: String)
    -> Bool
{
    if textField.tag == 1 {
        let set = NSCharacterSet(charactersInString: allowedChars)

        let filtered = string
            .componentsSeparatedByCharactersInSet(set)
            .joinWithSeparator("")
        return filtered != string
    }

    return true
}

You can also omit the ; in Swift.


text:
Q: Can't boot Windows 7 after installing Ubuntu I installed Ubuntu yesterday alongside Windows 7 and whenever I start my computer I don't have the option to boot Windows. When the computer starts it goes straight to Ubuntu without giving me an OS selection menu. When it goes to Ubuntu it gives me Ubuntu repair options and Ubuntu normal start option. I still have all of the Windows 7 files on my hard drive, but Windows 7 has no way to boot.

A: I had the same problem! After starting the computer the GRUB Boot loader displayed UBUNTU and 2 further entries but not Windows.
After long trying I succeeded by performing the following steps:

*

*Find out on what hard disk and what partition WINDOWS is installed.

*This you can do after opening a terminal and type at the prompt
sudo fdisk -l

(this must be done with administative rights, so you will be ask for your password).
You will now get a table of your partitions with device names like
 /dev/sda1, /dev/sda2 ..  and so on.
If you have installed windows it might have type NTFS. This means if the second entry in this table is like this:
Device...Boot.....Start...End......Blocks......Size .........Id.....System
/dev/sda1..*...2048..467118879..467116032..222,8G   ..7.....Linux
/dev/sda2 ..467118080...961144831....494026552..235,6G  7.....HPFS/NTFS/exFAT
/dev/sda3 ..1270138878...1953523711..341692417..7,6G        5.....Extended
/dev/sda5 ..1270138880...1945182207..337521664..7,6G        83....Linux

windows is installed on the second partition of the first hard disk (sda2)
(In my case both operating systems were installed on one hard disk with 2 partitions, on the first I had installed UBUNTU and Windows 7 on the second. )
Press C  for accessing the GRUB command prompt.
At the Grub-Prompt enter the following 3 commands:
Grub>   set root=(hd0,2)
Grub>   chainloader +1
Grub>   boot

Notice: In the command set root = (hd0,2)  after hd type the (zero-based) number of the hard    disk (here 0 ) and after the Comma the Number of the partion (here 2) . If your windows partition is sdb1 you must type set root=(hd1,1) if it is sdb4 type set root=(hd1,4) etc…
Now Windows should boot!
Now you might want to have Windows 7 permanently as a menu item in the GRUB Boatloader menu. This you can get as follows:
menuentry 'Windows 7' {
   set root=(hd0,2)
   chainloader +1
   boot
}

Save the file and close it.
Open a terminal and type on the command prompt:
sudo update-grub

After restarting my computer I got a further entry with windows 7 in the GRUB menu, so I can chose between Ubuntu and Windows.

A: *

*First, restart your PC or laptop.

*After restarting you see the Grub menu. Select Advanced Options for Ubuntu (with the arrow keys; press Enter to confirm).

*In the Advanced Options menu you will see an entry Recovery Menu that you need to select.

*Carefully select the grub – Update grub boot loader option.

*It will automatically add an entry for Windows 7/8/10 to the boot menu.

*To restart, press Ctrl+Alt+Del.

*The system will restart and you finally have a option to select Windows 10/8/7. Select Windows and finally you have with your Windows OS.

A: First thing first, you need to repair your WIn7 bootloader, and you can visit this page to learn how to do this. Write down on a piece of paper the required commands for fixing both boot and mbr. You'll be using those codes after getting to the Command Prompt screen.
Next you can download Boot Repair iso image as suggested in the previous answer by 'user3005324'. Choose 64 bit iso image if you have installed Ubuntu 64 bit or choose 32 bit iso image if you have Ubuntu 32 bit. I hope Win7 is the same architecture with Ubuntu, I mean you have either Win7 32 bit and Ubuntu 32 bit, or you have Win7 64 bit and Ubuntu 64 bit.
Burn the iso image, and restart your computer with the new Boot Repair CD in tray. You can write Boot Repair iso image on a USB pendrive with Unetbootin tool if you don't have a regular CD to use. Read instructions on how to use Unetbootin in Linux/Ubuntu, they are located at the middle of this page: http://unetbootin.sourceforge.net/ .
After Boot Repair cd or usb pendrive finish loading, you can press the 'Recommended Repair' option, wait to finish and after you get the message 'success' you can reboot and use Win7 and Ubuntu which will be present both in your start-up boot menu.

A: Run fdisk -l on terminal to check the windows partition.
If you found it, then type update-grub
Then reboot
And you will able be able to choose your selected OS
If permission is denied on running fdisk -l alone, add administrator privileges by entering you password after writing this code into terminal sudo fdisk -l

A: 1> boot into ubuntu live cd and do a simple os-prober in terminal
2> does it show win7?
If yes, you are safe.
Just  follow this link https://help.ubuntu.com/community/Boot-Repair
if not, you are probably screwed.Probable reason to that is windows was installed in LEGACY BIOS and u installed ubuntu in UEFI BIOS (provided your computer supports this new bios version) which means u have to reinstall everything.
But if your computer doesn't support UEFI bios, and both operatng systems are installed  in legacy bios, then the above link should work.

A: *

*Restart your PC.

*Choose  "Advanced options for Ubuntu".

*Choose recovery mode

*Update "grub"

*It will automatically load the other operating systems in the boot menu.

Precondition : you should have installed Ubuntu with "install Ubuntu along side with other operating system" option at the time of installation.


text:
Q: What's the difference between "as" and "when" in the following situation?
As I reached the middle of the bridge, I spotted someone leaning on the railing.
When I reached the middle of the bridge, I spotted someone leaning on the railing.

What's the difference between the two sentences? Or they mean exactly the same?

A: These two subordinate conjunctions have very similar meanings in this context. I believe "as" implies more of a continuous span of time, whereas "when" implies more of a precise moment in time.
"As I reached the middle of the bridge, I spotted..." implies that I began to spot the person when I was in the course of reaching the middle of the bridge.
"When I reached the middle of the bridge, I spotted..." implies that I first reached the middle of the bridge and then immediately spotted the person.


text:
Q: How could I make a react website to be completely bilingual I want my website to work with multiple languages. I have used react and node for implementing my website and it is completed for English language. And the requirement is that user can select the website language to be according to their preferences and it should be converted in that language.
I have come across with a package named as react-i18-next that is used for language conversion. But after going through the documentation, I have understood that only static texts can be converted with this package.
But the requirement is that, each and every texts which is visible on the webpage should be converted not just the static ones.


text:
Q: OData controller returns different error for local and different for remote machine In my project I use OData 3.0 and I need to handle error that comes from SQL stored procedure. Here is the controller code:
public class StartProductionBatchListController : ODataController {
    private SitContext<StartProductionBatchModel> db = new SitContext<StartProductionBatchModel>();

    [EnableQuery]
    [SITAuthorize("/production/ordersOverview")]
    public DbRawSqlQuery<StartProductionBatchModel> GetStartProductionBatchList([FromODataUri] string entryId)
    {
        Dictionary<string, string> parameters = new Dictionary<string, string>();

        parameters.Add("ENTRY_ID", entryId);

        return db.ExecuteProcedure("StartProductionBatch", parameters);
    }
}

In case of error in the stored procedure the exception is raised using SQL command RAISERROR.
On my client side I receive two different responses - if I connect from localhost, I get this:
{
  "odata.error":{
    "code":"","message":{
      "lang":"en-US","value":"An error has occurred."
    },"innererror":{
      "message":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","type":"System.InvalidOperationException","stacktrace":"","internalexception":{

        "message":"The following materials are not available on the line: 562942",

"type":"System.Data.SqlClient.SqlException","stacktrace":"

    ... there is the entire stack here

      }
    }
  }
}

...where I can read the error message (The following materials are not available on the line: 562942)
If I do the same thing from the remote computer, here is what I get back:
{
  "odata.error":{
    "code":"","message":{
      "lang":"en-US","value":"An error has occurred."
    }
  }
}

I tried to setup my IIS to return the detailed error (setting <httpErrors errorMode="Detailed" /> in web.config) even though it may be a security risc (not really in this case, it is an intranet application not published to the Internet), but nothing helped.
Thanks for any help.

A: You need to set the IncludeErrorDetailPolicy property on the HttpConfiguration class like this:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

More details can be found here: https://msdn.microsoft.com/en-us/library/system.web.http.httpconfiguration.includeerrordetailpolicy(v=vs.108).aspx