text:
Q: Difference between Constructor and ngOnInit Angular provides life cycle hook ngOnInit by default.
Why should ngOnInit be used, if we already have a constructor?

A: The constructor is a method in JavaScript and is considered as a feature of the class in es6 .When the class is instantiated it immediately runs the constructor whether it is used in Angular framework or not.So it is called by JavaScript engine and Angular has no control on that.
import {Component} from '@angular/core';
@Component({})
class CONSTRUCTORTEST {

//This is called by Javascript not the Angular.
     constructor(){
        console.log("view constructor initialised");
     }
}

The "ConstructorTest" class is instantiated below;So it internally calls the
constructor(All these happens by JavaScript(es6) no Angular).
new CONSTRUCTORTEST();

That is why there is ngOnInit lifecycle hook in Angular.ngOnInit renders when Angular has finished initialising the component.
import {Component} from '@angular/core';
@Component({})
class NGONINITTEST implements onInit{
   constructor(){}
   //ngOnInit calls by Angular
   ngOnInit(){
     console.log("Testing ngOnInit");
   }
}

First we instantiate the class as below which happen to immediate runs of constructor method.
let instance = new NGONINITTEST();

ngOnInit is called by Angular when necessary as below:
instance.ngOnInit();

But you may ask why we are using constructor in Angular?
The answer is dependencies injections.As it is mentioned before, constructor calls by JavaScript engine immediately when the class is instantiated (before calling ngOnInit by Angular), so typescript helps us to get the type of the dependencies are defined in the constructor and finally tells Angular what type of dependencies we want to use in that specific component.

A: constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature.
ngOnInit() is called after the constructor and ngOnInit is called after the first ngOnChanges.
i.e.:
Constructor() --> ngOnChanges() --> ngOnInit()
as mentioned above ngOnChanges() is called when an input or output binding value changes.

A: I will just add one important thing that was skipped in the explanations above and explains when you MUST use ngOnInit.
If you are doing any manipulation of the component's DOM via e.g. ViewChildren, ContentChildren or ElementRef, your native elements will not be available during the constructor phase.
However, since ngOnInit happens once the component has been created and the checks (ngOnChanges) have been called you can access the DOM at this point.
export class App implements OnInit, AfterViewInit, AfterContentInit {
  @Input() myInput: string;
  @ViewChild() myTemplate: TemplateRef<any>;
  @ContentChild(ChildComponent) myComponent: ChildComponent;

  constructor(private elementRef: ElementRef) {
     // this.elementRef.nativeElement is undefined here
     // this.myInput is undefined here
     // this.myTemplate is undefined here
     // this.myComponent is undefine here
  }

  ngOnInit() {
     // this.elementRef.nativeElement can be used from here on
     // value of this.myInput is passed from parent scope
     // this.myTemplate and this.myComponent are still undefined
  }
  ngAfterContentInit() {
     // this.myComponent now gets projected in and can be accessed
     // this.myTemplate is still undefined
  }

  ngAfterViewInit() {
     // this.myTemplate can be used now as well
  }
}

A: Two things to observe here:

*

*Constructor is called whenever an object is created of that class.

*ngOnInit called once the component is created.

Both have different usability.

A: The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.
The second one corresponds to a lifecycle hook of Angular2 components:
Quoted from official angular's website:

*

*ngOnChanges is called when an input or output binding value changes

*ngOnInit is called after the first ngOnChanges

So you should use ngOnInit if initialization processing relies on bindings of the component (for example component parameters defined with @Input), otherwise the constructor would be enough...

A: Constructor:
The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It's out of Angular's control when the constructor is invoked, which means that it's not a suitable hook to let you know when Angular has finished initialising the component. JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created. Bearing this in mind, there is a suitable scenario for using the constructor. This is when we want to utilise dependency injection - essentially for "wiring up" dependencies into the component.
As the constructor is initialised by the JavaScript engine, and TypeScript allows us to tell Angular what dependencies we require to be mapped against a specific property.
ngOnInit is purely there to give us a signal that Angular has finished initialising the component.
This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.
Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor, by design

A: Constructor is the first to execute, and it happens sometimes  when @input data is null!
so we use Constructor to inject services and ngOnInit happens after.
Example for constructor:
 constructor(translate: TranslateService, private oauthService: OAuthService) {
    translate.setDefaultLang('En');
        translate.use('En');}

Example for ngOnInit:
ngOnInit() {
    this.items = [
      { label: 'A', icon: 'fa fa-home', routerLink: ['/'] },
      { label: 'B', icon: 'fa fa-home', routerLink: ['/'] }]
}

I think that ngOnInit is like InitialComponents() in winForm .

A: Short and simple answer would be,
Constructor : constructor is a default method runs (by default) when component is being constructed. When you create an instance of a class that time also constructor(default method) would be called. So in other words, when the component is being constructed or/and an instance is created constructor(default method) is called and relevant code is written within is called. Basically and generally in Angular2, it used to inject things like services when the component is being constructed for further use.
OnInit: ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized.
So, Your constructor will be called first and Oninit will be called later after constructor method.
boot.ts
import {Cmomponent, OnInit} from 'angular2/core';
import {ExternalService} from '../externalService';

export class app implements OnInit{
   constructor(myService:ExternalService)
   {
           this.myService=myService;
   }

   ngOnInit(){
     // this.myService.someMethod()
   }
}

Resources: LifeCycle hook
You can check this small demo which shows an implementation of both things.

A: Both methods have different goals/responsibilities. The task of the constructor (which is a language supported feature) is to make sure that the representation invariant holds. Otherwise stated to make sure that the instance is valid by giving correct values to the members. It is up to the developer to decide what 'correct' means.
The task of the onInit() method (which is an angular concept) is to allow method invocations on a correct object (representation invariant). Each method should in turn make sure that the representation invariant holds when the method terminates.
The constructor should be used to create 'correct' objects, the onInit method gives you the opportunity to invoke method calls at a well defined instance.

A: The main difference between constructor and ngOnInit is that ngOnInit is lifecycle hook and runs after constructor. Component interpolated template and input initial values aren't available in constructor, but they are available in ngOnInit.
The practical difference is how ngOnInit affects how the code is structured. Most initialization code can be moved to ngOnInit - as long as this doesn't create race conditions.
Constructor antipattern
A substantial amount of initialization code makes constructor method hard to extend, read and test.
A usual recipe for separating initialization logic from class constructor is to move it to another method like init:
class Some {
  constructor() {
    this.init();
  }

  init() {...}
}

ngOnInit can serve this purpose in components and directives:
constructor(
  public foo: Foo,
  /* verbose list of dependencies */
) {
  // time-sensitive initialization code
  this.bar = foo.getBar();
}

ngOnInit() {
  // rest of initialization code
}

Dependency injection
The primary role of class constructors in Angular is dependency injection. Constructors are also used for DI annotation in TypeScript. Almost all dependencies are assigned as properties to class instance.
Average component/directive constructor is already big enough because it can have multiline signature due to dependencies, putting unnecessary intialization logic to constructor body contributes to the antipattern.
Asynchronous initialization
Asynchronous initialization constructor can often be considered antipattern and have smell because class instantiation finishes before asynchronous routine does, and this can create race conditions. If it's not the case, ngOnInit and other lifecycle hooks are better places for this, particularly because they can benefit from async syntax:
constructor(
  public foo: Foo,
  public errorHandler: ErrorHandler
) {}

async ngOnInit() {
  try {
    await this.foo.getBar();
    await this.foo.getBazThatDependsOnBar();
  } catch (err) {
    this.errorHandler.handleError(err);
  }
}

