text:
Q: How to dynamically import a file based on user input I'm writing an npm module and want to allow users to create a config file to control how the command line calls to this module run. How can I import this config file reliably? Ideally this should work in development using NPM link as well as in production.
Example file structure:
- project folder
  - node_modules
    - my_module
      - cli.mjs (Where the command line processing is running)
  - k.config.mjs

So, ideally, I want to reliably be able to import my.config.mjs if it exists. I've tried several ways of using the dynamic import. The most(?) successful has been:
const baseDir = process.cwd();
const configPath = path.resolve(baseDir,'./k.config.mjs');
const configURL = new URL(configPath);
const userOpts = import(configURL.pathname);
console.log('userOpts',userOpts);

This gives me an error though (using npm link):
TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module "\Git\Kurohyou_studios\inittest\k.config.mjs" is not a valid package name imported from E:\Git\Kurohyou_studios\k-scaffold\cli.mjs

So, what's the proper way for me to dynamically import this config file?


text:
Q: Is there a sufficient criterion to determine Lq convergence from Lp convergence (q>p)? I am wondering: If we have $p<q$ with $p,q \in [1, \infty)$ and a sequence $(f_n) \in L^p \cap L^q $ ,$(f_n) \rightarrow f \in L^p$ in $L^p$, what type of conditions are required to determine that $f_n \rightarrow f$ in $L^q$?
My thought process so far: First and foremost, one needs that $f \in L^q$ as well. Otherwise convergence in $L^q$ is not possible.
As a finite measure space implies the other direction I would assume that a finite measure space is also required. Are these two assumptions already sufficient? I am quite sure they arent, but I cannot come up with a counter example. I also tried proving that the claim is correct, but I dont see how one can approximate $|\cdot |_{L_q}$ with $|\cdot |_{L_p}$, as the first is generally bigger. Maybe it works with Holder, but I dont see how.
Any help is greatly appreciated!

A: A sufficient condition would be that $(f_n)$ is a bounded sequence in $L^{q+\epsilon}$ for some $\epsilon>0$. If $(f_n)$ is merely bounded in $L^q$, then at least $f_n \rightharpoonup f$ in $L^q$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Data organisation: How to transform time series to individual data I have a dataset of individuals at different time steps but I only have data entries when a change happens. So I have e.g. the takeover date of a territory but I want to know for each individual whether they were present or absent at a given time step.
  ID<-c("A","B","C","D","E")
    Takeover<-c(0,5,5,8,12)
    data<-data.frame(ID,Takeover)

So in this simplified data A was there in timesteps 1:4 and at timestep 5 B & C took over and stayed until timestep 8....
I then want to get an individual dataset that looks something like this

How do I organise my data?
However, I don't know how to this...


text:
Q: Dynamic of $SL_2(\mathbb{Z}$) on $\mathbb{C}^2$ I imagine the dynamic of $SL(2,\mathbb{Z}$) on $\mathbb{C}^2$ has been studied. Does one know if it is recurrent or ergodic (with respect to the Lebesgue measure) ? Is there any explicit description of the orbits ?
Thank you for your help,
Selim

A: The dynamics are ergodic with respect to Lebesgue measure. See

G. Hedlund, Fuchsian groups and mixtures, Ann. of Math. Volume 40, Number 2 (1939) 370-383, available here.

If you prefer something with modern terminology, I'd recommend

F. Ledrappier and M. Pollicott, Ergodic properties of linear actions of (2×2)-matrices, Duke Math. J. Volume 116, Number 2 (2003), 353-388, see here.

A: Since matrices from $SL(2,\mathbb Z)$ are real, the action on $\mathbb C^2$ is the same as the diagonal action on the product of two copies of $\mathbb R^2$. Now, the action of $SL(2,\mathbb Z)$ on $\mathbb R^2$ is well-known to be conjugate to its action on the space $H$ of horocycles in the hyperbolic plane $\mathbb H^2$. The ergodic properties of the latter action are the same as for the horocycle flow on the quotient surface.
A single horocycle is determined by a point on the boundary circle of $\mathbb H^2$ and a real parameter (the "radius" of the horocycle). Two horocycles therefore determine a geodesic in $\mathbb H^2$ (which joins the centers of these horocycles) and two points on this geodesic (where it intersects these horospheres). Therefore, the action of $SL(2,\mathbb Z)$ on $H^2$ is conjugate to the product of its action on the unit tangent bundle of $\mathbb H^2$ and the trivial action on $\mathbb R$. Finally, the action of $SL(2,\mathbb Z)$ on $U\mathbb H^2$ is obviously dissipative.
Thus, the answer is that the action of $SL(2,\mathbb Z)$ on $\mathbb C^2$ is dissipative,
and its ergodic components ($\equiv$ orbits) are parameterized by the product of the unit tangent bundle of the quotient surface and $\mathbb R$.
Actually, the above argument shows that the action is not just dissipative, but also properly discontinuous.
Edit: Sorry, in the original answer forgot about one more copy of $\mathbb R$.


text:
Q: Angular 2 Observable with multiple subscribers I have an angular 2 service that fetch data from an API
this service has 3 subscribers (defined in Components) each doing something else with the data (different graphs)
I'm noticing that I'm doing three GET requests to the API while what i want to achieve is one request and that the subscribers will share the data
I've looks into HOT and COLD observable and tried the .share() on the observable but I'm still doing 3 individual calls
Update, adding code

Service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import {Observable} from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { StationCompliance } from './model/StationCompliance';

@Injectable()
export class StationComplianceService {

  private url = '/api/read/stations';

  constructor(private http : Http) {
    console.log('Started Station compliance service');
   }

   getStationCompliance() : Observable<StationCompliance []> {
     return this.http.get(this.url)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
   }
}

Component 1

import { Component, OnInit } from '@angular/core';
import { CHART_DIRECTIVES } from 'angular2-highcharts';

import { StationComplianceService } from '../station-compliance.service';

@Component({
  selector: 'app-up-down-graph',
  templateUrl: './up-down-graph.component.html',
  styleUrls: ['./up-down-graph.component.css']
})
export class UpDownGraphComponent implements OnInit {

  graphData;

  errorMessage: string;

  options;

  constructor(private stationService : StationComplianceService) { }

  ngOnInit() {
    this.getStationTypes();
  }

  getStationTypes(){
    this.stationService.getStationCompliance()
      .subscribe(
        graphData => {
          this.graphData = graphData;
          this.options = {
            chart : {type: 'pie',
                    plotShadow: true
            },
            plotOptions : {
              showInLegend: true
            },
            title : {text: 'Up and Down devices'},
            series: [{
              data: this.processStationType(this.graphData)
            }]
          }
        },
        error => this.errorMessage = <any>error
      );
  }

Other two components are almost the same, they just show other graph

A: The issue that you have in your code is that you are returning a new observable each time your function is called.  This is because http.get is creating a new Observable each time it is called.  The way to solve this could be to store the observable (via closure) in the service which will ensure that all of the subjects are subscribing to the same observable. This isn't perfect code, but I had a similar issue and this solved my problem for the time being.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import {Observable} from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { StationCompliance } from './model/StationCompliance';

@Injectable()
export class StationComplianceService {

  private url = '/api/read/stations';

  constructor(private http : Http) {
    console.log('Started Station compliance service');
   }

   private stationComplianceObservable: Rx.Observable<StationCompliance[]>;

   getStationCompliance() : Observable<StationCompliance []> {

    if(this.stationComplianceObservable){
        return this.stationComplianceObservable;
    }

      this.stationComplianceObservable = this.http.get(this.url)
      .debounce(1000)
      .share()
      .map((res:Response) => res.json())
      .finally(function () { this.stationComplianceObservable = null})
      .catch((error:any) => Observable.throw(error.json().error || 'Server Error'));

    return this.stationComplianceObservable;
   }
}

A: I encountered a similar problem and solved it using Aran's suggestion to reference  Cory Rylan's Angular 2 Observable Data Services blog post.  The key for me was using BehaviorSubject.  Here's the snippets of the code that ultimately worked for me.

Data Service:

The data service creates an internal BehaviorSubject to cache the data once when the service is initialized.  Consumers use the subscribeToDataService() method to access the data.
    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';

    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    import { Observable } from 'rxjs/Observable';

    import { Data } from './data';
    import { properties } from '../../properties';

    @Injectable()
    export class DataService {
      allData: Data[] = new Array<Data>();
      allData$: BehaviorSubject<Data[]>;

      constructor(private http: Http) {
        this.initializeDataService();
      }

      initializeDataService() {
        if (!this.allData$) {
          this.allData$ = <BehaviorSubject<Data[]>> new BehaviorSubject(new Array<Data>());

          this.http.get(properties.DATA_API)
            .map(this.extractData)
            .catch(this.handleError)
            .subscribe(
              allData => {
                this.allData = allData;
                this.allData$.next(allData);
              },
              error => console.log("Error subscribing to DataService: " + error)
            );
        }
      }

      subscribeToDataService(): Observable<Data[]> {
        return this.allData$.asObservable();
      }

      // other methods have been omitted

    }

Component:

Components can subscribe to the data service upon initialization.
    export class TestComponent implements OnInit {
      allData$: Observable<Data[]>;

      constructor(private dataService: DataService) {
      }