If there are race conditions (including the one that a component shouldn't appear on initialization error), asynchronous initialization routine should take place before component instantiation and be moved to parent component, router guard, etc.
Unit testing
ngOnInit is more flexible than a constructor and provides some benefits for unit testing that are explained in detail in this answer.
Considering that ngOnInit isn't called automatically on component compilation in unit tests, methods that are called in ngOnInit can be spied or mocked after component instantiation.
In exceptional cases ngOnInit can be entirely stubbed to provide isolation for other component units (for instance, some template logic).
Inheritance
Child classes can only augment constructors, not replace them.
Since this cannot be referred before super(), this puts restrictions on initialization precedence.
Considering that Angular component or directive uses ngOnInit for time-insensitive initialization logic, child classes can chose whether super.ngOnInit() is called and when:
ngOnInit() {
  this.someMethod();
  super.ngOnInit();
}

This would be impossible to implement with constructor alone.

A: Like a lot of other languages, you can initialize variables at the class level, the constructor, or a method. It is up to the developer to decide what is best in their particular case. But below are a list of best practices when it comes to deciding.
 Class level variables
Usually, you will declare all your variables here that will be used in the rest of you component. You can initialize them if the value doesn't depend on anything else, or use const keyword to create constants if they will not change.
export class TestClass{
    let varA: string = "hello";
}

Constructor
Normally it's best practice to not do anything in the constructor and just use it for classes that will be injected. Most of the time your constructor should look like this:
   constructor(private http: Http, private customService: CustomService) {}

this will automatically create the class level variables, so you will have access to customService.myMethod() without having to do it manually.
NgOnInit
NgOnit is a lifecycle hook provided by the Angular 2 framework. Your component must implement OnInit in order to use it. This lifecycle hook gets called after the constructor is called and all the variables are initialized. The bulk of your initialization should go here. You will have the certainty that Angular has initialized your component correctly and you can start doing any logic you need in OnInit versus doing things when your component hasn't finished loading properly.
Here is an image detailing the order of what gets called:

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
TLDR
If you are using Angular 2 framework and need to interact with certain lifecycle events, use the methods provided by the framework for this to avoid problems.

A: The article The essential difference between Constructor and ngOnInit in Angular explores the difference from multiple perspectives. This answer provides the most important difference explanation related to the component initialization process which also shows the different in usage.
Angular bootstrap process consists of the two major stages:

*

*constructing components tree

*running change detection

The constructor of the component is called when Angular constructs components tree. All lifecycle hooks are called as part of running change detection.
When Angular constructs components tree the root module injector is already configured so you can inject any global dependencies. Also, when Angular instantiates a child component class the injector for the parent component is also already set up so you can inject providers defined on the parent component including the parent component itself. Component constructors is the only method that is called in the context of the injector so if you need any dependency that's the only place to get those dependencies.
When Angular starts change detection the components tree is constructed and the constructors for all components in the tree have been called. Also every component's template nodes are added to the DOM. The @Input communication mechanism is processed during change detection so you cannot expect to have the properties available in the constructor. It will be available on after ngOnInit.
Let's see a quick example. Suppose you have the following template:
<my-app>
   <child-comp [i]='prop'>

So Angular starts bootstrapping the application. As I said it first creates classes for each component. So it calls MyAppComponent constructor. It also creates a DOM node which is the host element of the my-app component. Then it proceeds to creating a host element for the child-comp and calling ChildComponent constructor. At this stage it's not really concerned with the i input binding and any lifecycle hooks. So when this process is finished Angular ends up with the following tree of component views:
MyAppView
  - MyApp component instance
  - my-app host element data
       ChildCompnentView
         - ChildComponent component instance
         - child-comp host element data

Only then runs change detection and updates bindings for the my-app and calls ngOnInit on the MyAppComponent class. Then it proceeds to updating the bindings for the child-comp and calls ngOnInit on the ChildComponent class.
You can do your initialization logic in either constructor or ngOnInit depending on what you need available. For example the article Here is how to get ViewContainerRef before @ViewChild query is evaluated shows what type of initialization logic can be required to be performed in the constructor.
Here are some articles that will help you understand the topic better:

*

*Everything you need to know about change detection in Angular

*Angular's $digest is reborn in the newer version of Angular

*The mechanics of property bindings update in Angular

A: To test this, I wrote this code, borrowing from the NativeScript Tutorial:
user.ts
export class User {
    email: string;
    password: string;
    lastLogin: Date;

    constructor(msg:string) {
        this.email = "";
        this.password = "";
        this.lastLogin = new Date();
        console.log("*** User class constructor " + msg + " ***");
    }

    Login() {
    }
}

login.component.ts
import {Component} from "@angular/core";
import {User} from "./../../shared/user/user"

@Component({
  selector: "login-component",
  templateUrl: "pages/login/login.html",
  styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export class LoginComponent {

  user: User = new User("property");  // ONE
  isLoggingIn:boolean;

  constructor() {
    this.user = new User("constructor");   // TWO
    console.log("*** Login Component Constructor ***");
  }

  ngOnInit() {
    this.user = new User("ngOnInit");   // THREE
    this.user.Login();
    this.isLoggingIn = true;
    console.log("*** Login Component ngOnInit ***");
  }

  submit() {
    alert("You're using: " + this.user.email + " " + this.user.lastLogin);
  }

  toggleDisplay() {
    this.isLoggingIn = !this.isLoggingIn;
  }

}

Console output
JS: *** User class constructor property ***
JS: *** User class constructor constructor ***
JS: *** Login Component Constructor ***
JS: *** User class constructor ngOnInit ***
JS: *** Login Component ngOnInit ***

A: The Constructor is executed when the class is instantiated. It has nothing do with the angular. It is the feature of Javascript and Angular does not have the control over it
The ngOnInit is Angular specific and is called when the Angular has initialized the component with all its input properties
The @Input properties are available under the ngOnInit lifecycle hook. This will help you to do some initialization stuff like getting data from the back-end server etc to display in the view
@Input properties are shows up as undefined inside the constructor

A: The above answers don't really answer this aspect of the original question: What is a lifecycle hook?  It took me a while to understand what that means until I thought of it this way.
1)  Say your component is a human.  Humans have lives that include many stages of living, and then we expire.
2)  Our human component could have the following lifecycle script: Born, Baby, Grade School, Young Adult, Mid-age Adult, Senior Adult, Dead, Disposed of.
3)  Say you want to have a function to create children.  To keep this from getting complicated, and rather humorous, you want your function to only be called during the Young Adult stage of the human component life. So you develop a component that is only active when the parent component is in the Young Adult stage.  Hooks help you do that by signaling that stage of life and letting your component act on it.
Fun stuff.  If you let your imagination go to actually coding something like this it gets complicated, and funny.

A: The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like
new MyClass(someArg);

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.
We have to import OnInit like this in order to use it (actually implementing OnInit is not mandatory but considered good practice):
import { Component, OnInit } from '@angular/core';

then to make use of the method OnInit, we have to implement the class like this:
export class App implements OnInit {
  constructor() {
     // Called first time before the ngOnInit()
  }

  ngOnInit() {
     // Called after the constructor and called  after the first ngOnChanges()
  }
}

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized.
ngOnInit is called right after the directive's data-bound properties have been checked for the first time,
and before any of its children have been checked.
It is invoked only once when the directive is instantiated.

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".
So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.
For more information refer here:

*

*https://angular.io/api/core/OnInit

*Angular Component Constructor Vs OnInit
Important to note that @Input values are not accessible in the constructor (Thanks to @tim for suggestion in comments)

A: OK, first of all ngOnInit is part of Angular lifecycle, while constructor is part of ES6 JavaScript class, so the major difference starts from right here!...
Look at the below chart that I created which shows the lifecycle of Angular.

In Angular2+ we use constructor to do the DI(Dependency Injection) for us, while in Angular 1 it was happening through calling to String method and checking which dependency was injected.
As you see in the above diagram, ngOnInit is happening after the constructor is ready and ngOnChnages and get fired after the component is ready for us. All initialisation can happen in this stage, a simple sample is injecting a service and initials it on init.
OK, I also share a sample code for you to look, see how we get use of ngOnInit and constructor in the code below:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
 selector: 'my-app',
 template: `<h1>App is running!</h1>
  <my-app-main [data]=data></<my-app-main>`,
  styles: ['h1 { font-weight: normal; }']
})
class ExampleComponent implements OnInit {
  constructor(private router: Router) {} //Dependency injection in the constructor

  // ngOnInit, get called after Component initialised!
  ngOnInit() {
    console.log('Component initialised!');
  }
}

A: I think the best example would be using services.  Let's say that I want to grab data from my server when my component gets 'Activated'.  Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.
It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.
For Example:
export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
    };

}

with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it.  Like make sure everything is upper_case, I am not entirely sure how my data is coming through.
So it makes it much easier to use ngOnInit.
export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
        this.user_list.toUpperCase();
    };

}

It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else.  Really it's just another tool you can use to make it easier to read and use in the future.  Also I find it really bad practice to put function calls within a constructor!

A: In the Angular life-cycles
1) Angular injector detect constructor parameter('s) and instantiate class.
2) Next angular call life-cycle
Angular Lifecycle Hooks
ngOnChanges --> Call in directive parameters binding.
ngOnInit -->    Start angular rendering...
Call other method with state of angular life-cycle.

A: The constructor is called when Angular "instanciates/constructs" the component.
The ngOnInit method is a hook which represents the initialization part of the component lifecycle.
A good practice is to use it only for service injection:
constructor(private
    service1: Service1,
    service2: Service2
){};

Even if it is possible, you should not do some "work" inside.
If you want to launch some action which have to occur at component "initialization", use ngOnInit:
ngOnInit(){
    service1.someWork();
};

Moreover, actions that involve input properties, coming from a parent component, can't be done in the contructor.
They should be placed in ngOnInit method or another hook.
It is the same for element related to the view (the DOM), for example, viewchild elements:
@Input itemFromParent: string;
@ViewChild('childView') childView;

constructor(){
    console.log(itemFromParent); // KO
    // childView is undefined here
};

ngOnInit(){
    console.log(itemFromParent); // OK
    // childView is undefined here, you can manipulate here
};

A: Constructor is a function executed when component (or other class) is built.
ngOnInit is a function belonging to a component life-cycle method groups and they are executed in a diffrent moment of our component (that's why name life-cycle). Here is a list of all of them:

Constructor will be executed before any life-cycle function.

A: Constructor
The constructor function comes with every class, constructors are not specific to Angular but are concepts derived from Object oriented designs. The constructor creates an instance of the component class.
OnInit
The ngOnInit function is one of an Angular component's life-cycle methods. Life cycle methods (or hooks) in Angular components allow you to run a piece of code at different stages of the life of a component.
Unlike the constructor method, ngOnInit method comes from an Angular interface (OnInit) that the component needs to implement in order to use this method. The ngOnInit method is called shortly after the component is created.

A: Constructor is part of ES6 also typescript is using es6 syntax and now days es7 as well so you can utilise advance feature which typescript would compile to es5/es4 (as per you define) to provide support to old browser.
While ngOnInIt is lifecycle hook of angular. It is initialised when your component is initialised. (Consider it's state as born of any new life)
It's wise to use ngOnInIt compare to constructor, because you have another lifecycle hook like ngOnDestory (Consider it as death of any life). Here you can unsubscribe to any observable which is good to prevent any memory leak.
Incase any question feel free to comment on this answer.

A: constructor() is used to do dependency injection.
ngOnInit(), ngOnChanges() and ngOnDestroy() etc. are lifecycle methods. ngOnChanges() will be the first to be called, before ngOnInit(), when the value of a bound property changes, it will NOT be called if there is no change. ngOnDestroy() is called when the component is removed. To use it, OnDestroy needs to be implemented by the class.

A: I found the answer and I tried to translate it to english:
This question still arised, even in technical interviews. In fact, there is a big resemblance between the two, but also there are some differences.

*

*The constructor is part of ECMAScript. On the other hand ngOnInit() is a notion of angular.

*We can call the constructors in all classes even if we do not use Angular

*LifeCycle: The constructor is called before ngOnInt ()

*In the constructor we can not call HTML elements. However, in ngOnInit () we can.

*Generally, calls of services in the ngOnInit () and not in the constructor
Source: http://www.angular-tuto.com/Angular/Component#Diff

A: constructor() can accept parameter and can used for dependency injection or constructor() is for adding service objects.
constructor is called before ngOnint();
ngOnInit() is for manipulating components with necessary service function calls or Generally, calls of services in the ngOnInit () and not in the constructor

A: Constructor is the default method provided by Typescript class, which dedicated to  initializes the class members generally is used for dependencies injections services like the example code above, or timer initialization, socket connection initialization
export class AppComponent {
  title = 'angular-fork-join';
  constructor(private http: HttpClient) {}

ngOnInit: is a lifecycle hook called when the component is initialized  provided by Angular which dedicated for  example for business logic, data initialization, API calls, etc .., example code that demonstrates API call :
export class HomeComponent implements OnInit {

  products = [];

  constructor(private dataService: DataService) { }

  ngOnInit() {

    this.dataService.sendGetRequest().subscribe((data: any[])=>{
      console.log(data);
      this.products = data;
    })
  }

}


text:
Q: C++ Max size of array of pointers const unsigned int PATRON_TABLE_SIZE = 10001;
Patron* patronTable[PATRON_TABLE_SIZE];

Patron is a class containing basic info.  I checked the pointer at patronTable[500] and it is NULL, but the pointer at patronTable[5000] is not NULL.  I can't find any info about why this is the way it is.  Any help is appreciated!

A: c++ doesn't automatically initialize the array of pointers to any set value (unless you explicitely tell it to). So what you are seeing ist just random garbage which happened to occupy the space where the array was allocated. patronTable is PATRON_TABLE_SIZE long, just like you told it to be

A: Arrays in C++ that are not global or declared static are not initialized by default.

A: If you program unmanaged (not .NET) code, the memory isn't cleared. If you want all array elements to be NULL do something like memset(patronTable, 0, PATRON_TABLE_SIZE * sizeof(Patron[0]));

A: You can initialize the content of your array by
Patron* patronTable[PATRON_TABLE_SIZE] = { };

That will set all the values to zero.

redpajama_set_name: RedPajamaStackExchange


text:
Q: About max execution timeout I have some question on server response max execution timeout.
If, I called server API to running something huge and not able to finish within time limit set in server php.ini max_execution_time config, will the process in server still continue to process?
- if so, will it process endless?
- if not, is the process stop immediately or canceling loop one by one and finish all process.
In my experience, when I receive  max execution timeout on local hosting, the data is already process.
So I not sure it is because it is stuck on response until timeout or server is continue running after throw max execution timeout exception.

A: It really depends on what your PHP code is like.
Usually the code execution will halt. You can alter this behaviour using ignore_user_abort().

A: PHP interpreter runs scripts against php.ini configuration and checks max_execution_time = 500 and max_input_time = 500.
PHP doesn't continue to run the script after the max_execution_time. It's simply "kills" the script.
What can also happen, script starts a database query, normally query will run on database server until finished no-matter what happens to the script. Also you may get a Gateway Timeout coming from the web server, for Apache check httpd.conf and look for the setting Timeout.
If you need to run a script that takes time to execute, a lot more then the rest of your website, you should call a web page, PHP on server, fork a new process as a background executed script (the PHP part that takes lot of time), inform user via async status updates or sending an email that processing ended. You should not extend max_execution_time for all script just for one exception.

A: It doesn't continue after the exception is thrown. It's simply cut when the time is up.
Anything before the time out is executed. If not designed especially to precent this.

A: The process won't continue and stop immediately after the time limit set in server php.ini max_executiontime config has been reached then php throw a max execution timeout exception.
Here (How to increase maximum execution time in php) if you want to increase maximum execution time in php file.


text:
Q: Unity Coroutine not working across scenes I am calling a Coroutine shown below, which is attached to a DontDestroyOnLoad objects that persists across scenes.
IEnumerator InitMaxScore()
{
    Debug.Log("will wait for some time");
    yield return new WaitForSeconds(1);
    GameObject[] coins = GameObject.FindGameObjectsWithTag("Coin");
    Debug.Log("coins length == " + coins.Length);
    if (coins.Length > 0)
    {
        maxScoreInitialized = true;
        maxScore = score + coins.Length * 10;
        foreach (GameObject healthPickup in GameObject.FindGameObjectsWithTag("Health"))
        {
            maxScore += healthPickup.GetComponent<Pickups>().pointsForLifePickup;
        }
        Debug.Log("maxScore inti == " + maxScore);
    }
    yield return null;
}

This Coroutine is called in the OnLevelWasLoaded event of the said gameobject which is set to DontDestroyOnLoad on awake as shown below.
private void Awake()
{
    int numGameSessions = FindObjectsOfType<GameSession>().Length;
    if (numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DifficultyManagement.setDifficulty(Difficulty.One); // start the game with diff one always
        DontDestroyOnLoad(this.gameObject);
    }
}

While the log "will wait for some time" in the Coroutine is getting printed, Debug.Log("coins length == " + coins.Length) is not getting printed all the times. I am certainly not destroying the said gameobject for the entire duration of my game that might have caused the Coroutine to behave this way. The behaviour is not consistent either, sometimes it works, sometimes it does not, and I am like why can't you make up your mind.
I have been banging my head on this for a long time and could not seem to fix this, any leads would be appreciated to lift my mental block :/

A: OnLevelWasLoaded is deprecated, consider using sceneLoaded event:
using UnityEngine.SceneManagement;

private void Awake()
{
    int numGameSessions = FindObjectsOfType<GameSession>().Length;
    if (numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DifficultyManagement.setDifficulty(Difficulty.One); // start the game with diff one always
        DontDestroyOnLoad(this.gameObject);
        SceneManager.sceneLoaded += (scene, mode) => StartCoroutine(InitMaxScore());
    }
}


text:
Q: Can you solve non-linear problems with a neural network without using backpropagation? E.g. is it possible to solve the XOR problem without backpropagation. If so, what would a solution look like?

A: Purpose of Backpropagation is to optimize the bias of each hidden layer and the weights on the connecting neurons. So without backpropagation you can solve the problem but you won't be getting correct results.
following link may be useful:
https://datascience.stackexchange.com/questions/11589/creating-neural-net-for-xor-function


text:
Q: Scala - How to check which regex pattern match a string Assume I have more than 30 regex patterns:
val pattern1 = """(pat)(tern)(1)""".r
val pattern2 = """(pat)(tern)(1)""".r
val pattern3 = """(pat)(tern)(1)""".r
...

I want to check which pattern matches a string. Something like this
val s = "MyString"

s match {
 case pattern1 => grup 1 of pattern1
 case pattern2 => grup 2 of pattern2
 case pattern3 => grup 3 of pattern3
 ...
 case _ => "No pattern match"
}

A: In your case,you can do something like this:
val s = "MyString"

s match {
   case k if s.matches(pattern1.regex) => //.....do something
   case k if s.matches(pattern2.regex) => //.....do something
   case k if s.matches(pattern3.regex) => //.....do something
   ...
   case _ => "No pattern match"

}


text:
Q: VBA code to select a cell when specific letters appears and sort I need some help to understand and modify some code I found in this answer:
Sub Main()

    Dim cell As Range
    Dim nextRow As Long
    For Each cell In Range("K50:K200")
        If StrComp(cell, "Late", vbTextCompare) = 0 Then
            nextRow = Range("J" & Rows.Count).End(xlUp).Row + 1
            Range("J" & nextRow) = Range("B" & cell.Row)
            Range("K" & nextRow) = Range("C" & cell.Row)
            Range("N" & nextRow) = Range("G" & cell.Row)
            Range("O" & nextRow) = Range("H" & cell.Row)
        End If
    Next

End Sub

What I'd like is:

*

*If late is along with some other words, say late submit, copy values in B and paste in J

*if row K has progress along with say in progress, copy values in C to K

*If sick is with say on sick leave, copy values in G to N
I tried so hard,  but I still didn't succeed in modifying this code to suit my needs.

A:
If late is along with some other words, say late submit

In that case, instead of StrComp, use Instr
If Instr(1, cell, "Late", vbTextCompare) > 0 Then

Similarly for the rest.
If you check Excel's help you will notice that Instr returns a Variant (Long) specifying the position of the first occurrence of one string within another.
Syntax
InStr([start, ]string1, string2[, compare])


text:
Q: Como montar uma String de XML com SOAP? Não estou sabendo montar a STRING do XML de forma correta para envio dos parâmetros com xml. Segundo a documentação o metódo se chama coletar() mas não estou conseguindo passar esses parâmetros corretamente, sempre dá Erro 500:
Documentação Aqui
void main() async {
      String soap = '''

        <?xml version="1.0"?>

    <soap:Envelope
    xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
    soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

    <soap:Body>
      <coletar>
        <part>
          <dominio>luz</dominio>
       </part>
       <part>
          <login>"user"</login>
       </part>
       <part>
          <senha>"123456"</senha>
       </part>
       <part>
          <cnpjRemetente>"000.000.000-00"</cnpjRemetente>
       </part>
       <part>
          <cnpjDestinatario>"000.000.000-00"</cnpjDestinatario>
       </part>
       <part>
          <numeroNF>"123456"</numeroNF>
       </part>
       <part>
          <tipoPagamento>"D"</tipoPagamento>
       </part>
       <part>
          <enderecoEntrega>"Av Norte 1345"</enderecoEntrega>
       </part>
       <part>
          <cepEntrega>"578888-999"</cepEntrega>
       </part>
       <part>
          <solicitante>"Ricardo"</solicitante>
       </part>
       <part>
          <limiteColeta>"20-05-2020"</limiteColeta>
       </part>
       <part>
          <quantidade>"10"</quantidade>
       </part>
       <part>
          <peso>"10"</peso>
       </part>
       <part>
          <observacao>"nenhuma"</observacao>
       </part>
       <part>
          <cubagem>"30"</cubagem>
       </part>
       <part>
          <valorMerc>"50"</valorMerc>
       </part>
       <part>
          <especie>"não especificado"</especie>
       </part>
      </coletar>
    </soap:Body>

    </soap:Envelope> ''';

        postOTP("https://ssw.inf.br/ws/sswColeta/index.php", soap);
    }

        Future<String> postOTP(String _uri, String _message) async {

      HttpClient client = new HttpClient();
      HttpClientRequest request = await client.postUrl(Uri.parse(_uri));
      request.write(_message);
      HttpClientResponse response = await request.close();
      StringBuffer _buffer = new StringBuffer();
      await for (String a in await response.transform(utf8.decoder)) {
        _buffer.write(a);
      }

      print("_buffer.toString: ${_buffer.toString()}");
      return _buffer.toString();
    }

A: Resolvi da seguinte forma:
Instalei um plugin no Google Chrome que ajuda a interpretar os métodos embutidos dentro da url do WebService:
Wizdler
Url do webservice:
https://ssw.inf.br/ws/sswColeta/index.php?wsdl

Método Coletar() extraído:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
    <Body>
        <coletar xmlns="urn:sswinfbr.sswColeta">
            <dominio>[string]</dominio>
            <login>[string]</login>
            <senha>[string]</senha>
            <cnpjRemetente>[string]</cnpjRemetente>
            <cnpjDestinatario>[string]</cnpjDestinatario>
            <numeroNF>[string]</numeroNF>
            <tipoPagamento>[string]</tipoPagamento>
            <enderecoEntrega>[string]</enderecoEntrega>
            <cepEntrega>[integer]</cepEntrega>
            <solicitante>[string]</solicitante>
            <limiteColeta>[dateTime]</limiteColeta>
            <quantidade>[integer]</quantidade>
            <peso>[decimal]</peso>
            <observacao>[string]</observacao>
            <instrucao>[string]</instrucao>
            <cubagem>[decimal]</cubagem>
            <valorMerc>[decimal]</valorMerc>
            <especie>[string]</especie>
        </coletar>
    </Body>
</Envelope>


text:
Q: spark2-submit is throwing java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream I am getting following error while running spark2-submit after installing spark 2.0.0.
Does anyone know why it is not able to point to hadoop jar files? When I 'echo $HADOOP_HOME' in spark2-submit its shows the correct HADOOP_HOME path.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
        at org.apache.spark.deploy.SparkSubmitArguments$$anonfun$mergeDefaultSparkProperties$1.apply(SparkSubmitArguments.scala:118)
        at org.apache.spark.deploy.SparkSubmitArguments$$anonfun$mergeDefaultSparkProperties$1.apply(SparkSubmitArguments.scala:118)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.deploy.SparkSubmitArguments.mergeDefaultSparkProperties(SparkSubmitArguments.scala:118)
        at org.apache.spark.deploy.SparkSubmitArguments.<init>(SparkSubmitArguments.scala:104)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:117)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.fs.FSDataInputStream
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

A: Try to add the jars in the HADOOP_HOME/share/hadoop to the CLASSPATH.
Such as I add CLASSPATH in the /etc/profile,and my hadoop version is 2.7.2
export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.7.2.jar:$HADOOP_HOME/share/hadoop/common/hadoop-common-2.7.2.jar:$HADOOP_HOME/share/hadoop/common/lib/commons-cli-1.2.jar:$CLASSPATH


text:
Q: how to hide text in html page source? I wanna show some text (and images) in browser but this text shouldn't be able to select in page preview or page source :

*

*At first i tried to use canvas, but managing text and also images in canvas is not easy and for this case i can't use canvas.

*I tried to use image but in this case, image is too slow to load.

*I used ROT13 encryption in Aptana studio, but ROT13 just encrypt page source with JS and when you click on 'inspect element' in chrome or opera you can see decrypt text and html yet.
Question: Is there any way in jquery or anything else?

A: No, whatever you display as text in webpage can be found by digging into the source of the webpage (including js). What would this be useful for btw.?
Edit: This looks useful but ends up using canvas or flash I believe. Still might be tuned to be fairly fast and therefor useful:
http://eric-blue.com/2010/01/03/how-to-create-your-own-personal-document-viewer-like-scribd-or-google-books/

A: You most likely won't find a way to do this easily, as when the browser downloads the page, in order to show the text to the user it has to be decoded or decrypted. So no matter what, if the user can see it, they can copy it. If all you want is to block selection in the browser, this answer should help

A: No, if you want to place something on the page a browser need to know what you want to place on the page. And everything what was sent to the browser is readable for a user. So you cannot do this.
The answer is very simple: If you don't want to publish something don't place it on the internet.

A: yes, this my logic check out
make you string in ascii code and write on document
check below link and find example may you help
 Link W3School

A: I guess no one could do that.
Just use some image instead, old-style, but useful.


text:
Q: C++ static library is not compiling in xcode on mac I am new to stack overflow. I am developing a static c++ library on mac using xcode(9.3). It was compiling and running fine but then i did some code changes and after that its showing some strange compile time errors. like
"/clang:-1: linker command failed with exit code 1 (use -v to see invocation)". Any help will be much appreciated.
    Undefined symbols for architecture x86_64:
  "LJCPPBL_CORE::LJCPPBL::Initialize(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      _main in main.o
  "LJCPPBL_CORE::LJCPPBL::GetShortestPath(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, float*)", referenced from:
      _main in main.o
  "LJCPPBL_CORE::LJCPPBL::GetJson()", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Above text is showing in log.
This is the LJCPPBL header file "LJCPPBL.hpp"
#ifndef LJCPPBL_hpp
#define LJCPPBL_hpp

#include <iostream>
#include "../Models/Models.hpp"
#include <list>
#include <string.h>

using namespace std;
using namespace LJCPPBL_Models;

namespace LJCPPBL_CORE {

 class LJCPPBL
    {
        public: static void Initialize(string clientAPIKEY);
        public: static string GetJson();
        public: static void SetJson(string strJson);
        public: static list<Destination> GetDestinationsList();
        public: static list<Point> GetShortestPath(string source, string destination, float* costOfPath);
    };
}

#endif /* LJCPPBL_hpp */

This is the Implementation of LJCPPBL header file "LJCPPBL.cpp"
#include <iostream>
#include "LJCPPBL.hpp"
#include "../Models/Models.hpp"
#include "../DAL/DataAccess.cpp"
#include "../Plugins/JsonParser/json.hpp"
#include "SPC.cpp"
#include "GlobalValues.cpp"
#include <list>

using namespace std;
using namespace LJCPPBL_CORE;
using namespace LJCPPBL_DAL;

namespace  LJCPPBL_CORE{
void LJCPPBL::Initialize(string clientAPIKEY){
        auto globalValues = new GlobalValues();
        LJCPPBLGlobalValues = *globalValues;
        LJCPPBLGlobalValues.ClientAPIKey = clientAPIKEY;
    }

    string LJCPPBL::GetJson()
    {
        LJCPPBLAPIDAL* objDAL = new LJCPPBLAPIDAL();
        string mapPointsAndPathJson = objDAL -> GetMapsAndPointsJSON();
        string mapDestinationJSON = objDAL -> GetMapDestinationsJSON();
        json jsonObj = {{"MapPointsAndPathJSON", mapPointsAndPathJson}, {"MapDestinationJSON", mapDestinationJSON} };
        return jsonObj.dump();
    }

    void LJCPPBL::SetJson(string strJson)
    {

    }

    list<Destination> LJCPPBL::GetDestinationsList()
    {
         LJCPPBLAPIDAL* objDAL = new LJCPPBLAPIDAL();
        return objDAL -> GetDestinations();
    }

    list<Point> LJCPPBL::GetShortestPath(string source, string destination, float* costOfPath)
    {
        return SPC::GetShortestPath(source, destination, costOfPath);
    }
}
//#endif

Thanks in Advance for your help.

A: Right-click on the linker error and select "show in log", this will give you real details about the error.
Most likely, it's some unresolved external symbol, so you might not have linked some library or some cpp file to your project.
After edit of question:
There seems to be some library "LJCPPBL" that you have not linked in. At least, you have not linked the core module. You need to set library paths and add library files to your project.


text:
Q: Sending a value on script start trying to make a bash script that sets a value for use later in the script, depending on what  I send when I run it;
 i.e. ./script.sh 24
code:
### Setting values depending on input
#
#   If value is between 7 and 13
if [[ $1 -le 13 || $1 -ge 7 ]]; then
    #set value to
    VALUE=7

#   else if value is between 14 and 29
elif [[ $1 -le 29 || $1 -ge 14 ]]; then
    #else set value to
    VALUE=14

# else if value is larger than 30
elif [[ $1 -le 30 ]]; then
    #Set value to VALUE=30
#else
 #   echo nope
fi

# This is just for showing what's going on
echo "input: $1"; echo "value: $VALUE"

#   Do other stuff here...

But I can't get it to work properly, it only sets "value" to 7, no matter what i send on script start.
Does bash read values in any special order? When I run it with ./script.sh 24 I gives "value=7" but it (in my mind) should be "value=14"

A: In the first comparison:
$1 -le 13 || $1 -ge 7

You are checking if a value is below 13 or above 7. All natural numbers matches this condition, like: 1 is below 13, 100 is avobe 7, and 10 is below 13 and avobe 7. So you always enter in the first branch.
Maybe you are looking for numbers above 7 AND below 13:
$1 -le 13 && $1 -ge 7


text:
Q: Permission denied on checking java version in ubuntu On asking java -version -
  java -version

  bash: /home/user/jdk-8u221-linux-x64/jdk1.8.0_221/bin/java: Permission denied

it says permission denied , but on using sudo it gives.
Due to which intelliJ is also not able to build project .
How to get access or how do I provide priveleg to the user
also showing problem in intellij -

A: You could try this command
sudo chmod a+x /usr/bin/java


text:
Q: Updating dbc.Card with hoverData I have the following skeleton code

# ------------------------------
#       IMPORT LIBRARIES
# ------------------------------

# Import Dash and Dash Bootstrap Components
import dash
import dash_bootstrap_components as dbc
from dash import Input, Output, dcc, html, dash_table, State
import dash_leaflet as dl

# Import Core Libraries
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from dash import Input, Output, dcc, html, dash_table

token='my_token'

FONT_AWESOME = "https://use.fontawesome.com/releases/v5.10.2/css/all.css"

# Import data

data_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSGcAFoXyMXk7lj3KJrpzKd5XiBufm2xa7M39QNZxw5ma0TZhP35q-mf2ybyf9cZQdEwsoWkHiQWfjC/pub?gid=0&single=true&output=csv'

df = pd.read_csv(data_url)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP,FONT_AWESOME], title='CONFIRM - SK4U', update_title=None,
    meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=0.7, minimum-scale=0.4"}],
    )