      ngOnInit() {
        this.allData$ = this.dataService.subscribeToDataService();
      }

    }

Component Template:

The template can then iterate over the observable as necessary using the async pipe.
    *ngFor="let data of allData$ | async"

Subscribers are updated each time the next() method is called on the BehaviorSubject in the data service.

A: shareReplay should do it now - "(...) valuable in situations where you know you will have late subscribers to a stream that need access to previously emitted values."

A: you can create a reactive data service and define a local Observable variable which is updated internally and subscribers can update themselves.
this article explains it properly
data services

A: I know this thread is old, but the accepted answer helped me a lot and I would like to add some possible improvements using debounce, switchmap and a hacky global notification system (to do this proper ngrx should be used: https://ngrx.io/)
The premise of the concept is that a notification service can be used to push changed to all other services telling them to fetch their data:
export class NotifyerService {

  constructor() { }

  notifyer: Subject<any> = new Subject

  notifyAll() {
    console.log("ALL NOTIFIED")
    this.notifyer.next("GO")
  }

}

A subject is used, because calling .next(val) on a subject pushes the data to all listeners
In the service for a particular componenet (in your case "DataService") you can manage the data aquisition, and caching activity:
export class GetDataService {

  // cache the incoming data
  cache: Subject<any> = new Subject

  constructor(private http: HttpClient,
    private notifyerService: NotifyerService) {

    // subscribe to any notification from central message broker
    this.notifyerService.notifyer.pipe(

      // filtering can be used to perform different actions based on different notifications
      filter(val => val == "GO"),

      // prevent notification spam by debouncing
      debounceTime(300),

      // SUBSCRIBE to the output of getData, cancelling previous subscription
      switchMap(() => this.getData())

    ).subscribe(res => {

      console.log("expensive server request")

      // save data in cache, notify listeners
      this.cache.next(res)
    })

  }

  // expensive function which gets data
  getData(): Observable<any> {
    return this.http.get<any>(BASE_URL);
  }

}

The key concept in the above code is that you setup a cache object, and update it whenever there is a notification. In the constructor, we want to pipe all future notifications through a series of operators:

*

*Filtering can be used if you want to only update the cache if the
notification service outputs certain things (in this case "GO"). If
you start doing this, ngrx will almost certainly be used instead.

*debounceTime prevents your server being spammed with many requests (if say, the notifications are based on user input)

*switchMap is a super important operator for caching and state change. switchMap runs the function inside (in this case, the getData function) and subscribes to its output. This means that the output of switchMap will be the subscription to the server data.

*Another important feature of switchMap is that is cancels previous subscriptions. This means that if your server request has not returned before another notification arrives, it will cancel the old one and ping the server again.

Now after all of that, the server data will be placed in the cache with the .next(res) method.
Now all the final component needs to do is listen to the cache for updates, and handle appropriatly:
export class ButtonclickerComponent implements OnInit {

  value: any;

  constructor(private getDataService: GetDataService,
    private notifyerService: NotifyerService) { }

  ngOnInit() {

    // listen to cache for updates
    this.getDataService.cache.pipe(

      // can do something specific to this component if have multiple subscriptions off same cache
      map(x => x)

      // subsc
    ).subscribe(x => { console.log(x); this.value = x.value })

  }

  onClick() {

    // notify all components of state changes
    this.notifyerService.notifyAll()
  }

}

The concept in action:
Angular App on button click
Server response

A: The solution is save once created observable and make it shareable (by default it is not). So your service will look like:
@Injectable()
export class StationComplianceService {

  private stationCompliance: StationCompliance;
  private stream: Observable<StationCompliance []>;
  private url = '/api/read/stations';

  constructor(private http : Http) {
    console.log('Started Station compliance service');
   }

   getStationCompliance() : Observable<StationCompliance []> {
     /** is remote value is already fetched, just return it as Observable */
     if (this.stationComliance) {
       return Observable.of(this.stationComliance);
     }
     /** otherwise if stream already created, prevent another stream creation (exactly your question */
     if (this.stream) {
       return this.stream;
     }
     /** otherwise run remote data fetching */
     this.stream = this.http.get(this.url)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server Error'))
      .share(); /** and make the stream shareable (by default it is not) */
     return this.stream;
   }
}


text:
Q: Skip or delete line/row in CSV file if the line/row does not start with established character in c# This is my CSV file
this file is provided from externally resource and saved in csv format with pipeline separator and on this I have to work
||||||||||||||||||||||||||||||||||||||||||||||||||
|Table1|||||||||||||||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||||
N|IDI  |TEST|START DATE HOUR    |CAUSE|KIND|NUMB|NAMES|
1|10704|    |21/07/2020 15:05:54|L    |MT  |2786|NAV  |
2|10660|    |21/07/2020 09:27:31|L    |MT  |4088|PIS  |
values of names
values of names .|0|0|1|1|0|0||||
||||||||||||||||||||||||||||||||||||||||||||||||||
|Table2|||||||||||||||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||||
N|IDI  |TEST|START DATE HOUR    |END DATE HOUR      |LENGHT  |RETURNS         |CAUSE|KIND|NUMB|NAMES|
1|10710|    |21/07/2020 19:34:00|21/07/2020 20:19:09|00:45:09| -              |L    |MT  |7806|ACC  |
2|10708|    |21/07/2020 18:28:12|21/07/2020 18:28:13|00:00:01| -              |T    |MT  |2600|LIT  |
3|10700|    |21/07/2020 14:16:37|21/07/2020 15:19:13|01:02:36|21/07/2020 17:00|L    |MT  |4435|UHI  |
4|10698|    |21/07/2020 14:06:45|21/07/2020 14:07:22|00:00:37|-               |B    |MT  |5789|TYK  |
5|10674|    |21/07/2020 10:21:04|21/07/2020 10:44:41|00:23:37|21/07/2020 12:30|T    |MT  |6699|FGR  |
||||||||||||||||||||||||||||||||||||||||||||||||||

I need delete or skip these rows on csv file because the line not starting with number or N value or pipeline |
values of names
values of names .|0|0|1|1|0|0||||

this is my code behind in error

Index was out of range. Must be non-negative and less than the size of
the collection parameter name:index

if the line does not start with number or N value or pipeline |
int posNewColumn = 4;

string input = @"C:\Temp\SO\import.csv";
string output = @"C:\Temp\SO\out.csv";

string[] CSVDump = File.ReadAllLines(input);
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList();
foreach (List<string> line in CSV)
{
    if (line[1] == "Table2")
    {
        break;
    }
    line.Insert(posNewColumn, line[0] == "N" ? "LENGHT" : string.Empty);
    line.Insert(posNewColumn, line[0] == "N" ? "END DATE HOUR" : string.Empty);
}

File.WriteAllLines(output, CSV.Select(x => string.Join("|", x)));

if there is only one element in line ( as in the line values of names) i need skip or delete lines
Can you help me please?

A: So you want to skip all lines that start with a pipe?
List<List<string>> CSV = CSVDump
  .Where(x => !x.StartsWith('|'))
  .Select(x => x.Split('|').ToList()).ToArray();

So you want to keep anything that starts with a number, an N or a pipe?
List<List<string>> CSV = CSVDump
  .Where(x => x.Length > 0 && "0123456789N|".Contains(x[0]))
  .Select(x => x.Split('|').ToList()).ToArray();

In response to Steve's concerns about performance etc, perhaps the best route to go is:
int posNewColumn = 3;

string input = @"C:\Temp\SO\import.csv";
string output = @"C:\Temp\SO\out.csv";

using (var dest = File.CreateText(output))
{
    bool adjust = true;

    foreach (string s in File.ReadLines(input))
    {
        if(line.Length == 0 || !"0123456789N|".Contains(line[0]) //skip zero len or line not begin with number/pipe/N
          continue;

        string line = s; //copy enum variable so we can adjust it

        if(adjust)
        {
          string[] bits = line.Split('|');

          if(line.StartsWith("N"))
            bits[posNewColumn] += "|END DATE HOUR|LENGHT";
          else
            bits[posNewColumn] += "||";

          line = string.Join("|", bits);
        }

        if(line.StartsWith("|Table2")
          adjust = false;

        dest.WriteLine(line);
    }
}

This requires minimal memory and processing; we don't split every line needlessly, thousands of Lists are not created, we don't try to hold the whole file in memory; we just read lines in and maybe write them out, and maybe adjust them if we didn't encounter Table2
Note; I have written it but not debugged/tested it - it might have a typo or a minor logic error; treat it as pseudocode

A: In my opinion you are overcomplicating the problem trying to update the same line while you loop over the lines collection. A simple approach (given the small file size) is to use another list that contains only the 'approved' lines.
For example:
int posNewColumn = 4; // ???
string input = @"C:\Temp\SO\import.csv";
string output = @"C:\Temp\SO\out.csv";

List<string> outputLines = new List<string>();
foreach (string line in File.ReadLines(input))
{
    var parts = line.Split('|').ToList();
    if (parts.Count > 1)
    {
        if (parts[1] == "Table2")
        {
            break;
        }

        // Add here all the conditions that allow a line to be
        // written in the output file
        char c = parts[0][0];
        if(c == '|' || c == 'N' || char.IsDigit(c))
        {
           parts.Insert(posNewColumn, parts[0] == "N" ? "LENGHT" : string.Empty);
           parts.Insert(posNewColumn, parts[0] == "N" ? "END DATE HOUR" : string.Empty);
           outputLines.Add(string.Join("|", parts);
        }
    }
}
File.WriteAllLines(output, outputLines);

This solution includes also the part where you add the new text into the lines approved for the output. While using Linq resolves with a single line the inclusion check, then you need another loop (in addition to the implicit one required by Linq) to insert the text


text:
Q: Infinite Intersections in Topology I'm having trouble finding an example that a professor wants. The problem is as follows.

Find an example of a topological space $(X,\mathcal{T})$ with open sets $U_{i}\in\mathcal{T}$, $i\in\mathbb{N}$, such that $\bigcap_{i=1}^{\infty}U_{i}\notin\mathcal{T}$.

I see why this intersection must not be in the topology from the definition alone. However, I'm not sure how to construct an example. Would the collection $A=\left\lbrace\left(-\frac{1}{n},\frac{1}{n}\right)\:|\:n\in\mathbb{N}\right\rbrace$ or the collection $B=\{(-m,m)\:|\:m\in\mathbb{N}\}$ constitute an example in $(\mathbb{R},\mathcal{T}_{std})$?
Thanks in advance for any help!

A: In the def'n of a topology, the intersection of $finitely$ many open sets is open. Example $A$ is correct, as $\cap A=\{0\}$ is not open in the usual topology. But $B$ is not an example, as $\cap B=(-1,1)$ is open.

A: Another example that I find interesting:  take $\mathbb{R}$ with the cofinite topology.  In this topology, a set is open if its complement is finite (plus, of course, we throw in the emptyset and all of $\mathbb{R}$, since those are required by the definition of a topology).  For example, the set $(-\infty,0)\cup (0,\infty)$ is open in this topology.  It is not to hard to check that this is, actually, a topology.
Now, let $U_n = \mathbb{R} \setminus \{n\}$, with $n$ ranging over the integers.  Each $U_n$ is open, but the intersection,
$$ \bigcap_{n\in\mathbb{Z}} U_n = \mathbb{R} \setminus \mathbb{Z}, $$
is not a cofinite set, and is therefore not open.

A: Taking complements, "find an infinite sequence of open sets whose intersection is not open" is equivalent to "find an infinite sequence of closed sets whose union is not closed." In the usual topology of the real line, all finite sets are closed, and so every countable set is the union of an infinite sequence of closed sets. Therefore, it will suffice to find a countable set of real numbers which is not closed in the usual topology; for instance, the set of all rational numbers, or the set of all reciprocals of positive integers.


text:
Q: Ubuntu 12.04 LTS on Lenovo Ideapad u300s I want to buy a Lenovo Ideapad U300s Ultrabook.
Is it compatible with Ubuntu 12.04 LTS?
(Intel Core i7-2677M, 4GB, 256GB SSD)
Thanks!

A: If it were me I would say I don't know why it would have a problem. Testing the laptop with an Ubuntu LiveCD will give you an answer quickly. If you can test it in the place where you are buying the laptop great. If not, when it arrives test the laptop.
But there are a couple of issues still present (At least in 12.04).I have also added some links of some old posts and bugs (That affected 11.04 and 11.10) that you might want to check and the ones that affect 12.04:
http://ubuntuforums.org/showthread.php?t=1889596&page=6
(11.04 and 11.10 users. most problems were hardware problems and not Ubuntu)
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/974455
(Suggest to do a BIOS Firmware upgrade)
http://support.lenovo.com/en_US/research/hints-or-tips/detail.page?&DocID=HT073063
(BIOS upgrade)
http://www.linlap.com/lenovo_ideapad_u300s
(Users confirming problem with 12.04 (And other distros like Fedora)
In general there are 3 problems detected:

*

*Suspend/Resume does not work correctly.
(There is a fix for this already)

*Touchpad functionality is not working properly. Recognized as a generic PS/2 mouse.
(Fix for this is on it's way)

*Some keys like T or any of the Arrow keys do not work correctly. Although this problem is more related to a hardware problem by many users. There is even some that have fixed the problem by either upgrading their BIOS or draining the battery completely (Again, more related to hardware than a system since it also happens on Windows).
I would recommend to either, wait for 13.04 or apply 12.10. Any of this 2 will have less probability to have any of this 3 bugs. Also verify the keys when the laptop arrives just to check that all keys are working correctly. Then simply test Ubuntu using the LiveCD or LiveUSB. Will save you the trouble of installing it and getting any error (If any appear in your case. Remember the problems mentioned do not happen to all users, only some).
For some additional information here are 2 positive links:
Stuart Langridge testing the Lenovo U300s
(Several tips by Stuart)
Ubuntu Friendly with the Lenovo U310
(Could not find the U300s)

A: Using Ubuntu on a Lenovo ideapad U300s has still this serious bug active:
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/974455
This bug causes some keys to permanently send other keys codes after using the machine for a while. Once the problem happens, the keyboard malfunction affects also the BIOS screen and any other OS installed. The ultrabook works fine on Windows (the only OS supported by Lenovo for this model) and once the bug appears (that only happens on Linux) it also affects the Windows instalation.
The only way to reset the keyboard back is to fully uncharge the battery or open the ultrabook's lid and disconnect it. So the problem exists because of an incorrect hardware support on Linux, and AFAIK no one is solving it right now. I'll buy another brand next time and i don't recommend this Lenovo ultrabook to anyone.

A: I have a a brand new Lenovo idea pad u410 and Ubuntu 12.04 is working now for me.  I'm new too, but from what I've learned so far, check into the graphics card on it.
I have a Nvidia GE610M and it is not recognized by Ubuntu....yet.  This is my challenge for today.  Not sure if you are new well, but if so, I would also recommend schooling yourself before hand on the installation process to make sure it goes nice and smooth the first time.  Wasn't so for me and although I have learned a great deal, it has taken some time.  Good luck!


text:
Q: clearInterval inside callback in ClojureScript Basically, what I want is to implement this piece of code in ClojureScript:
var win = window.open('foo.html', 'windowName');
var timer = setInterval(function() {
    if(win.closed) {
        clearInterval(timer);
        alert('closed');
    }
}, 1000);

I tried this:
(let [popup (.open js/window "foo.html" "windowName")
      interval (.setInterval
                js/window
                (fn []
                  (when (.-closed popup)
                    (do
                      ;; 'interval' is undefined at this point
                      (.clearInterval js/window interval)

                      (.alert js/window 'closed')))
                1000)]
...)

but CLJS compiler gives me a warning that interval is not defined.
Any ideas?

A: The issue is that you access interval local binding in your anonymous function before that binding has been defined (right hand side has to be evaluated first before it gets bound to interval symbol and until then interval is not defined.
You might workaround it by defining an atom storing your interval and access it from your callback function:
(let [popup (.open js/window 'foo.html', 'windowName')
      interval (atom nil)]
  (reset! interval (.setInterval
                    js/window
                    (fn []
                      (when (.-closed popup)
                        (do
                          (.clearInterval js/window @interval)
                          (.alert js/window "Closed")))))))

I am not sure if there is a more elegant way to achieve it using your approach with an interval callback.

A: Use of an atom

*

*is easy

*and is included within ClojureScript's core functionality

however interval being an atom may not clearly convey its actual nature and intent.
The original issue was the compiler's complaint that interval was not defined. So what is needed is a value that:

*

*can be defined first and

*resolved (delivered) later
That sounds like a promise to me. As of ClojureScript 1.8.34 Clojure promises aren't supported yet. Because of the existence of core.async there are indications that support of Clojure's promise isn't an urgent priority in ClojureScript - especially as core.async contains promise-chan. With promise-chan the code could be written as follows
(ns test.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [cljs.core.async :refer [<! close! promise-chan put!]]))

(let [interval (promise-chan)
      fooWin (.open js/window "./foo.html", "windowName")
      checkOnFooWin
        (fn []
          (when (.-closed fooWin) ;; when has an implicit do
            (go
              (.clearInterval js/window (<! interval)))
            (.alert js/window "Closed")))]
  (put! interval (.setInterval js/window checkOnFooWin 500))
  (close! interval))

This code is neither easier nor more elegant than the atom version - however it does have the advantage that

*

*interval can only be resolved once

*each and every value taken from interval will always be the initially delivered value.

A: Another way is to use direct js interop:
(let [popup (.open js/window "foo.html" "windowName")]
  (js* "var interval = setInterval(function() {
          if (popup.closed) {
            clearInterval(interval);
            alert('close');
          }
        }, 500);")

    ...)


text:
Q: cxgrid expand grouped data using cxDateEdit My displayed data in the cxGrid is grouped by date (collapsed) .
Is there a way I can expand this grouped data "only" for a selected date using cxDateEdit for the occasion ?
Right now,all I could manage is to collapes or expand all data using buttons:
procedure TArchive.EXPANDClick(Sender: TObject);
begin
cxGrid1DBTableView1.ViewData.Expand(True);
end;

procedure TArchive.COLLAPSEClick(Sender: TObject);
begin
cxGrid1DBTableView1.ViewData.Collapse(True);
end;

I would like to expand the records only for the date displayed in the cxDateEdit. And possibly display a message if no data for the desired date was found.
Edit :
I have found a way to do this :
procedure TARCHIVE.cxDateEdit1PropertiesChange(Sender: TObject);
begin
with cxGrid1DBTableView1 do
  begin
    DataController.DataSource.DataSet.Locate('FOR_DATE',cxDateEdit1.Date,
    [loPartialKey]);
    ViewData.Records[DataController.FocusedRowIndex].Expand(True);
end;
end;

However I cant figure out how to flash a message if the date displayed in the cdDateEdit does not exist in the cxGrid.

A: Got it :
    procedure TARCHIVE.cxDateEdit1PropertiesChange(Sender: TObject);
    begin
    with cxGrid1DBTableView1 do
    begin
    if   DataController.DataSource.DataSet.Locate('FOR_DATE',cxDateEdit1.Date,
        [loPartialKey]) then begin
        ViewData.Records[DataController.FocusedRowIndex].Expand(True);
    end else begin
    ShowMessage('No entries for desired date.');
    end;
    end;
    end;


text:
Q: Auto adjusting image sizes in GridLayout? I have 12 images which I wish to display in a grid of 4 rows by 3 columns.
For this purpose I am using a GridLayout.
The images are of different sizes and I wish for them to be scaled so each fill a cell, something like weight in Linear Layout.
I've played with the ImageViews scaleType and  adjustViewBounds properties but have only succeeded by manually setting layout_width and layout_height.
Is this possible or should I adjust the sizes in advance? Is there a better way of achieving my goal with a different layout?
I am working with Android Studio 1.1.0, API 21.
Thank you!
activity_set_background.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ImagesGridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="4"
tools:context=".SetBackgroundActivity">

<ImageView
    android:id="@+id/background1"
    android:layout_gravity="start|top"
    android:scaleType="centerInside"
    android:adjustViewBounds="true"
    android:layout_rowSpan="1"
    android:layout_columnSpan="1"
    android:src="@drawable/bg1"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="0"
    android:layout_column="0" />

<ImageView
    android:id="@+id/background2"
    android:layout_gravity="left|top"
    android:src="@drawable/bg2"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="0"
    android:layout_column="1" />

<ImageView
    android:id="@+id/background3"
    android:layout_gravity="left|top"
    android:src="@drawable/bg3"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="0"
    android:layout_column="2" />

<ImageView
    android:id="@+id/background4"
    android:layout_gravity="left|top"
    android:src="@drawable/bg4"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="1"
    android:layout_column="0" />

<ImageView
    android:id="@+id/background5"
    android:layout_gravity="left|top"
    android:src="@drawable/bg5"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="1"
    android:layout_column="1" />

<ImageView
    android:id="@+id/background6"
    android:layout_gravity="left|top"
    android:src="@drawable/bg6"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="1"
    android:layout_column="2" />

<ImageView
    android:id="@+id/background7"
    android:layout_gravity="start|top"
    android:scaleType="centerInside"
    android:adjustViewBounds="true"
    android:layout_rowSpan="1"
    android:layout_columnSpan="1"
    android:src="@drawable/bg7"
    android:layout_row="2"
    android:layout_column="0"
    android:layout_width="124dp"
    android:layout_height="123dp" />

<ImageView
    android:id="@+id/background8"
    android:layout_gravity="left|top"
    android:src="@drawable/bg8"
    android:layout_width="131dp"
    android:layout_height="108dp"
    android:layout_row="2"
    android:layout_column="1" />

<ImageView
    android:id="@+id/background9"
    android:layout_gravity="left|top"
    android:src="@drawable/bg9"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="2"
    android:layout_column="2" />

<ImageView
    android:id="@+id/background10"
    android:layout_gravity="left|top"
    android:src="@drawable/bg10"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="3"
    android:layout_column="0" />

<ImageView
    android:id="@+id/background11"
    android:layout_gravity="left|top"
    android:src="@drawable/bg11"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="3"
    android:layout_column="1" />

<ImageView
    android:id="@+id/background12"
    android:layout_gravity="left|top"
    android:src="@drawable/bg12"
    android:layout_width="118dp"
    android:layout_height="97dp"
    android:layout_row="3"
    android:layout_column="2" />

A: See https://stackoverflow.com/a/14881357/2680254 .
public class SquareImageView extends ImageView
{

public SquareImageView(final Context context)
{
    super(context);
}

public SquareImageView(final Context context, final AttributeSet attrs)
{
    super(context, attrs);
}

public SquareImageView(final Context context, final AttributeSet attrs, final int defStyle)
{
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
    final int width = getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
    setMeasuredDimension(width, width);
}

@Override
protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh)
{
    super.onSizeChanged(w, w, oldw, oldh);
}

}

A: As per My idea, You Can Use Relative and Linear Layout For display Imageview and set its mergin or padding with diffrent style from values folder for supported size of devices,set below code with imageview
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
    android:id="@+id/first"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="3" >

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"

        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
</LinearLayout>
<LinearLayout
    android:id="@+id/second"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/first"
    android:weightSum="3" >

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
</LinearLayout>
<LinearLayout
    android:id="@+id/third"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/second"
    android:weightSum="3" >

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
</LinearLayout>
<LinearLayout
    android:id="@+id/fourth"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/third"
    android:weightSum="3" >

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:text="1" />
</LinearLayout>


text:
Q: perl script to read an xlsx file(which has many sheets) using the sheet name I am trying to write a perl script which reads an excel file(which has many sheets in it)  using the sheet name.
I know how to access a particular sheet of the excel file using the sheet number, but not sure how to read it using sheet name.
Any help provided is highly appreciated.
Below is the code I wrote to access the sheet using sheet number:
my $Sheet_Number = 26;
my $workbook = ReadData("<path to the excel file>");

for (my $i =2; $i<$limit; $i++){
    my $cell = "A" . $i;
    my $key_1 = $workbook->[$Sheet_Number]{$cell};
}

Thanks
----Edit----
I want to open the particular sheet within the Excel file by using the sheet name. And then read the data from that particular sheet. The name of the sheet will be entered by the user while running the script from the command line arguments.
Below is the code that I am using after getting suggested answers for my earlier question:
my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse("$path");
my $worksheet;
if ($worksheet->get_name() eq "$Sheet_Name"){
for (my $i =2; $i<$limit; $i++){
    my $cell = $worksheet->get_cell($i,"A");
    my $value = $cell->value();
    push @array_keys, $value;
    }
}

I want to read the values of Column A of the particular sheet and push it into an array.
$Sheet_Name : It is the name of the sheet which is entered by the user as cmd line arg.
$path : It is the complete path to the Excel file

Error Message: Can't call method "get_name" on an undefined value at perl_script.pl (The error points to the line where the if-condition is used.)
Thanks for the help.
-----EDIT----
Anyone, with any leads on this post, please post your answer or suggestions. Appreciate any responses.
Thanks

A: The get_name() method of the worksheet object, in conjunction with Perl's grep command should get you this:
my ($worksheet) = grep { $_->get_name() eq 'Sheet2' } $workbook->worksheets();

This would be an un-golfed version of the same:
my $worksheet;
foreach $worksheet ($workbook->worksheets()) {
  last if $worksheet->get_name() eq 'Sheet2';
}

Assuming there is a match...  if not, I guess my un-golfed version would give you the last worksheet if there was no match.
-- Edit --
I made assumptions and -- you certainly do need to first call the method to load the workbook:
use strict;
use Spreadsheet::ParseExcel;

my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('/var/tmp/foo.xls');

Then the code above should work.


text:
Q: Rust Mutex is not working when using a callback function from multiple C threads created by `fork` I am using the C library Cuba which uses a callback function that is called from multiple threads created in C. The Cuba parallelization is based on the fork/wait POSIX functions instead of pthreads (arxiv.org/abs/1408.6373). It gives the current thread in the core parameter.
I am trying to log results from this callback function to a screen and a file. If I use println! I get expected output, but if I use slog the output is mangled when I use a Mutex drain. If I use the async drain I get no output at all.
Is the Mutex not locking since it can't see the function is actually called from another thread? I tried to recreate the problem with Rust threads, but couldn't. Preferably I'd like to get the async drain to work.
Below is an example program that gives the problematic behaviour. The callback gets the last parameter of the vegas function as one of its arguments. This is a vector of clones of loggers. This way, each core should have its own copy of the logger:
#[macro_use]
extern crate slog;
extern crate cuba;
extern crate slog_term;

use slog::Drain;

// this function is called from different c threads
// `core` indicates which thread
fn integrand(
    _x: &[f64],
    _f: &mut [f64],
    loggers: &mut Vec<slog::Logger>,
    _nvec: usize,
    core: i32,
) -> Result<(), &'static str> {
    info!(loggers[core as usize], "A\nB\nC");

    Ok(())
}

fn main() {
    let decorator = slog_term::TermDecorator::new().build();
    let drain = slog_term::CompactFormat::new(decorator).build();
    let drain = std::sync::Mutex::new(drain).fuse();

    let log = slog::Logger::root(drain, o!());

    let mut integrator = cuba::CubaIntegrator::new(integrand);
    integrator.set_cores(10, 1000); // set 10 cores

    integrator.vegas(
        1,
        1,
        cuba::CubaVerbosity::Progress,
        0,
        vec![log.clone(); 11],
    );
}

Output:
C
INFO Mar 26A
B
C 10:27
:42.195 MarINFO 26  10:27A
B
C:42.195
 MarINFO 26  10:27A
B
C:42.195
 INFO A
B
C
Mar 26 10:27:42.196 INFO A
B
C
Mar 26 10:27:42.196 INFO A
B
C

A: The Cuba C library has this to say:

Windows users: Cuba 3 and up uses fork(2) to parallelize the execution threads. This POSIX function is not part of the Windows API, however, and is furthermore used in an essential way such that it cannot be worked around simply with CreateProcess etc. The only feasible emulation seems to be available through Cygwin.

Here's a reproduction of the code. We fork and then the child and the parent attempt to hold the mutex while printing stuff out. A sleep is inserted to encourage the OS scheduler to try other threads:
use nix::unistd::{fork, ForkResult}; // 0.13.0
use std::{sync::Mutex, thread, time::Duration};

fn main() {
    let shared = Mutex::new(10);

    match fork() {
        Ok(ForkResult::Parent { .. }) => {
            let max = shared.lock().unwrap();
            for _ in 0..*max {
                println!("Parent");
                thread::sleep(Duration::from_millis(10));
            }
        }
        Ok(ForkResult::Child) => {
            let max = shared.lock().unwrap();
            for _ in 0..*max {
                println!("Child");
                thread::sleep(Duration::from_millis(10));
            }
        }
        Err(e) => {
            eprintln!("Error: {}", e);
        }
    }
}

$ cargo run

Parent
Child
Parent
Child
Child
Parent
Child
Parent
Child
Parent
Child
Parent
Child
Parent
Child
Parent
Child
Parent
Child
Parent

Using fork with threads is really a pain to deal with; I distinctly remember hunting down terrible problems related to this before. Two resources I found that go in depth:

*

*Mutexes And fork()ing In Shared Libraries

*Synchronization, Part 1: Mutex Locks
The latter says (emphasis mine):

Can I create mutex before fork-ing?
Yes - however the child and parent process will not share virtual memory and each one will have a mutex independent of the other.
(Advanced note: There are advanced options using shared memory that allow a child and parent to share a mutex if it's created with the correct options and uses a shared memory segment. See procs, fork(), and mutexes)

If I use the async drain I get no output at all.

See also:

*

*Why doesn't a lazy_static slog::Logger print until a non-static logger is used?

I would not trust the Cuba Rust library. There are two main points:

*

*If there are threads being created, the user data generic type should have either a Sync or Send bound on it, restricting to only types that are safe to share / transfer the data between threads.

*The user data passed to the integrand function should not be a &mut. A fundamental Rust concept is that there can only be a single mutable reference to any piece of data at any time. Cuba trivially allows you to circumvent this.
Here's an attempted reproduction of the Cuba Rust and C libraries:
#[macro_use]
extern crate slog;

use slog::Drain;

fn integrand(loggers: &mut Vec<slog::Logger>, core: i32) {
    info!(loggers[core as usize], "A\nB\nC\n{}", core);
}

fn main() {
    let decorator = slog_term::TermDecorator::new().build();
    let drain = slog_term::CompactFormat::new(decorator).build();
    let drain = std::sync::Mutex::new(drain).fuse();

    let log = slog::Logger::root(drain, o!());

    let logs = vec![log.clone(); 11];

    cuba_repro(logs, integrand);
}

use std::{ffi::c_void, thread};

type Integrand<T> = fn(&mut T, i32);

fn cuba_repro<T>(mut user_data: T, mut integrand: Integrand<T>) {
    // From the `vegas` method
    let user_data_ptr = &mut user_data as *mut _ as *mut c_void;
    let integrand_ptr = &mut integrand as *mut _ as *mut c_void;

    unsafe { cuba_repro_ffi::<T>(user_data_ptr, integrand_ptr) }
}

unsafe fn cuba_repro_ffi<T>(user_data: *const c_void, integrand: *const c_void) {
    let user_data = FfiDoesNotCareAboutSendOrSync(user_data);
    let integrand = FfiDoesNotCareAboutSendOrSync(integrand);

    let threads: Vec<_> = (0..4).map(move |i| {
        thread::spawn(move || {
            // C doesn't care about this pedantry
            let user_data = &mut *(user_data.0 as *const T as *mut T);
            let integrand = &mut *(integrand.0 as *const Integrand<T> as *mut Integrand<T>);

            // From the `c_integrand` function
            let k: &mut T = &mut *(user_data as *mut _);
            let _ignored = integrand(k, i);
        })
    }).collect();

    for t in threads { t.join().unwrap() }
}

#[derive(Copy, Clone)]
struct FfiDoesNotCareAboutSendOrSync<T>(T);
unsafe impl<T> Send for FfiDoesNotCareAboutSendOrSync<T> {}
unsafe impl<T> Sync for FfiDoesNotCareAboutSendOrSync<T> {}

I had to make numerous changes to get the Rust compiler to ignore the huge amount of unsafety and rule-breaking that the Cuba library and related FFI is performing.
This code example does actually print out 4 log statements each in order, so this is not a complete answer. However, I'm fairly certain that the Cuba library is triggering undefined behavior, which means that any outcome is possible, including apparently working.


text:
Q: Parse.com How to keep subscriptions channels between installations? For example if a user to "alpha", "beta", "gamma" channels uninstall the application and reinstall subscribe or erasing data from the application as I restore your subscriptions

A: You can save channels that a user subscribed on in a ParseUser object. Next time when the user will authorize, you can retrieve these channels and restore user's subscriptions.


text:
Q: verbose if condition " if not hasattr(self, '__total'):" I am following "Fluent Python" to learn Function and Design Pattern:
In chapter 6 example-code/strategy.py
class Order:  # the Context

    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion(self)  # <1>
        return self.total() - discount

    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())

I am very confused about:
    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

What's the purpose of if condition here? I guess it could be more readable if:
    def total(self):
        return sum(item.total() for item in self.cart)

What's the key point I missed? could you please provide any hints?

A: What happens if you call total more than once?  If self.cart hasn't changed, then you're needlessly recalculating the total, a potentially expensive operation.
You're checking if you've already stored the value.  If you haven't you calculate it, but if you have you simply return the stored value without recalculating.
As an aside, I would expect name mangling to make your life difficult here because of the double underscore at the beginning of __total.  You may want to consider switching to a single underscore.


text:
Q: How to block some Pages if in .txt file How to block (redirect) a Page if the Page is in a .txt file:
I have this snippet - the good news is the url in block.txt will be blocked (white Site) but i want it to redirect to /file-not-found.php
<?php
list($blockExist, $blockData) = array(false, null);

if (is_string($blockData = @file_get_contents('/block.txt'))) {
    $blockData = preg_replace('/\s+/', '', $blockData);
}

if (isset($_SERVER['REQUEST_URI'])) {
    $httpLink = explode('?', $_SERVER['REQUEST_URI']);
    $httpLink = $httpLink[0] == '/' ? null : $httpLink[0];
}

if ($blockData != null && $httpLink != null && stripos("{$blockData}http://", "{$httpLink}http://") !== false) {
    $blockExist = true;
}

if ($blockExist) {
    require_once dirname(__FILE__) . '/file-not-found.php';
    exit;
}
?>

A: Try this code..
//require_once dirname(__FILE__) . '/file-not-found.php';
header('Location: http://www.example.com/file-not-found.php');

Thank


text:
Q: UITextView Font Setting I am having a problem in UITextView. following is my code.
UITextView *txtDescription = [[UITextView alloc] initWithFrame:CGRectMake(15, 50, 290, 100)];
//txtDescription.font = [UIFont fontWithName:@"ArialMT" size:17.0];
txtDescription.delegate = self;
txtDescription.tag = 2;
//txtDescription.autocorrectionType = UITextAutocorrectionTypeNo;
txtDescription.layer.cornerRadius = 5.0;
UILabel *lblPlaceholder = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, 200, 30)];
//lblPlaceholder.text = @"Description (Required)";
//lblPlaceholder.textColor = [UIColor lightGrayColor];
//lblPlaceholder.font = [UIFont fontWithName:@"ArialMT" size:17];
[txtDescription addSubview:lblPlaceholder];
[scrollView addSubview:txtDescription];

when i am tring to set Font, AutocorrectionType or add any subview to my textview it is giving following error.
UIKit`-[UITextInteractionAssistant(UITextInteractionAssistant_Internal) selectionView]
Please have a look.
I am using same code for 2 months but from today it is giving this kind of error.
I am not getting any solution. Please help me.
Thank You in advance.

A: There's absolutely no reason for that code to crash. So I think the problem has to be elsewhere.
I've tried this and it doesn't crash for me:
UITextView *txtDescription = [[UITextView alloc] initWithFrame:CGRectMake(15, 50, 290, 100)];
[txtDescription setFont:[UIFont systemFontOfSize:20]];
[txtDescription setText:@"This is TEXT"];
[txtDescription setAutocorrectionType:UITextAutocorrectionTypeNo];
[self.view addSubview:txtDescription];

This also works:
txtDescription.font = [UIFont systemFontOfSize:50];
txtDescription.autocorrectionType = UITextAutocorrectionTypeNo;

Do you have the font?


text:
Q: Resque.. how can I get a list of the queues Ok.. On heroku I have up 24 workers (as I understand it)
I have say 1000 clients. Each with their own "schema" in a postgresql database.
each client has tasks that can be done "later".. sending orders to my companies back end, is a great example.
I was thinking that I could create a new queue for each client, and each queue would have it's own worker(process). That it seems isn't in the cards.
So ok.. my thinking now is to have a queue field in client record..
so client 1 through 15 are in queue_a
and client 16 through 106 are in queue_b.. ect  If one client is using heaps, we could move them to a new queue, or move others out of the slow Queue. clients with low volumns could be collected.. It would be a balancing act, but it wouldn't be all that hard to manage, if we kept track of metrics (which we will anyway)
(any counter ideas would be awesome to hear, I'm really in spit ball phase)
Right now, though. I'd like to figure out how to create a worker for each queue.
https://gist.github.com/486161 tells me how to create X workers, but doesn't really let me set a worker to a Queue. If I knew that, and how to get a list of queues, I think I'd be on my way to a viable solution to the limits.

Reading onhttp://blog.winfieldpeterson.com/2012/02/17/resque-queue-priority/
I realize that my plan is fraught with hardship.. The first client/queue to get added to the worker, would get priority.. I don't want that, I'd want them to all have the same.  As long as they are part of the same queue..

A: i just stick to the topic :)
getting all queues in resque is pretty easy
Resque.queues

is a list of all queue names, it does not include the 'failed' queue, i did something like this
(['failed'] + Resque.queues).each do |queue|
  queue_size = queue=='failed' ? Resque::Failure.count : Resque.size(queue)
end


text:
Q: Потерялся 1 бит в long double По следам вопроса о битовом представлении вещественных чисел и моего ответа на него.
Хочу программно для любого вещественного типа определить, сколько бит в нём отводится под мантиссу, а сколько под экспоненту. Для этого написал следующий код (в нём бит под знак считается отдельно от мантиссы, поэтому числа на 1 меньше):
https://ideone.com/YuIWNc - код на Си (float, double, long double)
https://ideone.com/342B4S - код на Си++ (float, double, long double)
https://ideone.com/VURQnw - код на Си++ (float, double, long double, __float128)
#include <cstdio>

template <typename typed> void count(unsigned *result_m, unsigned *result_e)
{
  typed x = 1, exp;
  unsigned res, e;
  for (res=0; x!=0; ++res) x/=2;
  for (exp=1,e=0; exp*2<res; ++e) exp*=2;
  *result_e = e+1;
  *result_m = res-exp+1;
}

int main(void)
{
  unsigned f_m, f_e, d_m, d_e, ld_m, ld_e, f128_m, f128_e;

  count<float>(&f_m, &f_e);
  count<double>(&d_m, &d_e);
  count<long double>(&ld_m, &ld_e);
  count<__float128>(&f128_m, &f128_e);

  printf("              S    M   E   SZ\n");
  printf("float:        1  %3u  %2u  %3u\n",    f_m,    f_e, 8 * sizeof(float));
  printf("double:       1  %3u  %2u  %3u\n",    d_m,    d_e, 8 * sizeof(double));
  printf("long double:  1  %3u  %2u  %3u\n",   ld_m,   ld_e, 8 * sizeof(long double));
  printf("__float128:   1  %3u  %2u  %3u\n", f128_m, f128_e, 8 * sizeof(__float128));
}

Получается так:
              S    M   E   SZ
float:        1   23   8   32
double:       1   52  11   64
long double:  1   63  15  128
__float128:   1  112  15  128

Для float, double и даже __float128 всё работает (Википедия, IEEE 754-2008).
А вот с long double возникают проблемы:

*

*1+63+15 = 79 - 79 бит. Вместо 80. Где ещё один бит?

*long double представляет собой 10-байтные числа, но sizeof вернул 16.
Как-то можно получить 10?

A: Один бит потерялся из-за того, что на платформе x86 80-битное плавающее значение имеет одно принципиальное отличие в представлении от 32- и 64-битных IEEE754 плавающих значений (float и double).
float и double используют представление с неявной ведущей единицей в мантиссе. То есть в нормализованном представлении старшая единица в мантиссе не хранится явно, а лишь подразумевается. А вот в расширенном 80-битном плавающем типе long double эта ведущая единица в мантиссе всегда хранится явно.
Из-за этого и возникает разница.
Для типов float и double ваш первый цикл сначала итерирует через нормализованные представления числа, в которых явная мантисса всегда равна нулю, а экспонента уменьшается от половины своего максимального значения (127 для float) до значения 1:
// Для `float`

// Нормализованные представления: мантисса равна 0, а экспонента убывает от 127 до 1

0x3F800000
...
0x00800000  <- после 126 делений

После этого ваш цикл продолжает итерировать через денормализованные представления числа, в которых экспонента равна 0, а по мантиссе вправо движется одинокая единица. Когда эта одинокая единица вылетит за правый край мантиссы, x станет равен нулю и цикл завершится
// Денормализованные представления: экспонента равна 0, а мантисса состоит
// из движущейся вправо единицы

0x00400000
0x00200000
...
0x00000001
0x00000000  <- после 150 делений

Заметьте, в float и double единица в мантиссе возникает только в самом первом денормализованном значении и проходит через все биты мантиссы. Получается, что количество денормализованных ненулевых значений в этом случае равно количеству битов в мантиссе.
Однако при использовании long double единица в старшем бите мантиссы явно присутствовала всегда, с самого начала. Когда в вашем цикле экспонента long double достигает нуля и цикл начинает подсчитывать денормализованные значения long double, единица в мантиссе не возникает "из никуда" в старшую позицию мантиссы (как это было в в float и double), а уже присутствует в старшей позиции изначально и "стартует" именно оттуда. Из-за этого та часть цикла, которая считает денормализованные значения, делает на одну итерацию меньше.

Кстати, странная манера складывать в одну сумму - res - половину диапазона экспоненты и ширину мантиссы чревата проблемами. Вы потом вычисляете значение log2 res и ожидаете, что эта величина будет правильно описывать количество битов в экспоненте. Однако если в некотором гипотетическом плавающем типе мантисса окажется очень широкой, то величина log2 res может оказаться ошибочной.

A: Справка по C/C++ сообщает удивительную подробность:

long double — тип с плавающей точкой повышенной точности. Не
  обязательно отображается на типы IEEE-754. Обычно 80-битный тип с
  плавающей точкой формата x87 на архитектурах x86 и x86-64.

Получается, ответственность за реализацию лежит целиком на компиляторе.
Чтобы проверить, куда и какой бит делся, можно добавить распечатку в процесс "обнаружения" всех бит:
#include <cstdio>
#include <cstring>
#include <cinttypes>

template <typename typed> void count(unsigned *result_m, unsigned *result_e)
{
  typed x = 1, exp;
  unsigned res, e;
  std::uint32_t bytes[4] {0,0,0,0};
  for (res=0; x!=0; ++res) {
    x/=2;
    std::memcpy(bytes, &x, sizeof(typed));
    printf("x(%3d): %08x %08x %08x %08x\n", res, bytes[0], bytes[1], bytes[2], bytes[3]);
  }
  for (exp=1,e=0; exp*2<res; ++e) exp*=2;
  *result_e = e+1;
  *result_m = res-exp+1;
}

int main(void)
{
  unsigned f_m, f_e, d_m, d_e, ld_m, ld_e;

  count<float>(&f_m, &f_e);
  count<double>(&d_m, &d_e);
  count<long double>(&ld_m, &ld_e);

  printf("              S   M   E   SZ\n");
  printf("float:        1  %2u  %2u  %3u\n",  f_m,  f_e, 8 * sizeof(float));
  printf("double:       1  %2u  %2u  %3u\n",  d_m,  d_e, 8 * sizeof(double));
  printf("long double:  1  %2u  %2u  %3u\n", ld_m, ld_e, 8 * sizeof(long double));
}

Так, например, для 32-битного числа:
x(  0): 3f000000
x(  1): 3e800000
x(  2): 3e000000
x(  3): 3d800000
...с номера 126 наступает денормализация:
x(124): 01000000
x(125): 00800000
x(126): 00400000
x(127): 00200000
x(128): 00100000
x(129): 00080000
x(130): 00040000
...и далее перебор заканчивается:
x(147): 00000002
x(148): 00000001
x(149): 00000000

Где бит пропал - там и заковыка. Аналогично будут видны все незадействованные биты, и так можно оценить эффективный размер типа.
Продолжение для long double:
x(    0): 00000000 80000000 00003ffe 00000000
x(    1): 00000000 80000000 00003ffd 00000000
x(    2): 00000000 80000000 00003ffc 00000000
x(    3): 00000000 80000000 00003ffb 00000000
...денормализация:
x(16379): 00000000 80000000 00000003 00000000
x(16380): 00000000 80000000 00000002 00000000
x(16381): 00000000 80000000 00000001 00000000
x(16382): 00000000 40000000 00000000 00000000
x(16383): 00000000 20000000 00000000 00000000
...
x(16410): 00000000 00000004 00000000 00000000
x(16411): 00000000 00000002 00000000 00000000
x(16412): 00000000 00000001 00000000 00000000
x(16413): 80000000 00000000 00000000 00000000
x(16414): 40000000 00000000 00000000 00000000
...финал:
x(16443): 00000002 00000000 00000000 00000000
x(16444): 00000001 00000000 00000000 00000000
x(16445): 00000000 00000000 00000000 00000000

Итак, один бит действительно всегда выставлен в 1 для нормальных чисел, в соответствии с английской википедией на тему Extended Precision - и становится 0 после денормализации. В "стандартных" 32-битных и 64-битных представлениях этот бит опускается


text:
Q: time series with error bounds at lower level than "series" I have what I think is a very basic question but I am greatly struggling with knowing what model to use and where to start, and all help would be appreciated.
Basically I have a dataset that is a panel dataset.  Whenever a home is sold it is added into this dataset with it's sale date and sale price.    Therefore my dataset is every home sold in the united states and the price of that home by month.
My main metric is taking an average of the sales price by Time period (End of months value, so 2/28 3/31 etc.. Any dates that fall in February will roll into 2/28, etc..).  I would like to be able to forecast the Next Months sales price and the distribution of this sales price.
So basically I want something similar to a time series model on the 'aggregate' national house price.  However I have the underlying "home" level information that makes up the national average.
[B]My question is:[/B]  Would i ignore the underlying 'homes' breakout and just do a regular time series model on the aggregate index 'average home price by Time'?    I feel like doing things this way would be throwing away meaningful data.
The end goal is to take this 'forecast' and plug it into a model that has this variable (among others) as inputs.  Some of the other variables would also need to be forecast (such as taxes paid, hoa/fees, etc..).  my final model might look like.
avg(Total profit)=Avg(house price) - Avg(taxes) - Avg(hoA)..  This brings me to my second question.
dist(total Profit) = Defined as below.
[B]Second Question:[/B]  If a time series model (or whatever model) is the best way to go, how do I get the Distribution of each forecasted variable?  I don't just need the point estimate, I also need the bands it can be in and the likelihood of those bands (it's actual distribution).
I need this information because I don't just want a point estimate of the Total Profit. I actually want to give a distribution of the total profit, which itself is a random variable that comes from the 3 other forecasted 1 month values (which themselves have "reasonable bounds").
If anyone has any questions or I am not being clear please let me know!
Thanks


text:
Q: I have known from various sources that I can not import .dll file in Windows Phone 7 project. So what are the other ways to achieve my objective I am developing a live Windows Phone app.I have to encrypt my data to post it on server through a third party .dll file which was written in C++.
I have known from various sources that I can not import .dll file in Windows Phone 7 project.
So what are the other ways to achieve my objective.
Moreover,how it wolud be helpful for me if I have the source code of that .dll file.
great thanks!

A: You absolutely can reference dll files, but not of every type. It has to be a class library made for Windows Phone or a Portable Class Library (this one can be used by different platforms).
Indeed, having the source code would be helpful, you could implement the encryption and make an own class library.
Edit:
Andy Dent described a theoretical way to use C++ library in Windows Phone projects in this post. It is possible but not very comfortable as most of the C++ code will throw an exception: Operation could destabilize the runtime.
Another way would be to rewrite the code in C#, but that would mean to write nearly everything of the logic again.
Note: If you would write an application for Windows Phone 8 you could use C++ references without that problems. Have a look at this article.


text:
Q: Is there any python-based (or with api) library or tool (or repo) to index YAML-based config files with support for queries? We have an experimentation tool that uses YAML config files to run experiments and deploy models. We made this choice some time ago to integrate better with a Kubernetes orchestration.
Right now, we have hundreds of historical experiments, and we are stuck with trying to index them for querying. I have seen several questions about converting YAML files to json for indexing, but we would like to keep them as YAML. I found this YAMLDB from this question before. However this has no support for querying and isn't tied to python, which we'd like for inter-operability.
Would anyone have pointers to any repos or packages or libraries that do this (or perhaps mongo extensions if they exist). In-progress/alpha code is also okay.
Thank you.


text:
Q: How to get the absolute path of asset folder? I have folder named 'auto' inside the assets folder. I am working on running php script.
Here I have given absolute path for run.php.
My question is how to call assets folder
 $phpScript = Helpers::joinPath(
            "C:\\xampp\\htdocs\\project_name\\assets\\auto\\task",
            "run.php "
        );

A: I'm not sure if there's an asset path helper, but you can use base_path('assets/foo/bar')

A: You can get the absolute path for files located in the public folder using :
$path = public_path("assets/auto/task/run.php")

A: In Laravel 5.8 (don't know same applies to 5.x) there's a helper method to get the asset folder:

// $url = 'http://project_name.com/asset/auto/task/run.php'

$url = asset('auto/task/run.php');

I'm not quite sure what you're trying to do, but your question is how to call assets folder. And the answer is to use the asset() helper.
This will generate the asset's url based on what you've assigned ASSET_URL to in the .env file.
You can read more in the documentation: https://laravel.com/docs/5.8/helpers#method-asset

A: $url = base_path('assets/auto/task/run.php')
use this hope helpful for you


text:
Q: Gemfile local path dependencies, dependencies I need to package a copy of Redmine with all gems in a named local path. Redmine requires a few gems:
gem "rails", :path => File.join('..', 'lib', 'gems', 'rails-3.2.14')
gem "jquery-rails", :path => File.join('..', 'lib', 'gems', 'jquery-rails-2.0.3')
gem "i18n", :path => File.join('..', 'lib', 'gems', 'i18n-0.6.5')
gem "coderay", :path => File.join('..', 'lib', 'gems', 'coderay-1.0.9')
gem "fastercsv", :path => File.join('..', 'lib', 'gems', 'fastercsv-1.5.5')
gem "builder", :path => File.join('..', 'lib', 'gems', 'builder-3.0.4')
gem "pg", :path => File.join('..', 'lib', 'gems', 'pg-0.17.0')
gem "thin", :path => File.join('..', 'lib', 'gems', 'thin-1.5.1')

These gems require their own gems, they then require their own ones etc. How do I also specify the local copies of these so they're not just downloaded from rubygems.org?
In essense, when I run "bundle install", how do I make it grab all dependencies (including nested dependencies) from "../lib/gems/*"?

A: If you 'bundle pack' after 'bundle install', all of gems that specified in Gemfile is cache to 'vendor/cache' directory in your rails project.
Next, you can install all of your gems with 'bundle install --local'.
It will be extremely faster than just 'bundle install'.
Cheers, Sangil.


text:
Q: Using Connection Pool in MVC with EF Code First I want to know how to use the connection pool available in IIS 7 and configure the EF to fecth DB conenctions from Connection Pool
And another i am facing is when ever i use where or FirstorDefault() or Savechanges() new db connections get opened
How can i avoid that and use the opened connection for all the transactions?


text:
Q: Creating NSDictionary how i can create Dictionary that when i create jsondata with it, json looks like :
 "historyStep":[

{
"counter": "50",
"timestamp": "1461674383632"
}
 ]

I did this :
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:@(810) forKey:@"counter"];
[jsonDictOth setObject:@"1464957395241.447998" forKey:@"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,@"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

but it looks :
 historyStep =     {
    counter = 810;
    timestamp = "1464957395241.447998";
};

A: You are missing a level: NSDictionary (top level) with NSArray of NSDictionary in the top level key historyStep:
NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];

NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = @{@"counter":@"50", @"timestamp":@"1461674383632"};
[historySteps addObject:aStep]

[topLevel setObject:historySteps forKey@"historyStep"];

NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
                                               options:NSJSONWritingPrettyPrinted
                                                 error:&error];

A: Your code should be like,
   NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:@(810) forKey:@"counter"];
[jsonDictOth setObject:@"1464957395241.447998" forKey:@"timestamp"];

NSMutableArray *arr = [[NSMutableArray alloc]init];

[arr addObject:jsonDictOth];

NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,@"historyStep", nil];
NSLog(@"jsonMain is %@",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
                                               options:0
                                                 error:&error];

It's output is,
jsonMain is {
historyStep =     (
            {
        counter = 810;
        timestamp = "1464957395241.447998";
    }
 );
}

You just missed one array between

A: NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:@"50", @"counter",@"1461674383632", @"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, @"historyStep", nil];

Use this code it will work perfectly.


text:
Q: Redirect url to another domain using .htaccess I have the following in a .htaccess file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>

# END WordPress

I have tried the following but it does not work:
RewriteRule ^this-url$ http://www.anotherdomain.com/ [NC,L,R=301]

Any idea how I can resolve this?
Regards,
Neil.

A: It should work with your rule, but it must be placed before those concerning WordPress (Always redirect before rewriting):
RewriteEngine On
RewriteRule ^this-url$ http://www.anotherdomain.com/ [NC,L,R=301]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A: i'm using this code for my htacces to redirect to another website.
RewriteEngine On
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]

That should work.


text:
Q: Populating card view from database in ASP.Net Net. I want something like a recyclerview where you have 1 card in the aspx file which keeps recurring according to the number of entries in the database. So if my database table has supposed 3 entries of a particular name then there should be 3 cards in the page.
Here's what I did till now:
In my .aspx file:

     <asp:Label ID="Label1" runat="server" >
        <%# uni_name %>
     </asp:Label>

and for my aspx.cs:-
    public string uni_name;
    SqlCommand cmd = new SqlCommand();

    //SQL connection here

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        cmd.CommandText = //select statement here
        cmd.Connection = con;
        SqlDataReader rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            uni_name = rd["name"].ToString();
        }
        this.DataBind();

        con.Close();
    }

With this as of now I'm only able to get 1 entry from my database, but I want it to keep recurring until the end of the database.

A: You need some kind of array to show:
CS
public List<string> Names { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    cmd.CommandText = //select statement here
    cmd.Connection = con;
    SqlDataReader rd = cmd.ExecuteReader();
    Names = new List<string>();
    while (rd.Read())
    {
        Names.Add(rd["name"].ToString());
    }
    this.DataBind();

    con.Close();
}

ASP
 <%foreach (var name in this.Names)
  {%>

<%=name%>

   <%}%>

Update.
If you have a complex object like
class MyObj
{
    public string ID;
    public string Name;
}

You still can use it here instead of string.
public List<MyObj> Items{ get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    cmd.CommandText = //select statement here
    cmd.Connection = con;
    SqlDataReader rd = cmd.ExecuteReader();
    Items = new List<MyObj>();
    while (rd.Read())
    {
        var item = new MyObj
        {
             Name = rd["name"].ToString(),
             Id = rd["id"].ToString()
        };
        Names.Add(item);
    }
    this.DataBind();

    con.Close();
}

Then use it like
 <%foreach (var item in this.Items)
  {%>

<%=item.Id%> <%=item.Name%>

   <%}%>


text:
Q: The type or namespace name 'Application' does not exist in the namespace 'WebApplication1.Models' Hi I am new to Net Core and I am following this tutorial from PragimTech. In extending IdentityUser Part(77) of tutorial when I create new Class for ApplicationUser in order to extend from IdentityUser I face a Compile error saying

type Application  does not exist in namespace

. There are my codes to show.
ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class ApplicationUser:IdentityUser
    {

    }
}

_ViewImports.cshtml
@using WebApplication1.Models
@using WebApplication1.ViewModels
@using Microsoft.AspNetCore.Identity

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The ConfigureServices method in Startup.cs file
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection"))
          );
        services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
        services.AddScoped< IEmployeeRepository, SqlEmployeeRepository> ();
        services.AddIdentity<ApplicationUser, IdentityRole>(options => {
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 4;
        }).
            AddEntityFrameworkStores<AppDbContext>();
    }

The injection part in _layout.cshtml
@inject SignInManager<ApplicationUser> signeInManager;

AccountController
public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> userManager;
        private readonly SignInManager<ApplicationUser> signInManager;

        public AccountController(UserManager<ApplicationUser> userManager,
                            SignInManager<ApplicationUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

        [AcceptVerbs("Post","Get")]
        [AllowAnonymous]
        public async Task< IActionResult> IsEmailInUse(string email)
        {
            var user = await userManager.FindByEmailAsync(email);

            if(user == null)
            {
                 return Json(true);
            }
            else
            {
                return Json($"Email {email} is already taken.");
              }
         }

         [HttpGet]
         [AllowAnonymous]
         public IActionResult Register()
         {
             return View();
          }

         [HttpPost]
         [AllowAnonymous]
         public async Task< IActionResult> Register(RegisterViewModel model)
         {
             if (ModelState.IsValid)
              {
                 var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                 var result = await userManager.CreateAsync(user, model.Password);
                 if (result.Succeeded)
                 {
                     await signInManager.SignInAsync(user, false);
                     return RedirectToAction("index","home");
                      }
                  else
                {
                     foreach (var error in result.Errors)
                     {
                         ModelState.AddModelError("", error.Description);
                     }
            }
        }
        return View(model);
         }

         [HttpGet]
         [AllowAnonymous]
         public IActionResult Login()
         {
             return View();
          }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(model.Email, model.Password,
               model.RememberMe, false);
              if (result.Succeeded)
              {
                   if(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                   {
                    return Redirect(returnUrl);
                    }else
                     return RedirectToAction("index", "home");
                 }
                 else
                 {
                     ModelState.AddModelError(string.Empty, "Invalid user or password");
                  }
              }
               return View(model);
         }

          [HttpPost]
          public async Task<IActionResult> Logout()
          {
              await signInManager.SignOutAsync();
              return RedirectToAction("Index", "home");
           }

             }

A: Just Cleaned the solution and re-built it.


text:
Q: Oracle IAM/WNA protocol fallback to form-based logon page fails when Microsoft Online Services Sign-In Assistant is installed First post here.  Facing a problem where on Windows 10 an Oracle Identity Access Management (IAM) Windows Native Authentication (WNA) protocol fallback to a form-based logon page always fails whenever the Microsoft Online Services Sign-In Assistant (SIA) is installed.  Whenever we remove the SIA, the WNA fallback to a form-based logon page always succeeds.  This error is reproducible 100% of the time. We have not tested on Windows 8 or Windows 7. I've researched it, and there is not much out there to read about the SIA; it does not look to be configurable on the client end.  Really want to avoid changing up code on the IAM WNA side.
Anyone out there seen this before? This is a large enterprise network, using all Windows 10 computers, which has both Oracle IAM running for some applications as well as Microsoft Windows 2008 R2 Active Directory, to which all the Windows 10 computers are joined.  We are also standardized with Office 2016 with all back-end servers supporting Office apps such as Outlook, Lync, etc. in the cloud (Office 365).
Please let me know if I need to show the Oracle IAM/WNA SSO fallback code.

A: The Microsoft Online Services Sign-In Assistant is not configurable.  But, if all your computers are running Office 2016 you do not need it anyway and it can be safely uninstalled, which as you said will make the fallback to form-based logon page work.  If you were running Office 2013 you would need it however.  Office 2016 apps such as Outlook and Lync can go direct with ADFS whereas previous versions could not do this.  I don't have a URL reference for you, this is based on my experience.


text:
Q: Python - Solve some mathematical problems in a list filled with random elements Task: In a list filled with random numbers you need to count:

*

*A sum of negative numbers

*A sum of even numbers

*A sum of odd numbers

*A product of elements with indexes that multiple 3

*A product of elements between min and max element

*A sum of elements, which located between first and last element

I can't figure out how to solve last two issues
The code I have so far:
import random

size = int(input('Enter the size of a list: '))
begin = int(input('Enter the beginning of a list: '))
end = int(input('Enter the end of a list: '))

my_list = list()
for i in range(size):
    my_list.append(random.randint(begin, end))

for i in range(0, len(my_list)):
    print(f'{my_list[i]}[{i}]', end=' ')
print()

mul = 1
for i in range(0, len(my_list), 3):
    print(f'{mul} * {my_list[i]}[{i}] = ', end=' ')
    mul *= my_list[i]
    print(mul)

sum_list = [0] * 3

for item in my_list:
    if item < 0:
        sum_list[0] += item
    if item % 2 == 0:
        sum_list[1] += item
    if item % 2 != 0:
        sum_list[2] += item

print(f'Sum negative: {sum_list[0]}')
print(f'Sum even: {sum_list[1]}')
print(f'Sum odd: {sum_list[2]}')
print(f'Mul even 3 index: {mul}')

A:
A product of elements between min and max element

For this task, you can use .sort() method of the "list" object to sort it in-place then use list indexes to exclude the first and last item (min and max because it is sorted) and then use math.prod to calculate the product of rest
import math
my_list.sort()
math.prod(my_list[1:-1]) if len(my_list) > 2 else 0

A sum of elements, which located between the first and last element

Use list indexes to get the remaining elements and sum() them
sum(my_list[1:-1]) if len(my_list) > 2 else 0 # we need to check if list is long enough


text: Q: Is there a way to control the Status Bar color with Javascript or jQuery? I'm currently trying to build an app, but for some reason iOS isn't registering the status bar color as white. I'm wondering how I can set it as a certain color using only JavaScript or jQuery.


text:
Q: Updating daily files in pandas I am running pandas code on several files everyday which are .csv and always just for the one report date (previous day). I download these raw files from our client's website into their designated folders. I then open up ipython notebook and run my pandas modification on each file (I manually edit the name of the location to match the most recent file) and append it to my running/consolidated file.

*

*Is there a way to automate this? Can pandas only run code on the latest modified date or something?

*Can I create a code which will run all of my pandas codes daily? (example, open latest raw data from file 1 --> modify it as needed --> append it to a consolidate file --> open latest raw data from file 2 --> ...)

pandas has already saved me a ton of time (I used to manually open up files and paste them below in Excel, then I learned macros and some addins to merge files together), but maybe there is more I can learn to automate this further.


text:
Q: Rubygems and Bundler: Slow startup Edit: Somewhat different (and fewer) bottlenecks with Bundler 1.0.9 instead of 1.0.3.
I'm terribly annoyed by Rails's slow startup time (since I run tests repeatedly), so I'm trying to find out the culprit is using poor-man's profiling, by running rails console --help (which loads all my gems) repeatedly, hitting Ctrl+C, and looking at the stack trace.
Apart from the obvious culprits like active_support and friends being loaded, some of the time (perhaps 10% or so), the output looks similar to this:
$ rails console --help
^C/var/lib/gems/1.9.1/specifications/i18n-0.5.0.gemspec:3:in `new': Interrupt
    from /var/lib/gems/1.9.1/specifications/i18n-0.5.0.gemspec:3:in `load_specification'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:95:in `eval'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:95:in `load_specification'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:153:in `block (2 levels) in load_gems_in'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:152:in `each'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:152:in `block in load_gems_in'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:149:in `reverse_each'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:149:in `load_gems_in'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:345:in `refresh!'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:78:in `from_gems_in'
    from /usr/lib/ruby/1.9.1/rubygems/source_index.rb:58:in `from_installed_gems'
    from /usr/lib/ruby/1.9.1/rubygems.rb:866:in `source_index'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/source.rb:161:in `installed_specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/source.rb:151:in `block in fetch_specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/index.rb:7:in `build'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/source.rb:150:in `fetch_specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/source.rb:65:in `specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:159:in `block (2 levels) in index'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:158:in `each'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:158:in `block in index'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/index.rb:7:in `build'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:157:in `index'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:151:in `resolve'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:90:in `specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:135:in `specs_for'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/definition.rb:124:in `requested_specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/environment.rb:23:in `requested_specs'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler/runtime.rb:11:in `setup'
    from /var/lib/gems/1.9.1/gems/bundler-1.0.9/lib/bundler.rb:101:in `setup'
    from /home/jo/src/mercury/config/boot.rb:8:in `<top (required)>'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from script/rails:5:in `<main>'

So it seems that quite some time is spent loading gemspecs.
Is there some way to speed this up?  Dirty hacks are appreciated too -- I just want to run my test suite without (so much) delay.

A: have you tried spork?

A: Update to this: tconsole is really cool too, if you are using MiniTest.


text:
Q: PostgreSQL UUID date type I'm building a platform with a PostgreSQL database (first time) but I've experience with Oracle and MySQL databases for a few years now.
My question is about the UUID data type in Postgres.
I am using an UUIDv4 uuid to indentify a record in multiple tables, so the request to /users/2df2ab0c-bf4c-4eb5-9119-c37aa6c6b172 will respond with the user that has that UUID. I also have an auto increment ID field for indexing.
My query is just a select with a where clause on UUID. But when the user enters an invalid UUID like this 2df2ab0c-bf4c-4eb5-9119-c37aa6c6b17 (without the last 2) then the database responds with this error: Invalid input syntax for UUID.
I was wondering why it returned this because when you select on a integer-type with a string-type it does work.
Now I need to set a middleware/check on each route that has an UUID-type parameter in it because otherwise the server would crash.
Btw I'm using Flask 0.12 (Python) and PostgreSQL 9.6

A:
UUID as defined by RFC 4122, ISO/IEC 9834-8:2005... is a 128-bit quantity ... written as a sequence of lower-case hexadecimal digits... for a total of 32 digits representing the 128 bits. (Postgresql Docs)

There is no conversion from a 31 hex digits text to a 128-bit UUID (sorry). You have some options:

*

*Convert to ::text on your query (not really recommended, because you'd be converting every row, every time).
SELECT * FROM my_table WHERE my_uuid::TEXT = 'invalid uid';

*Don't store it as a UUID type. If you don't want / need UUID semantics, store it as a varchar.

*Check your customer input. (My recommendation). Conceptually, this is no different from asking for someone's age and getting 'ABC' as the response.

Postgres allows upper/lower case, and is flexible about use of hyphens, so a pre-check is simply strip the hyphens, lowercase, count [0-9[a-f] & if == 32, you have a workable UUID. Otherwise, rather than telling your user "not found", you can tell them, "not a UUID", which is probably more user-friendly.

A: The database is throwing an error because you're trying to match in a UUID-type column with a query that doesn't contain a valid UUID.  This doesn't happen with integer or string queries because leaving off the last character of those does result in a valid integer or string, just not the one you probably intended.
You can either prevent passing invalid UUIDs to the database by validating your input (which you should be doing anyway for other reasons) or somehow trap on this error.  Either way, you'll need to present a human-readable error message back to the user.
Also consider whether users should be typing in URLs with UUIDs in the first place, which isn't very user-friendly; if they're just clicking links rather than typing them, as usually happens, then how did that error even happen?  There's a good chance that it's an attack of some sort, and you should respond accordingly.


text:
Q: why I can't get mnist datasets using scikit learn in python This's my code. why isn't it not working
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original', data_home='./data')

when I run it in cmd, I get that
Traceback (most recent call last):
  File "mnistTest.py", line 7, in <module>
    mnist = fetch_mldata('MNIST original', data_home='./data')
  File "C:\Python27\lib\site-packages\sklearn\datasets\mldata.py", line 142, in
fetch_mldata
    mldata_url = urlopen(urlname)
  File "C:\Python27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 429, in open
    response = self._open(req, data)
  File "C:\Python27\lib\urllib2.py", line 447, in _open
    '_open', req)
  File "C:\Python27\lib\urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 1228, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python27\lib\urllib2.py", line 1198, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 10060] A connection attempt failed becau
se the connected party did not properly respond after a period of time, or estab
lished connection failed because connected host has failed to respond>

Why isn't it work and how I make it working?

A: fetch_mldata function fetches data from mldata.org, which seems to be down.


text:
Q: How can i close my app which is still running in background after closing My application is running normally and when I move on some new activity I used the code as
Intent start=new Intent(current activity.this,new activity.class);
                startActivityForResult(start, 0);
                finish();

and then when I have to move back to the earlier activity I used the following code
Intent start = new Intent(current activity.this,earlier activity.class);
                    startActivity(start);
                    finishActivity(0);

I think in this way the stack of the activities may be clear. And on click of the button or the phone back button I used the following code
Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(startMain);

But my application is still running in the background. I also used the android:noHistory="true" app is killed from the background but message appered that app close forcefully. Simple finish(); moves to the last activity.
I also seen the link Quitting an application - is that frowned upon? but I am new so did't get much. Please suggest me some way how can I deal with this.

A:
I think in this way the stack of the activities may be clear

You are welcome to your opinion. startActivityForResult() is not designed for how you are using it.

And on click of the button or the phone back button I used the following code

I would fire anyone who worked for me who did this.
Please follow the Android design guidelines for proper handling of the BACK button -- while I do not agree with everything in there, it is much better than what you are doing. In the eyes of the user, BACK means back.

But my application is still running in the background

So long as you have not leaked any threads or services, your process will be running, but it will be consuming no significant CPU time. Android will terminate the process when it needs the RAM. This way, if the user elects to return to your application, or something else in your application needs to run (e.g., AlarmManager event, broadcast Intent), Android does not have to waste CPU time and battery life to fork another process.

Please suggest me some way how can I deal with this.

Just leave the process alone, and nobody will get hurt.