server = app.server

fig_map = px.scatter_mapbox(df,lat='latitude',lon='longitude',
                            mapbox_style='mapbox://styles/vostpt/cl1w0k6uf000415nt86nk7uv2',
                            #color='Kategória / Category',
                            width=1400,height=700,
                            hover_name='name',

                            #center=[48.799330977271445,19.338585158029197],
                            center=dict(lon=20.0068, lat=48.8264),
                            zoom=7,
                            custom_data=['name']
                            )

fig_map.update_layout(
        hoverlabel=dict(
        bgcolor="white",
        font_size=16,
        font_family="sans-serif"
        )
    )

fig_map.update_layout(mapbox = dict(accesstoken = token, style ='mapbox://styles/vostpt/cl1w0k6uf000415nt86nk7uv2'))

app.layout = html.Div(
            [
            dbc.Row(
                [
                dbc.Col(
                    dbc.Card(
                        dbc.CardBody(
                            [
                                html.H4("Title", className="card-title"),
                                html.H6("Card subtitle", className="card-subtitle"),
                                html.P(id="card_data"),
                                dbc.CardLink("Card link", href="#"),
                                dbc.CardLink("External link", href="https://google.com"),
                            ]
                        ),

                    ),

                ),
                dbc.Col(
                    dcc.Graph(id="my_map",figure=fig_map),
                xs=12,
                ),
                ],
                ),

            ],
)

@app.callback(
    Output(component_id="card_data", component_property="children"),
    Input(component_id="my_map", component_property="hoverData")
)

def upgrade_card(hoverData):
    title = hoverData['name'][0]
    return title

if __name__ == "__main__":
    app.run_server(host='0.0.0.0', debug=True)

My objective is to update the text in the card, with the data from the dataframe, on mouse hover.
The app receives the input from the hoverData but returns the error message
TypeError: 'NoneType' object is not subscriptable

Any help would be much appreciated.
Disclaimer: The solution will be used in a non-for-profit NGO's project. No commercial use will be made of the solution

A: These errors usually come up when you did not properly initialize. The children of the p-tag are non-existent in your example, so they cannot be updated.
So, replace html.P(id="card_data") with html.P("", id="card_data").


text:
Q: I have json Data and want to Dispaly on .cshtm view in Asp.net i have some Json data and i want to show on Razor view,
Please suggest me here is my Json data
Json Data:
[{"Name":"H&S 01","1":65656.0,"2":67779.0,"3":32323.0,"4":232323.0,"5":34.0,"6":345.0,"7":34.0,"8":23.0,"9":0.0,"10":0.0,"11":0.0,"12":0.0},{"Name":"H&S 02","1":2342.0,"2":234.0,"3":234.0,"4":23.0,"5":234.0,"6":23423.0,"7":23423.0,"8":4343.0,"9":23658.0,"10":667.0,"11":366.0,"12":34766.0},{"Name":"H&S 03","1":0.0,"2":333.0,"3":0.0,"4":0.0,"5":0.0,"6":0.0,"7":0.0,"8":0.0,"9":0.0,"10":0.0,"11":0.0,"12":0.0}]

disply 1
Second Images
Output 2
and i want to display on view be like.
Name| Jan- 2008 | Feb- 2008 | Mar - 2008| Total
H&S1| 65656     | 23        |  34       | 65727
H&S2| 23333     | 4300      | 2150      | 27570

A: What you can try is
First, Translate
From
[
  {
    "1": 65656,
    "2": 67779,
    "3": 32323,
    "4": 232323,
    "5": 34,
    "6": 345,
    "7": 34,
    "8": 23,
    "9": 0,
    "10": 0,
    "11": 0,
    "12": 0,
    "Name": "H&S 01"
  }
]

To something like:
[
  {
    "Jan- 2008": 65656,
    "Feb- 2008": 67779,
    "Mar- 2008": 32323,
    "Apr- 2008": 232323,
    "May- 2008": 34,
    "Jun": 345,
    "Jul": 34,
    "Aug": 23,
    "Sep": 0,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0,
    "Name": "H&S 01"
  }
]

You can do this using JSON serializers like https://www.newtonsoft.com/json.
Have a look at this on how you can iterate on your properties
Next, you can use a library to display the JSON as a table and then just customize the table with CSS
Here's one I found.
https://github.com/jongha/jquery-jsontotable
If you want to try out how JSON to table works, have a go here


text:
Q: Creating a Qweb Report based on Category for custom module Hello Odooers and XMLers.
How can i group these records based on Category and Sub-Category(custom fields) in a Custom Module ?
Records Tree View:

Example Desired Report Design:

i Tried this Code but didn't work.
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="report_main">
    <t t-call="web.html_container">
        <t t-set="main_seco" t-value="[]"/>
        <t t-foreach="bondid" t-as="l">
            <t t-set="work1_name" t-value="work1_name+[l.work1_id]"/>
        </t>
    <t t-foreach="set(work1_name)" t-as="work1">

    <t t-foreach="o.bondid" t-as="l">

    </t>
</t>
</t>
</template>
</odoo>
Blockquote

A: Frist, you use t-foreach for get all item parent with t-as="i"
Second, in t-foreach you use search and with domain is category.parent = i.parent
The same with sub-category
You can view my example:
image
If you lose, you can contact to me (transon821996@gmail.com). I will support you.
Sorry for my english. I'm trying learn it.


text:
Q: Search by date range and by keyword For report generation in the project I made I want to use 2 methods:

*

*By date range (from date and up to date)

*By employee ID

While using the above keywords the complete record of the employee should be displayed in that particular range.
For ex- emp1234 is the employee whose record is to be checked between date 20 may 2018 to 30 june 2018. The result must be displayed in between the range
Another thing is that the search can be done either by date or by employee id or both but both should not be compulsory.
the script is as follows:

I need to combine these two different queries into one.
filter.php
<?php
 //filter.php
 if(isset($_POST["from_date"], $_POST["to_date"]))
 {
      $connect = mysqli_connect("localhost", "root", "", "ais");
      $output = '';
      $query = "
           SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance  WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_out_time_attendance.date  BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
      ";
      $result = mysqli_query($connect, $query);
      $cnt=1;
      $output .= '

                     Sr No.
                     EMPLOYEE ID
                     EMPLOYEE NAME
                     IN_TIME
                     OUT_TIME
                     DATE
                     WORKING HOURS

      ';
      if(mysqli_num_rows($result) > 0)
      {
           while($row = mysqli_fetch_array($result))
           {
                        $outtime = $row["outtime"];
                        $intime = $row["intime"];
                        $array1 = explode(':', $intime);
                        $array2 = explode(':', $outtime);

                        $minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
                        $minutes2 = ($array2[0] * 60.0 + $array2[1])/60;

                        $diff = round(($minutes2 - $minutes1),1).' hrs';

                $output .= '

                          '. $cnt .'
                          '. $row["EmpId"] .'
                          '. $row["FirstName"] . " " . $row["LastName"].'
                          '. $row["intime"] .'
                           '. $row["outtime"] .'
                          '. $row["date"] .'	 ';
        if ($diff < 8) {
        $output .= ' ' . $diff . ' 	';
} else {
    $output .= ' ' . $diff . ' 	';
}
$output .= '
';

          $cnt++;
           }

      }
      else
      {
           $output .= '

                     No Record Found

           ';
      }
      $output .= '
';
      echo $output;
 }

 ?>

Fetch.php
<?php

$connect = mysqli_connect("localhost", "root", "", "ais");
$output = '';
if(isset($_POST["query"]))
{

 $query = "
          SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance  WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_employees.EmpId LIKE '".$_POST["query"]."' ";
}
else
{
 $query = "SELECT * from tbl_employees, tbl_in_time_attendance , tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date";

}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
 $cnt=1;

 $output .= '

                     Sr No.
                     EMPLOYEE ID
                     EMPLOYEE NAME
                     IN_TIME
                     OUT_TIME
                     DATE
                     WORKING HOURS

 ';
 while($row = mysqli_fetch_array($result))
 {
  $outtime = $row["outtime"];
                        $intime = $row["intime"];
                        $array1 = explode(':', $intime);
                        $array2 = explode(':', $outtime);

                        $minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
                        $minutes2 = ($array2[0] * 60.0 + $array2[1])/60;

                        $diff = round(($minutes2 - $minutes1),1).' hrs';

                $output .= '

                          '. $cnt .'
                          '. $row["EmpId"] .'
                          '. $row["FirstName"] . " " . $row["LastName"].'
                          '. $row["intime"] .'
                           '. $row["outtime"] .'
                          '. $row["date"] .'	 ';
        if ($diff < 8) {
        $output .= ' ' . $diff . ' 	';
} else {
    $output .= ' ' . $diff . ' 	';
}
$output .= '
';

          $cnt++;
 }
 }
 else
      {
           $output .= '

                     No Record Found

           ';
      }
      $output .= '
';
      echo $output;

?>

I want these to separate fetch and filter files into one file.
Please help.

A: please dont delete the question again, i was writing a few minutes and then the question was deleted haha
soo, as you have a filter button which has to be clicked to get the results there are two ways you can choose!

*

*you display your table with datatable plugin which means you only need to filter by date and then write the employeeid in the searchbox and you will only see the results for this person WITHOUT having to query it again!
https://datatables.net/

*you get the two dates AND your search query by clicking on the filter button which means you will only have one php file (i dont know why you actually want to use fetch & filter).. In your php file you then look if there are only dates submitted OR the query is also submitted:
$('#filter').click(function(){
   var from_date = $('#from_date').val();
   var to_date = $('#to_date').val();
   var query = $("#search_text").val();

   if(from_date != '' && to_date != '')
   {
     $.ajax({
          url:"filter.php",
          method:"POST",
          data:{from_date:from_date, to_date:to_date, employee: query},
          success:function(data)
          {
               $('#report_table').html(data);
          }
     });
   }
   else
   {
     alert("Please Select Date");
   }
});

in php file
if(isset($_POST["employee"]) AND $_POST["employee"] != "") {
    // make your sql call with dates AND employeeid
} else {
    // make your sql call only with dates
}

depending on how many results you have I'm sure its also possible to dont even have to query again for different dates and instead tweak datatable so that you have one from_date, one to_date and one search field and filter the table after keyup.. see example here: https://datatables.net/examples/api/multi_filter.html


text:
Q: How can I update a secret on Kubernetes when it is generated from a file? I've created a secret using
kubectl create secret generic production-tls \
  --from-file=./tls.key \
  --from-file=./tls.crt

If I'd like to update the values - how can I do this?

A: This should work:
kubectl create secret generic production-tls \
--save-config \
--dry-run=client \
--from-file=./tls.key --from-file=./tls.crt \
-o yaml | \
kubectl apply -f -

A: For more specific cases you might need to specify your namespace that the cert needs to be renewed and delete the old one.
For deletion of the cert
kubectl delete secret -n `namespace`

For the creation of new cert to specific namespace
kubectl create secret {your-cert-name} --key /etc/certs/{name}.com.key --cert /etc/certs/{name}.com.crt -n {namespace}

A: Late to the party but still here are my inputs.
Potentially we can use both the patch or edit option.

*

*With edit :
kubectl edit secrets/<SECRET_NAME> -n <NAME_SPACE>

*

*NOT the recommended way of editing the secrets.

*You should have enough permission to do the above edit.

*The value should be base64 encode by yourself and then the encoded value should be placed while editing.

*With patch :

*

*this may help you How to update secret with "kubectl patch --type='json'"

A: Just to expand on these answers I found that adding '--ignore-not-found' to the delete helped with our CICD as it wouldn't error out if the secret didn't exist, it would just go ahead and create it:
kubectl delete secret production-tls --ignore-not-found
kubectl create secret generic production-tls --from-file=./tls.key --from-file=./tls.crt.

A: Alternatively, you can also use jq's = or |= operator to update secrets on the fly.
TLS_KEY=$(base64 < "./tls.key" | tr -d '\n')
TLS_CRT=$(base64 < "./tls.crt" | tr -d '\n')
kubectl get secrets production-tls -o json \
        | jq '.data["tls.key"] |= "$TLS_KEY"' \
        | jq '.data["tls.crt"] |= "$TLS_CRT"' \
        | kubectl apply -f -

Although it might not be as elegant or simple as the kubectl create secret generic --dry-run approach, technically, this approach is truly updating values rather than deleting/recreating them. You'll also need jq and base64 (or openssl enc -base64) commands available, tr is a commonly-available Linux utility for trimming trailing newlines.
See here for more details about jq update operator |=.

A: As I wasn't able to reply to Devy's answer above, which I like because it will preserve Ownership where deleting and recreating has the potential to lose any extra information in the record.  I'm adding this for the newer people who may not immediately understand whey their variables aren't being interpolated.
TLS_KEY=$(base64 < "./tls.key" | tr -d '\n')
TLS_CRT=$(base64 < "./tls.crt" | tr -d '\n')
kubectl get secrets production-tls -o json \
        | jq ".data[\"tls.key\"] |= \"$TLS_KEY\"" \
        | jq ".data[\"tls.crt\"] |= \"$TLS_CRT\"" \
        | kubectl apply -f -

This lead me to attempting to use the 'patch' method of kubectl, which also seems to work.
kubectl \
        patch \
        secret \
        production-tls \
        -p "{\"data\":{\"tls.key\":\"${TLS_KEY}\",\"tls.crt\":\"${TLS_CRT}\"}}"

Thanks Devy for the answer that best met my needs.

A: You can delete and immediately recreate the secret:
kubectl delete secret production-tls \
--ignore-not-found

kubectl create secret generic production-tls \
--from-file=./tls.key \
--from-file=./tls.crt

I put these commands in a script. The --ignore-not-found prevents getting a warning on the first run.

A: You can use patch secret:
kubectl patch secret my-secret  --patch="{\"data\": { \"tls.key\": \"$(base64 -w0 ./tls.key)\",\"tls.crt\": \"$(base64 -w0 ./tls.crt)\"  }}"

A: I've found a best way to do so:
kubectl create secret generic production-tls --from-file=./tls.key  --from-file=./tls.crt --dry-run=client -o yaml | kubectl apply -f -


text:
Q: Database with support for JOINs and a flexible data schema For our project, we need a database that supports JOINs and has the ability to easily add and modify attributes of the entity (schema-less/free). Key points:

*

*The system is designed to work with customers (CRM)

*Basic entities: User, Customer, Case, Case Interaction, Order

*Currently in the database there are ~200k customers and ~250k orders

*Customer entity contains 15-20 optional attributes that are most often not filled

*About 100 new cases a day

*The data is synchronized with several other sources in the background

Requirements (high to low priority):

*

*Ability to implement search/sort by related entities, e.g. Case by linked Customer name (support JOINs)

*Having the flexibility to change the schema of the data and do not store NULL for a large number of attributes

*Performance

*ORM for Python with support for monitoring changes and the possibility of storing only the changes to the database

What we've tried:

*

*MongoDB does not satisfy paragraph 1.

*PostgreSQL with all the attributes in one table does not satisfy paragraph 2.

*PostgreSQL with a separate table for each attribute or EAV does not satisfy paragraph 3 (a lot of slow joins), but seems a better solution than others.

Can you suggest any database or design of the system that will meet our needs?

A: Datomic might be worth checking out (http://www.datomic.com/). It satisfies requirements 1-3, and although there's no python ORM, there is a REST API.
Datomic is based on an Entity Attribute Value schema (it's not quite schema free - you need to specify a name and type for each attribute -  but any entity can have any attribute). It is transactional and has support for joins, unlike some of the other flexible "NoSQL" solutions. Interestingly, it also has first-class support for time (e.g. what is the history of this entity/what did the database look like at time t,etc), which might be useful if you're tracking cases and interactions.
Queries are based on datalog, which queries by unification. Query by unification looks a bit odd at first but is brilliant once you get used to it.
For example,  a query to find cases by linked customer name would be something like this:
[find ?x
 :in $
 :where [?x :case/linked-customers ?c
         ?c :customer/name "Barry"]]

The query engine looks in the database, and tries to satisfy the where clause by unifying all occurrences of a given variable. In this case, only ?c appears twice (the case has a linked customer c whose name is Barry), but queries can obviously get a lot more complex. The $ here represents the database.

A: You may want to consider storing the "flexible" part as XML. Some databases, e.g. DB2, allow XML indexing so lookup performance should be as good as with the relational data store. DB2 Express-C is free and does not have an artificial limit on the database size.
Update Since 2015 DB2 Express-C limits the database user data volume to 15 TB, which still should be plenty.


text:
Q: Regular expression to delete the whole line include the end of line I want to delete all the commented lines in a powershell script using another powershell script. I expected this to be very easy, but apparently it is not. Here are the things I tried, and obviously didn't work:
(Get-Content commented.ps1) -replace '^#.*$', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '#.*$', '' | Set-Content uncommented.ps1

These worked, but the end of line is still there, so now I have some empty lines instead of the comments, which is not what I want.
(Get-Content commented.ps1) -replace '#.*\r\n', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '^#.*\r\n$', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '#.*\r\n$', '' | Set-Content uncommented.ps1

I also tried to write just \n, even though I'm sure my file is CRLF. And I also tried to put \n or \r\n at the beginning. These did not work at all, but they also didn't error.
Test files:
commented.ps1 :
#This is a comment
$var = 'this is a variable'
# This is another comment
$var2 = 'this is another variable'

expected uncommented.ps1 :
$var = 'this is a variable'
$var2 = 'this is another variable'

I simply don't get it why \r\n does not match end of line. Any help is highly appreciated. I guess the question is:
How to match the end of the line successfully in powershell using Get-Content -replace?

A: Instead of using -replace you can use simple Where-Object to filter lines without the comment sign (#), the regex as well is pretty simple, ^# means match any # character at the start of the line, see: http://www.regular-expressions.info/anchors.html
(Get-Content commented.ps1) | Where-Object {$_ -notmatch '^#'} | Set-Content uncommented.ps1


text:
Q: Run Casperjs with specific version of Phantomjs In response to this issue where newer PhantomJS is 10x slower:
https://github.com/ariya/phantomjs/issues/14066
I want to run CasperJS with an older version of PhantomJS.  I have globally installed both with npm.
sudo npm install -g casperjs
sudo npm install -g phantomjs@1.9.8
$ phantomjs --version
1.9.7
$ casperjs --version
1.1.0-beta5
However when I run my Casper scripts my previously properly (but slowly) running script throws:
Error: TypeError: 'null' is not an object (evaluating 'document.getElementById('Email').value = email')
How do I properly link casperjs to phantomjs?


text:
Q: data overwrited when added to Json Array I have data coming from Splunk, the data are host with ports, some host have more then one port. so I made the logic below. for every host with single port I added to jsonarray. the issue is the port is always overwrite at the moment where it added to the jsonarray I counldnt figure out why?
 public JSONObject parse_OS_Vuln_data_to_Json() {
        JSONObject responseDetailsJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (list_of_OS_VulnerabilityOS.size()>0)
        {
            for (int i = 0; i < list_of_OS_VulnerabilityOS.size(); i++) {
                JSONObject formDetailsJson = new JSONObject();
                if (list_of_OS_VulnerabilityOS.get(i).getList_of_ports().size() > 1)
                {
                    for (int v = 0; v < list_of_OS_VulnerabilityOS.get(i).getList_of_ports().size(); v++)
                    {
                        formDetailsJson.put("host", list_of_OS_VulnerabilityOS.get(i).getDest());
                        formDetailsJson.put("port", list_of_OS_VulnerabilityOS.get(i).getList_of_ports().get(v)); // i got each time different port
                        formDetailsJson.put("open", list_of_OS_VulnerabilityOS.get(i).isOpen());
                        formDetailsJson.put("info", list_of_OS_VulnerabilityOS.get(i).getInfo());
                        jsonArray.add(formDetailsJson); // here it overwrites to the first port again
                        total_hostNumber_OS++;
                    }
                } else {
                    formDetailsJson.put("host", list_of_OS_VulnerabilityOS.get(i).getDest());
                    formDetailsJson.put("port", list_of_OS_VulnerabilityOS.get(i).getPorts___port());
                    formDetailsJson.put("open", list_of_OS_VulnerabilityOS.get(i).isOpen());
                    formDetailsJson.put("info", list_of_OS_VulnerabilityOS.get(i).getInfo());
                    jsonArray.add(formDetailsJson);
                    total_hostNumber_OS++;
                }
        }
            responseDetailsJson.put("data", jsonArray);
            System.out.print("\n list size: " + list_of_OS_VulnerabilityOS.size());
            System.out.print("\n total of OS-host to be send : " + total_hostNumber_OS);

        }
        return responseDetailsJson;
    }```

A: You're referencing the same formDetailsJson instance within your 'v'-loop. Meaning that every time you call 'put', it's on the same object (This means that not only your port should be overwritten, but all other fields as well). All entries in your jsonArray would be a reference to the same instance.
It might also be nicer to assign a variable to list_of_OS_VulnerabilityOS inside of your loop instead of duplicating so often.
Code would look something like this:
    public JSONObject parse_OS_Vuln_data_to_Json() {
        JSONObject responseDetailsJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (list_of_OS_VulnerabilityOS.size()>0) {
            for (int i = 0; i < list_of_OS_VulnerabilityOS.size(); i++) {
                WhateverTheTypeIs currentOSVulnerability = list_of_OS_VulnerabilityOS.get(i);
                JSONObject formDetailsJson;

                if (currentOSVulnerability .getList_of_ports().size() > 1) {
                    for (int v = 0; v < list_of_OS_VulnerabilityOS.get(i).getList_of_ports().size(); v++) {
                        formDetailsJson = new JSONObject() // Here's the fix: assign inside of the loop, so it's a new instance
                        formDetailsJson.put("host", currentOSVulnerability.getDest());
                        formDetailsJson.put("port", currentOSVulnerability.getList_of_ports().get(v));
                        formDetailsJson.put("open", currentOSVulnerability.isOpen());
                        formDetailsJson.put("info", currentOSVulnerability.getInfo());
                        jsonArray.add(formDetailsJson);
                        total_hostNumber_OS++;
                    }
                } else {
                    formDetailsJson = new JSONObject();
                    formDetailsJson.put("host", currentOSVulnerability.getDest());
                    formDetailsJson.put("port", currentOSVulnerability.getPorts___port());
                    formDetailsJson.put("open", currentOSVulnerability.isOpen());
                    formDetailsJson.put("info", currentOSVulnerability.getInfo());
                    jsonArray.add(formDetailsJson);
                    total_hostNumber_OS++;
                }
            }
            responseDetailsJson.put("data", jsonArray);
            System.out.print("\n list size: " + list_of_OS_VulnerabilityOS.size());
            System.out.print("\n total of OS-host to be send : " + total_hostNumber_OS);
        }
        return responseDetailsJson;
    }

A:  public JSONObject parse_OS_Vuln_data_to_Json() {
    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    if (list_of_OS_VulnerabilityOS.size()>0)
    {
        for (int i = 0; i < list_of_OS_VulnerabilityOS.size(); i++) {
            JSONObject formDetailsJson = null; // change #1
            if (list_of_OS_VulnerabilityOS.get(i).getList_of_ports().size() > 1)
            {
                for (int v = 0; v < list_of_OS_VulnerabilityOS.get(i).getList_of_ports().size(); v++)
                {
                    formDetailsJson = new JSONObject();  // change #2
                    formDetailsJson.put("host", list_of_OS_VulnerabilityOS.get(i).getDest());
                    formDetailsJson.put("port", list_of_OS_VulnerabilityOS.get(i).getList_of_ports().get(v)); // i got each time different port
                    formDetailsJson.put("open", list_of_OS_VulnerabilityOS.get(i).isOpen());
                    formDetailsJson.put("info", list_of_OS_VulnerabilityOS.get(i).getInfo());
                    jsonArray.add(formDetailsJson); // here it overwrites to the first port again
                    total_hostNumber_OS++;
                }
            } else {
                formDetailsJson = new JSONObject();  // change #3
                formDetailsJson.put("host", list_of_OS_VulnerabilityOS.get(i).getDest());
                formDetailsJson.put("port", list_of_OS_VulnerabilityOS.get(i).getPorts___port());
                formDetailsJson.put("open", list_of_OS_VulnerabilityOS.get(i).isOpen());
                formDetailsJson.put("info", list_of_OS_VulnerabilityOS.get(i).getInfo());
                jsonArray.add(formDetailsJson);
                total_hostNumber_OS++;
            }
    }
        responseDetailsJson.put("data", jsonArray);
        System.out.print("\n list size: " + list_of_OS_VulnerabilityOS.size());
        System.out.print("\n total of OS-host to be send : " + total_hostNumber_OS);

    }
    return responseDetailsJson;
}

In the #2 for loop, you are using the same formDetailsJson object. So each time the loop runs, your formDetailsJson object would be overwrited.


text:
Q: sencha touch modern developer mobile terminal, textfield display exception The development of the mobile terminal landing interface, the runtime found that the text input box display abnormal. If you put the code in toolbar to show no problem, the house ah formPanel shows weird, the effect is as follows
enter image description here
mycode:
Ext.define('GasApp.view.main.login.Login',{
    extend : 'Ext.form.Panel',
    xtype : 'loginView',
    requires: [
        'Ext.field.Password',
        'Ext.Button',
        'Ext.field.Toggle',
        'Ext.layout.HBox',
        'Ext.Toast',
        'GasApp.view.main.login.Controller'
    ],
    alternateClassName: 'loginView',
    controller : 'loginCtrl',
    listeners: {
        initialize: 'onLoginInitialize'
    },
    config:{
        padding: '40 30 0 30',
        items: [{
            xtype: 'textfield',
            name: 'account',
            ui : 'text_',
            label: '账号',
            clearIcon:true,
            required: true
        },{
            xtype: 'passwordfield',
            name: 'password',
            label: '密码',
            required: true
        },{
            items: [{
                xtype: 'togglefield',
                name: 'persist',
                label: '记住我',
                labelTextAlign: 'right',
                labelAlign: 'left',
                value: true
            }]
        },{
            xtype: 'button',
            width: '100%',
            text: '登   陆',
            ui: 'action',
            listeners: {
                tap: 'onLoginClick'
            }
        }]
    }
});


text:
Q: urlpatterns don't get updated after DB insertion? I'm having an html form which inserts data into one table called srv.
I've built the urls.py in such a way to capture every insertion:
for item in srv.objects.all():
    linkSrv = item.loc.lower() + '/srv/' + item.subctg.lower() + '/' + item.title.lower()
    urlpatterns += patterns('',
    url(r'^' + linkSrv + '/$', 'beta.views.queryFromIndexDeep'),
)

After the one insertion is being made, e.g. loc='loc', subctg='subctg' and title='title'
if i point my browser to 127.0.0.1:8000/loc/srv/subctg/title/ i get the http404 error (no matching url)
If I 'force-save' the urls.py (vim urls.py then :x! ) - after loc,subct,title were inserted - then I can successfully access 127.0.0.1:8000/loc/srv/subctg/title/
Anyone can shed some light? It looks like the urlpatterns need to be 'updated' each time a row is insterted in srv table.

A: You should just use something like this:
urlpatterns += patterns('',
    url(r'^(?P<loc>\w+)/(?P<subctg>\w+)/(?P<title>\w+)/$',
                         'beta.views.queryFromIndexDeep'),
)

Using regular expressions to match your view is way easier, and recommended. In your view, the above would match a function defined like beta.views.queryFromIndexDeep(request, loc, subctg, title), from where you can continue to work with these variables to extract the relevant data from your defined models.

A: add a slugfield (unique) to your srv model and add a method to the model
def get_absolute_url(self):
    return /yourapp/%s/ % self.slug

Then in urls use a pattern to match this
url(r'^srv/(?P<slug>[-\w]+)/$', yourgenericview),

Look into the django slugify snippit for fun http://djangosnippets.org/snippets/690/


text:
Q: LNK2001: unresolved external symbol when building for x64 platform The project builds on Win32 platform, but not on x64.
Full error message:
dllentry.obj : error LNK2001: unresolved external symbol "class CFactoryTemplate * g_Templates" (?g_Templates@@3PAVCFactoryTemplate@@A)
The dllentry.cpp compiles on both platforms. It contains the external declarations:
extern CFactoryTemplate g_Templates[];
extern int g_cTemplates;

g_Templates[] is then used in two functions:
__control_entrypoint(DllExport) STDAPI DllGetClassObject(__in REFCLSID rClsID,
    __in REFIID riid, __deref_out void **pv)
{
    ...
    for (int i = 0; i < g_cTemplates; i++)
    {
        const CFactoryTemplate * pT = &g_Templates[i];
    }
}

and
DllInitClasses(BOOL bLoading)
{
    ...
    for (int i = 0; i < g_cTemplates; i++)
    {
        const CFactoryTemplate * pT = &g_Templates[i];
    }
}

I checked all the libraries in the project settings and all seems to be OK, the 64 bit versions are used. What should I do to make the project build for x64 platform?

A: You stated in a comment to an earlier answer

The other, valid definition, is in myClass.cpp (main class of my
  project) 'CFactoryTemplate* g_Templates=0;' followed by 'int
  g_cTemplates=0;' at the uppermost level in the file, just after the
  includes.

Your definition of of g_Templates is inconsistent with its declaration.
The declaration is
extern CFactoryTemplate g_Templates[];

This declares g_Templates as an array of CFactoryTemplate (of unknown size). But your definition of
CFactoryTemplates* g_Templates = 0;

defines it as a pointer to a CFactoryTemplate, which is not the same thing.
Therefore, you failed to provide a definition of g_Templates that matches the declaration, and the error message is correct.
You need to get the declaration and definition to agree. One way is to write
CFactoryTemplates g_Templates[1];

to create a definition that is consistent with the declaration. (Note that zero-length arrays are disallowed in C++, so instead we create an array of length 1 and ignore the element in it.)
Another is to change the declaration to
extern CFactoryTemplates* g_Templates;

A: The statement extern CFactoryTemplate g_Templates[]; does not actually define an array* named g_Templates; it simply states that one exists somewhere in the project. You are essentially telling the compiler "don't worry that you don't see this thing anywhere; when it comes time to link, you'll be able to find it in a different module." Except that apparently isn't true. Two possible reasons I can think of are (1) The file that contains the actual definition of g_Templates is not being included in the x64 build configuration, and (2) the definition, wherever it is, is surrounded with something like #ifdef x86.
To solve this, you'll need to locate the actual definition of g_Templates (maybe search for "CFactoryTemplate g_Templates[") and then determine why it is being omitted in the x64 build.

* Technically it is treated as a pointer here


text:
Q: Python multipart upload. Creates larger file at destination I have written a small CLI in python to handle multipart uploads to a flask server. When testing the process, I find that the 25MB file I am uploading creates a 42MB file on the server when completed?! Each chunk is almost double when it reaches the server.
CLI client code:
from requests_toolbelt.multipart.encoder import MultipartEncoder

#Open file
            with open(self.file_path, 'rb') as file:
                start = 0
                chunk_count = math.ceil(self.file_size / self.max_byte_length)
                print("Number of upload parts:", chunk_count)

                with alive_bar(chunk_count) as bar:
                    #for i in range(chunk_count):
                    while self.i < chunk_count:

                        if self.i >= chunk_count-1:
                            is_last_chunk = True

                        end = min(self.file_size, start + self.max_byte_length)
                        file.seek(start)
                        data = file.read(end)
                        start = end

                        print("Chunk size : {}".format(str(sys.getsizeof(data))))

                        multipart_data = MultipartEncoder(
                        fields={
                                # a file upload field
                                'data': data,
                                # plain text fields
                                'chunk_index': str(self.i+1),
                                'chunk_size' : str(sys.getsizeof(data)),
                                'chunk_count' : str(chunk_count),
                                'file_size' : str(self.file_size),
                                'resource_friendly_name': friendly_name,
                                'upload_id': str(self.upload_id)
                            }
                        )
                        # Set headers
                        headers = {
                        'Content-Type': multipart_data.content_type
                        }

                        #Make request to server
                        try:

                            response = requests.request("POST", self.api_url, headers=headers, data=multipart_data)

The chunk sizes logged by the CLI client are as follows:
on 0: Chunk size : 5242913
on 1: Chunk size : 10485793
on 2: Chunk size : 14685268
on 3: Chunk size : 9442388
on 4: Chunk size : 4199508

The chunk sizes logged by the server are as follows:
on 0: Chunk size : 10466998
on 1: Chunk size : 41801848
on 2: Chunk size : 29323520
on 3: Chunk size : 18865242
on 4: Chunk size : 8388424

I have no clue as to why each chunk size is so dramatically increased?

A: use:

data = file.read(end - start)

instead of:

data = file.read(end)

This will select the exact part of the file as required.


text:
Q: NSData to NSUrl and viceversa I am using multipeer connectivity to send files. When I send it I have it in form of NSData, but the method requires NSUrl, and the same when the file is received. The device receives the NSUrl and I have to convert it to NSData. So:
NSdata => NSUrl ........ NSUrl => NSData
For the first (NSData to NSUrl) I have tried this:
1)
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"sendData.xxxxxxx"];

    [myData writeToFile:filePath atomically:YES];
    NSURL *urlData = [NSURL fileURLWithPath:filePath];

    NSProgress *progress = [session sendResourceAtURL:urlData withName:@"Resource" toPeer:peerID withCompletionHandler:nil];

2)
NSURL* fileURL = [[NSURL alloc] init];
    [myData writeToURL:fileURL atomically:YES];

Finally I can send the url:
[session sendResourceAtURL:urlData withName:@"Resource" toPeer:peerID withCompletionHandler:nil];

For the second I do:
NSData* data = [NSData dataWithContentsOfURL:localURL options:NSDataReadingUncached error:&error];

...but sometimes the app crashes, and this happens when I try to send larger files. I think this is because the system takes time to writetofile, and anyway the whole process will take longer if I need to 'save' the file again. Is there a faster and more secure way??


text:
Q: Delte rows in a range based on a cell value I have a data on employees in the range Q6:V100. The data is not in table and the data consists of 6 columns(job title, duty, pay etc.) and based on the first column which is "Currently employed" I want to delete the row where the employee is not employed anymore (="").  The first column shows "O" if employed and ""(just a blank) if no  . This is the code I have tried. But it shows error message

"Autofilter method of range class failed"

and I have no idea what is wrong... It will grateful if someone can help !
Sub Delete_Rows_Based_On_Value()

Dim ws As Worksheet

  Set ws = ThisWorkbook.Worksheets("Trainings")
  ws.Activate

  'Clear any existing filters
  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0

  '1. Apply Filter
  ws.Range("Q6:V100").AutoFilter Field:=1, Criteria1:=""

  '2. Delete Rows
  Application.DisplayAlerts = False
    ws.Range("Q7:V100").SpecialCells(xlCellTypeVisible).Delete
  Application.DisplayAlerts = True

  '3. Clear Filter
  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0

End Sub

A: I would advise a more robust system, with a notation in Column Q stating:
1 = Employed,
0 = Not employed
Sub Delete_Rows_Based_On_Value()

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Trainings")
    ws.Activate

Dim i As Integer
Dim n as Integer

    n = ws.Range("Q6").CurrentRegion.Rows.Count

    For i = n + 5 To 6 Step -1
        If ws.Cells(i, 17).Value = 0 Then
            ws.Rows(i).Delete
        End If
    Next i

If you do not adapt the new system, change the If-statement to match your current system:
If ws.Cells(i, 17).Value = "" Then


text:
Q: Redis in-memory read replica of an RDS master I have a high traffic web service.
Each request SELECTs some data from an MSSQL RDS.
The relevant tables in the RDS are very small, update/inserts will only happen few times a day.
In order to minimize each request time, I wanted to have some sort of an in-memory read replica Redis that will store those table in some sort of a key-value structure that I'll define in advance.
And to make sure that every time an Update/Insert is done on the RDS, it will update the Redis.
This application runs on multiple linux instances, so I'll need to have a way to deploy it to all of them, and obviously to keep them sync.
1.Does it make sense? maybe I should take a different approach?
2.If it does, can anyone share how would I achieve such thing? Is there an implemented tool in MSSQL/Redis or do I have to write some sort of a third-party app for it? couldn't find anything similar online.
Thanks for reading!