text:
Q: What is httpinterceptor equivalent in angular2? In angularjs, we have http interceptor
$httpProvider.interceptors.push('myHttpInterceptor');

with which we can hook into all http calls, and show or hide loading bars, do logging, etc..
What is the equivalent in angular2?

A: With the Angular 4.3.1 release, there's now an interface called HttpInterceptor.
Here's the link to the docs:
https://angular.io/api/common/http/HttpInterceptor
Here's an implementation sample.

This would be the interceptor class implementation.
Is basically written as any other service:
@Injectable()
export class ExceptionsInterceptor implements HttpInterceptor {
    constructor(
        private logger: Logger,
        private exceptionsService: ExceptionsService,
        private notificationsService: NotificationsService
    ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request)
            .do((event) => {
                // Do nothing here, manage only errors
            }, (err: HttpErrorResponse) => {
                if (!this.exceptionsService.excludeCodes.includes(err.status)) {
                    if (!(err.status === 400 && err.error['_validations'])) {
                        this.logger.error(err);
                        if (!this.notificationsService.hasNotificationData(err.status)) {
                            this.notificationsService.addNotification({ text: err.message, type: MessageColorType.error, data: err.status, uid: UniqueIdUtility.generateId() });
                        }
                    }
                }
            });
    }
}

Then since you'll treat this like a normal service, you have to add this line inside your app module's providers:
{ provide: HTTP_INTERCEPTORS, useClass: ExceptionsInterceptor, multi: true }

Hope it can help.

A: As @Günter pointed it out, there is no way to register interceptors. You need to extend the Http class and put your interception processing around HTTP calls
First you could create a class that extends the Http:
@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

and register it as described below:
bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

The request and requestError kinds could be added before calling the target methods.
For the response one, you need to plug some asynchronous processing into the existing processing chain. This depends on your need but you can use operators (like flatMap) of Observable.
Finally for the responseError one, you need to call the catch operator on the target call. This way you will be notified when an error occurs in the response.
This links could help you:

*

*Handling refresh tokens using rxjs

*Angular 2 - How to get Observable.throw globally

A: Angular 4.3 now supports Http interceptor out-of-the-box.
Check it out how to use them:
https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors

A: update
The new HttpClient module introduced in Angular 4.3.0 supports interceptors https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0

feat(common): new HttpClient API HttpClient is an evolution of the
  existing Angular HTTP API, which exists alongside of it in a separate
  package, @angular/common/http. This structure ensures that existing
  codebases can slowly migrate to the new API.
The new API improves significantly on the ergonomics and features of
  the legacy API. A partial list of new features includes:

*

*Typed, synchronous response body access, including support for JSON body types

*JSON is an assumed default and no longer needs to be explicitly parsed

*Interceptors allow middleware logic to be inserted into the pipeline

*Immutable request/response objects

*Progress events for both request upload and response download

*Post-request verification & flush based testing framework

original
Angular2 doesn't have (yet) interceptors. You can instead extend Http, XHRBackend, BaseRequestOptions or any of the other involved classes (at least in TypeScript and Dart (don't know about plain JS).
See also

*

*RFC: Http interceptors and transformers

*Introduce an interception mechanism

*Interceptors in Angular2

*Angular2 - set headers for every request

A: There's an implementation for a Http @angular/core-like service in this repository: https://github.com/voliva/angular2-interceptors
You just declare the provider for that service on bootstrap, adding any interceptors you need, and it will be available for all the components.
import { provideInterceptorService } from 'ng2-interceptors';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    MyHttpInterceptor,
    provideInterceptorService([
      MyHttpInterceptor,
      /* Add other interceptors here, like "new ServerURLInterceptor()" or
         just "ServerURLInterceptor" if it has a provider */
    ])
  ],
  bootstrap: [AppComponent]
})

A: DEPRICATED SINCE Angular 4.3 (HttpInterCeptors are Back in 4.3)
You can create your own custom HTTP Class and use rxjs Subject Service to reuse your custom Http Class and implement your behaviors in a custom class.
Implementation of your Custom Http Class with "HttpSubjectService" which contains some rxjs Subjects.
import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { HttpSubjectService } from './httpSubject.service';

@Injectable()
export class CustomHttp extends Http {
   constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private httpSubjectService: HttpSubjectService) {
       super(backend, defaultOptions);

       //Prevent Ajax Request Caching for Internet Explorer
       defaultOptions.headers.append("Cache-control", "no-cache");
       defaultOptions.headers.append("Cache-control", "no-store");
       defaultOptions.headers.append("Pragma", "no-cache");
       defaultOptions.headers.append("Expires", "0");
   }

   request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
       //request Start;
       this.httpSubjectService.addSpinner();
       return super.request(url, options).map(res => {
           //Successful Response;
           this.httpSubjectService.addNotification(res.json());
           return res;
       })
           .catch((err) => {
               //Error Response.
               this.httpSubjectService.removeSpinner();
               this.httpSubjectService.removeOverlay();

               if (err.status === 400 || err.status === 422) {
                   this.httpSubjectService.addHttp403(err);
                   return Observable.throw(err);
               } else if (err.status === 500) {
                   this.httpSubjectService.addHttp500(err);
                   return Observable.throw(err);
               } else {
                   return Observable.empty();
               }
           })
           .finally(() => {
               //After the request;
               this.httpSubjectService.removeSpinner();
           });
   }
}

Custom module to register your CustomHttp class - here you overwrite the default Http implementation from Angular with your own CustomHttp Implementation.
import { NgModule, ValueProvider } from '@angular/core';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';

//Custom Http
import { HttpSubjectService } from './httpSubject.service';
import { CustomHttp } from './customHttp';

@NgModule({
    imports: [ ],
    providers: [
        HttpSubjectService,
        {
           provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, httpSubjectService: HttpSubjectService) => {
                return new CustomHttp(backend, defaultOptions, httpSubjectService);
            },
            deps: [XHRBackend, RequestOptions, HttpSubjectService]
        }
    ]
})
export class CustomHttpCoreModule {

    constructor() { }
}

now we need the HttpSubjectService Implementation where we can SubScribe to our rxjs Subjects when they get called with the "next" statement.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class HttpSubjectService {
    //https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md
    //In our app.component.ts class we will subscribe to this Subjects
    public notificationSubject = new Subject();
    public http403Subject = new Subject();
    public http500Subject = new Subject();
    public overlaySubject = new Subject();
    public spinnerSubject = new Subject();

    constructor() { }

    //some Example methods we call in our CustomHttp Class
    public addNotification(resultJson: any): void {
        this.notificationSubject.next(resultJson);
    }

    public addHttp403(result: any): void {
        this.http403Subject.next(result);
    }

    public addHttp500(result: any): void {
        this.http500Subject.next(result);
    }

    public removeOverlay(): void {
        this.overlaySubject.next(0);
    }

    public addSpinner(): void {
        this.spinnerSubject.next(1);
    }

    public removeSpinner(): void {
        this.spinnerSubject.next(-1);
    }
}

to call your custom Implementations we need to Subscribe to the Subjects in the e.g. "app.component.ts".
import { Component } from '@angular/core';
import { HttpSubjectService } from "../HttpInterception/httpSubject.service";
import { Homeservice } from "../HttpServices/home.service";

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
})
export class AppComponent {
    private locals: AppLocalsModel = new AppLocalsModel();

    constructor(private httpSubjectService : HttpSubjectService, private homeService : Homeservice) {}

    ngOnInit(): void {
        this.notifications();
        this.httpRedirects();
        this.spinner();
        this.overlay();
    }

    public loadServiceData(): void {
        this.homeService.getCurrentUsername()
            .subscribe(result => {
                this.locals.username = result;
            });
    }

    private overlay(): void {
        this.httpSubjectService.overlaySubject.subscribe({
            next: () => {
              console.log("Call Overlay Service");
            }
        });
    }

    private spinner(): void {
        this.httpSubjectService.spinnerSubject.subscribe({
            next: (value: number) => {
              console.log("Call Spinner Service");
            }
        });
    }

    private notifications(): void {
        this.httpSubjectService.notificationSubject.subscribe({
            next: (json: any) => {
                console.log("Call Notification Service");
            }
        });
    }

    private httpRedirects(): void {
        this.httpSubjectService.http500Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Error Page");
            }
        });

        this.httpSubjectService.http403Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Not Authorized Page");
            }
        });
    }
}

class AppLocalsModel {
    public username : string = "noch nicht abgefragt";
}

SINCE ANGULAR 4.3 you can Use InterCeptors
In Angular 4.3 you have native Interceptors where you can implement your own stuff like a redirect for server error 500
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class SxpHttp500Interceptor implements HttpInterceptor {

  constructor(public router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req).do(evt => { }).catch(err => {
          if (err["status"]) {
              if (err.status === 500) {
                  this.router.navigate(['/serverError', { fehler: JSON.stringify(err) }]);
              }
          }
          return Observable.throw(err);
      });
  }
}

you need to Register this in your core module in the providers Array
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Router } from '@angular/router';
import { SxpHttp500Interceptor } from "./sxpHttp500.interceptor";
 ....

providers: [
    {
        provide: HTTP_INTERCEPTORS, useFactory: (router: Router) => { return new SxpHttp500Interceptor(router) },
        multi: true,
        deps: [Router]
    }
]

A: I have released interceptor with following node module. We was create this  module for our internal purpose finally we released in npm package manager
npm install angular2-resource-and-ajax-interceptor
https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

A: As @squadwuschel pointed out, work is underway to get this functionality into @angular/http.  This will be in the form of a new HttpClient API.
See https://github.com/angular/angular/pull/17143 for more details and current status.

A: Try  Covalent from  Teradata, they provides lots of extensions for  Angular and Angular Material.
Check HTTP part, it provides the missing http interceptor in Angular and RESTService(similar to restangular).
I have implemented JWT token authentication via  Covalent HTTP  in my sample, Please check here.
https://github.com/hantsy/angular2-material-sample/blob/master/src/app/core/auth-http-interceptor.ts
Read my development notes for it, Handle token based Authentication via IHttpInterceptor.

A: Angular2 donot support httpinterceptor like angular1
Here is awesome example of use of httpinterceptor in angular2.
https://github.com/NgSculptor/ng2HttpInterceptor


text:
Q: Would variables that don't differ between the two categories improve classification? I want to build do classification to determines if a user will visit another page on the website before logging out. So it's making a binary prediction: last page or not last page.
Would variables that are constant between pages (e.g. user age, user gender) add any value to the model or no?
I mean, I suppose age and gender may be somewhat correlated with the typical number of pages a user visits, but we would already include mean number of page a user visits as a feature.
Would the answer to the question depend on the type of classification algorithm used?

A: The answer to this question hinges on whether you already include individual fixed effects.
An interpretation of your question:
Q: If I already have individual fixed effects in my model, can I increase prediction power by adding right hand side variables (eg. gender) that don't vary within an individual?
A: In the context of classic linear models (eg. linear regression), the answer is no. All it would do is change your estimate of the fixed effects and none of your predictions would change at all.
If you ran the following two regressions:
$$y_{it} = \hat{a} + \hat{b}_1 x_{it} + \hat{u}_i +\hat{\epsilon}_{it}$$
$$y_{it} = a + b_1 x_{it} + b_2 z_i + u_i + \epsilon_{it}$$
Your forecasting power would be the same, and you'd have $\hat{u}_i = b_2 z_i + u_i$.
Q: Moving beyond ordinary least squares regression, could it change things?
A: Yes. In the most general sense, you need not have the equivalence. I would not expect it to improve things (since the data is collinear), but perhaps in certain contexts it could? Eg. repeating the same feature in a random forest could give it a higher probability of being selected etc...

A: Your question may be wrongly worded, as the age or gender of a person does not really stay the same between the two categories, which are whether the user will visit another page or not.
This is because for a given user, they cannot be in both categories at the same time.
But whether there is any correlation between certain features and the propensity of a user to stay on that page or not, needs to be found from the data. You would ideally like to consider a large pool of possible features and then perform feature selection to prune out the ones that do not seem to be correlated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RavenDB results transformer not fully populating result I have setup the following RavenDB "Result Transformer" to operate on the model included below and outputting the result class as defined below.  When the query is executed everything works fine except that the "Id" field in the VoicemailMessageHeader in the result class does not get populated.  All of the other fields in the VoicemailMessageHeader do get populated.  Why would the "Id" field not be getting populated?
Result Transformer:
public class VoicemailMessageHeaderWithDisplayNameTransformer : AbstractTransformerCreationTask<VoicemailMessageHeader>
{
  public VoicemailMessageHeaderWithDisplayNameTransformer()
  {
    TransformResults = voicemailMessageHeaders => from voicemailMessageHeader in voicemailMessageHeaders
       let displayNameRecord = LoadDocument<DisplayName>(voicemailMessageHeader.CallerPhoneNumber)
       let displayName = (displayNameRecord != null) ? displayNameRecord.Name : string.Empty
       select new{
         VoicemailMessageHeader = voicemailMessageHeader,
         DisplayName = displayName,
       };
   }
 }

The database object that gets transformed:
public class VoicemailMessageHeader
{
        public string Id { get; set; }
        public string OwnerId { get; set; }
        public string FolderId { get; set; }
        public string CallerName { get; set; }
        public string CallerPhoneNumber { get; set; }
        public string AccountNumber { get; set; }
        public DateTime CallDateTime { get; set; }
        public TimeSpan Duration { get; set; }
        public string MessageUrl { get; set; }
        public bool IsListened { get; set; }
        public bool IsDeleted { get; set; }
        public bool IsDownloaded { get; set; }
        public string MessageFilePath { get; set; }
}

The result class that is created by the transformer:
public class VoicemailMessageHeaderWithDisplayName
{
        public VoicemailMessageHeader VoicemailMessageHeader { get; set; }
        public string DisplayName { get; set; }
}

The Query:
session.Query<VoicemailMessageHeader>()
  .TransformWith<RavenDbIndexes.VoicemailMessageHeaderWithDisplayNameTransformer,
    VoicemailMessageHeaderWithDisplayName>()


text:
Q: how to make shortcut with command? I want to open a .jar file with java. It is located in /home/myusername. I had to type in the terminal to open it
java -jar filename.jar

I want to have a shortcut that if I click it, it will run the command and launch the program with java automatically..
is there anything I could do?

A: You can create a .desktop file on your desktop using your favourite text editor  and save the following code in a it.
[Desktop Entry]
Encoding=UTF-8
Name=myjavafile
Type=Application
Exec=java -jar /home/myusername/filename.jar
Icon=/path/to/java.jpg

You need to change Name and jar file name in Exec field. If you want to set an icon for it put a 128x128 .jpg or .png image for java and specify it accordingly on Icon field. Otherwise remove the last line.

Give it execution permission,
chmod +x /home/myusername/Desktop/<filename>.desktop

Now you can click on it to open your jar file using java directly.

A: First create an Empty Document and name it yourchoosenname.sh
(.sh means that this file contain commands to run )

Second open this file and add the code you write in Terminal, adjusting the path as appropriate:
java -jar /home/$USER/filename.jar

Third make this file executable:
Right click on the file, then to the Permissions tab.

Fourth run this file by double clicking.


text:
Q: Attempted to call an undefined method named "getChoices" of class "Symfony\Component\Form\ChoiceList\View\ChoiceListView" In the app updated from Symfony 2.3 to 2.8, we have changed the choice list that changed in 2.7.
See the links below for documentation on previous code and changes.
I got the following error in it.
Does this mean I have to create getChoices in StaffChoiceLoader?
I think only loadChoiceList, loadChoicesForValues,  loadValuesForChoices required for ChoieLoaderInterface is needed.
Beforecode
Symfony: Unable to reverse value for property path [...]: The choice [...] does not exist or is not unique
Document
https://github.com/symfony/symfony/blob/2.8/UPGRADE-2.7.md
ChoiceLoader.php
class StaffChoiceLoader implements ChoiceLoaderInterface
{
    public function loadChoiceList($value = null)
    {
        $staffs = $this->staffService->getStaffByShop($this->loginStaff->getShop());

        $factory = new DefaultChoiceListFactory();

        $choiceList = $factory->createListFromChoices($staffs);

        $choiceListView = $factory->createView(
           $choiceList,
           function ($staffs, $key) use ($staffs) {
           return $staffs[$key];
        });

            return $choiceListView;
    }
}


text:
Q: My footer bounces up and down On the sell page of our site, when a user goes through the process the footer is going up and down which gets a little annoying.
The selling page
This is the custom CSS I am using:

.ajax-loader,.offer-n-accept,.thumbnail{text-align:center}.repop-row,.repop-row-selected{border:1px solid #ebebeb;padding:20px}#declaration,#save_data,.ajax-loader,.error-msg,.payment_information,.previews{display:none}@font-face{font-family:brandfont;src:url(Inversionz.otf)}.branded{font-family:brandfont;font-size:300%;color:#FFF}.navbar .navbar-brand{font-family:brandfont;font-size:40px;color:#f5f5f5}.navbar-inverse .navbar-brand{font-family:brandfont;font-size:40px;color:#FFF}.navbar-default .navbar-brand:hover{font-family:brandfont;font-size:40px;color:#2E64FE}.row.repsteps,.row.steps{margin-bottom:10px;text-align:center;display:none}.thumbnail{cursor:pointer}.thumbnail:hover{border-color:#2E64FE}h1 span{color:#2E64FE}.offer-n-accept span{font-size:80px}.footer-links{color:#ebebeb;margin-left:5px;margin-right:5px}.repop-row,.repop-row-selected{margin-left:auto;margin-right:auto}footer.well{background-color:#000;color:#FFF;margin-top:0;margin-bottom:0;border-top:10px solid #2e64fe}.social-icons{font-size:43px;color:#fff}.repop-row{border-radius:2px;width:90%;height:90%;cursor:pointer}.repop-row-selected{border-radius:2px;width:90%;height:90%;background-color:#2e64fe;color:#fff;cursor:pointer}.repop-row:hover{border-color:#2e64fe}.repop-row-selected .repop-price-col{font-size:20px;color:#333;background-color:#fff;border-radius:2px;padding:5px}.repop-price-col,.selected .thumbnail{background-color:#2e64fe}.repop-price-col{font-size:20px;color:#fff;border-radius:2px;padding:5px}.repop-row-selected .repop-title-col{font-size:20px;margin-top:4px;color:#fff}.repop-title-col{font-size:20px;margin-top:4px}.selected .thumbnail .caption{color:#fff}.thumbnail .preview-title{font-size:16px;color:#2e64fe}span.device-price{font-size:40px;color:#337AB7;font-weight:700}.facebook-icon:hover{color:#3A5795}.twitter-icon:hover{color:#2B7BB9}.howitworks{background-color:#F2F2F2;padding:50px;margin-bottom:0}.howitworks div h3{color:#2e64fe}.howitworks div span.fa{font-size:80px}.accessory-selected .thumbnail{background-color:#2e64fe}.accessory-selected .thumbnail .caption h3{color:#FFF}.social-icons{margin:5px}.faq{background-color:#FAFAFA}.item img{margin-left:auto;margin-right:auto}.feature h2{color:#2e64fe}.btn-toolbar .btn{margin-bottom:5px}@media(max-width:767px){.h1,h1{font-size:32px}.h3,h3{font-size:18px}}

This is the layout file:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php if (isset($meta)): ?>
    <?= $meta->meta_tags ?>

    <?php endif ?>

    <?php if (isset($title)&&!isset($meta)): ?>
      <title><?= $title ?></title>
    <?php endif ?>
    <link rel="icon" href="<?= site_url() ?>resources/favicon.ico" type="image/x-icon">
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic' rel='stylesheet' type='text/css'>

    <link href="<?= site_url() ?>third_party_plugins/dist/css/style.css" rel="stylesheet">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

   <link href="<?= site_url() ?>resources/css/custom.css" rel="stylesheet" >

  <?php
  $sell_active = '';
  $repair_active = '';
  $register_active = '';
  $login_active = '';
  $track_active = '';
  $myorders_active = '';
  //active classes.
  if(uri_string() == 'sell') {
    $sell_active = 'active';
  } else if(uri_string() == 'repair') {
    $repair_active = 'active';
  } else if(uri_string() == 'register') {
    $register_active = 'active';
  } else if(uri_string() == 'login') {
    $login_active = 'active';
  } else if(uri_string() == 'track') {
    $track_active = 'active';
  }else if(uri_string() == 'myorders') {
    $myorders_active = 'active';
  }

   ?>

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

        </button>
        <a class="navbar-brand" href="<?= site_url() ?>"><?= $this->config->item('app_name')?>

        <?php if(!isset($_SESSION['user_login'])): ?>

          <a href="<?= site_url() ?>login" class="btn btn-success"> Login

        <?php else: ?>

            <a href="<?= site_url() ?>logout" class="btn btn-info"> Logout

        <?php endif ?>

          <li class="<?= $sell_active ?>"><a href="<?= site_url() ?>sell"> Sell

          <li class="<?= $repair_active ?>"><a href="<?= site_url() ?>repair"> Repair

          <?php if(isset($_SESSION['user_login'])): ?>
            <li class="<?= $myorders_active ?>">
              <a href="<?= site_url() ?>myorders"> My Orders

          <?php else: ?>
            <li class="<?= $track_active ?>">
              <a href="<?= site_url() ?>track"> Order Status

          <?php endif ?>
          <?php if (isset($_SESSION['user_login'])): ?>
            <?php else: ?>
            <li class="<?= $register_active ?>">
              <a href="<?= site_url() ?>register"> Register

          <?php endif ?>

  <?php echo $view ?>

Open in Dade, Broward, & Palm Beach

© 2016 MacMetro.com. All rights reserved.

<a href="<?php echo base_url('help'); ?>">Help

<a href="<?php echo base_url('faqs'); ?>">FAQs

<a href="<?php echo base_url('terms'); ?>">Terms

<a href="<?php echo base_url('contact'); ?>">Contact Us

              <a href="<?= $_SESSION['company'][1]->facebook ?>" target="_blank">

              <a href="<?= $_SESSION['company'][1]->twitter ?>" target="_blank">

A: you can set position to position: absolute; and then your footer will be in the same place.
position: relative; will make it bounce, if you added it please change it to position: absolute; and add top: 1000px or any height.

A: You should consider using a sticky footer

The sticky  can be found here and the css here

A: Two suggestions for you off the top of my head could be:
Give your
 a minimum height so it'll push down the footer, the width of a screen varies a lot but the the height not so often. Then it'll also follow further down on smaller devices.
Alternatively you can make a
 and give it a fixed position to make sure it'll always be in the bottom, in case you wanna have that infomation displayed at all time.
However, more solutions are possible for this problem.

A: Good option about sticky footer.
You can also add an extra class (fx.: order-steps) to the section with class section-md that contains all the steps. Add a property to
.order-steps {
  min-height: 600px
}
This will make 'room' for the content in the different steps.


text:
Q: Add current year in redirect htaccess I try to write a Rewrite Rule which route from:
/abteilungen/einsatzabteilung/einsaetze.php

to
domain.de/abteilungen/einsatzabteilung/einsaetze/2016 (CURRENT_YEAR)

My .htaccess looks now like this:
RewriteEngine on
Redirect 301 /abteilungen/einsatzabteilung/einsaetze.php %{HTTP_HOST}/abteilungen/einsatzabteilung/einsaetze/

Is it possible that the year at the end of the target get the current year and how can i do this?
Edit
Full .htaccess throws 404 error:
RewriteEngine On
RewriteRule ^/abteilungen/einsatzabteilung/einsaetze.php$ %{HTTP_HOST}/abteilungen/einsatzabteilung/einsaetze/%{TIME_YEAR} [L,R=301]

RewriteRule ^(.*)einsaetze/([0-9]{4})$ $1/abteilungen/einsatzabteilung/index\.php/$2

A: in apache exist variable TIME_YEAR
RewriteEngine on
Redirect 301 /abteilungen/einsatzabteilung/einsaetze.php %{HTTP_HOST}/abteilungen/einsatzabteilung/einsaetze/%{TIME_YEAR}

try use RewriteRule
RewriteEngine On
RewriteRule ^/abteilungen/einsatzabteilung/einsaetze.php$ %{HTTP_HOST}/abteilungen/einsatzabteilung/einsaetze/%{TIME_YEAR} [R=301,L]


text:
Q: I am having problems with Node.js and NPM on Windows I am new to Node.js and NPM. I just installed it on my computer and every time I try to use the command npm in CMD it shows me the following:

A: This message on windows means that NODE_PATH is not set.
You can use next bat-file
@echo off
cd..
pushd %~dp0
set NODE_PATH=%cd%;%cd%\folder1;%cd%\folder2;
node %cd%\app.js
pause

or define in package.json section "scripts/start"
  "scripts" : {
    "start": "set NODE_PATH=.;./folder1;./folder2; && node app.js"
  }

and run app as npm start


text:
Q: React: useState hook updates only the last instance from multiple instances of the same functional component When I click on any of 3 items then only the last one is incremented. When using class-based component instead of functional one for Item component then everything is fine. Could someone explain please?
const { Fragment, useState } = React;

const List = () => {
  return (
    <Fragment>
      <Item /><Item /><Item />
    </Fragment>
  )
};

const Item = () => {
  [count, setCount] = useState(0);
  return (

 setCount(count + 1)}>{count}

  );
};

ReactDOM.render(
  <List />,
  document.getElementById('root')
);

https://jsfiddle.net/antonfil/qk08srn5/17/

A: You are creating globals when you do
[count, setCount] = useState(0);

You need to do
const [count, setCount] = useState(0);


text:
Q: GraphX Edges with multiple features I am working with Graphx and trying to add features to edges. I have a csv file with Id1, Id2, Weight, Type
I am able to get the Ids and one feature - either weight or type. Is there a way to save multiple features for an edge. Here is a snippet of my code:
val edgesWriterWriterCollaborated: RDD[Edge[String]] = sc.textFile(edgeWeightedWriterWriterCollaborated).map {
  line =>
    val row = line.split(",")
    Edge(row(0).toLong, row(1).toLong, row(2))
}

This gives me an error:
val edgesWriterWriterCollaborated: RDD[Edge[Tuple2]] = sc.textFile(edgeWeightedWriterWriterCollaborated).map {
  line =>
    val row = line.split(",")
    Edge(row(0).toLong, row(1).toLong, (row(2), row(3)))
}

Update:
I fixed my code as so:
    case class WriterWriterProperties(weight: String, edgeType: String)
 val edgesWriterWriterCollaborated: RDD[Edge[WriterWriterProperties]] = sc.textFile(edgeWeightedWriterWriterCollaborated).map {
  line =>
    val row = line.split(",")
    Edge(row(0).toLong, row(1).toLong, WriterWriterProperties(row(2), row(3)))
}

However when I try to print:
   graph4.triplets.foreach(println)

I am getting an error: Caused by: java.io.NotSerializableException

A: Sure. Use a Tuple2 :
Edge(row(0).toLong, row(1).toLong, (row(2), row(3)))

or any domain specific object that makes sense in your case:
case class FooBar(foo: String, bar: String)

Edge(row(0).toLong, row(1).toLong, FooBar(row(2), row(3)))


text:
Q: JAXRPCSERVLET28: Missing port information Reason for this error JAXRPCSERVLET28: Missing port information

A: One of my server had some issues coming up after a bounce.. I think that made to throw this error. We bounced the server and the server is back up now and it is working....
Note : this service was working before. So I think bounce fixed our issue. I just wanted to post this here because I see many post for this error without a solution
Please include if you have any thoughts.

A: From my research, the following stack trace shows the location of error; it also provides information that the _send() method is where the error occurs:
java.rmi.ServerException: JAXRPC.JAXRPCSERVLET.28: Missing port information
=09at com.sun.xml.rpc.client.StreamingSender._raiseFault(StreamingSender.ja=
va:372)
=09at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:224=
)
=09at com.sun.xml.rpc.client.dii.CallInvokerImpl.doInvoke(CallInvokerImpl.j=
ava:61)
=09at com.sun.xml.rpc.client.dii.BasicCall.invoke(BasicCall.java:339)
=09at com.sun.xml.rpc.client.dii.CallInvocationHandler.doCall(CallInvocatio=
nHandler.java:99)
=09at com.sun.xml.rpc.client.dii.CallInvocationHandler.invoke(CallInvocatio=
nHandler.java:71)
=09at $Proxy0.getWorkList(Unknown Source)
=09at com.workpoint.sample.client.webservices.WorkItemServiceClient.testGet=
WorkList(WorkItemServiceClient.java:124)
=09at com.workpoint.sample.client.webservices.WorkItemServiceClient.main(Wo=
rkItemServiceClient.java:48)
=09

This problem was resolved for me when I looked at the server.log file and saw that the JAXRPC servlet did not deploy correctly because of an initialization issue.  The war file successfully deployed.  Beware: after running tests, the original error in the server.log file will be 'left behind', fronted by other log activity that was not helpful.  This error could be caused by any number of causes.


text:
Q: how to search in multi tables with using ormlite i have app in android i'm using ormlite library
the database contain 5 tables
i need using searchview to quick search for any thing in this 5 tables
and view the search in listview
I have no idea about the search using ormlite
I need a better solution can be used

A: For an Idea -
you can create QueryBuilder for each table and join them. Then use
queryBuilderObject.where().eq(<your searching column>, <value>).query();

to retrive the values. Refer this


text:
Q: How to Model Ternary Relationship in CakePhp? Page table
(1)
|
|
(*)
User_Moderate_Page (*)----------- (1)Access_level table
(*)
|
|
(1)
User table
How do i Model such a ternary relationship in CakePhp?
User to Page can be modelled using the hasBelongtoMany Relationship. But User_Moderate_page is just an association table, should I even write a Model for User_Moderate_Page in Cake?

A: I'm not sure CakePHP accepts this, but what you should do is create the table with a primary key and the 3 foreign keys. Somewhat like this:
CREATE  TABLE IF NOT EXISTS `mydb`.`access_levels_pages_users` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `page_id` INT NOT NULL ,
  `access_level_id` INT NOT NULL ,
  `user_id` INT NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_access_levels_pages_users_pages` (`page_id` ASC) ,
  INDEX `fk_access_levels_pages_users_access_levels1` (`access_level_id` ASC) ,
  INDEX `fk_access_levels_pages_users_users1` (`user_id` ASC) ,
  CONSTRAINT `fk_access_levels_pages_users_pages`
    FOREIGN KEY (`page_id` )
    REFERENCES `mydb`.`pages` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_access_levels_pages_users_access_levels1`
    FOREIGN KEY (`access_level_id` )
    REFERENCES `mydb`.`access_levels` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_access_levels_pages_users_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `mydb`.`users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB

Now, I'm not sure Cake will bake this table, so you might have to try and make the models by hand, this table would have belongsTo the 3 other tables. The other 3 tables non association tables will have to have a HMABTM relationship with the other 2, as in users HMABTM access_levels and pages and so on.
Again, not sure if it will work. I would suggest maybe trying to see if you can model it in a different manner.

A: Let me generalize it by describing it with generic tables:
Lets say you have 3 tables - firsts, seconds, thirds - each with primary keys 'id'.
let your join table be called 'firsts_seconds_thirds' with foreign keys to each main table:

*

*first_id

*second_id

*third_id

*<additional fields of this association table>

usually we define HABTM relationships between tables, in this case we need to create a cake model for the join table - lets call it FirstsSecondsThird (By cakePhp's naming conventions)
The relationship between models you need to define is:

*

*First hasMany FirstsSecondsThird

*Second hasMany FirstsSecondsThird

*Third hasMany FirstsSecondsThird

*FirstsSecondsThird belongsTo First,Second,Third

The need for this is explained here - Associations: Linking Models Together
Code for the same:
class First extends AppModel {
    public $hasMany = array(
        'FirstsSecondsThird'  => array(
            'className' => 'FirstsSecondsThird',
            'foreignKey' => 'first_id'
        )
    );
}

//Same for classes 'Second' and 'Third'

class FirstsSecondsThird extends AppModel {
    public $belongsTo = array(
        'First' => array(
            'className' => 'First',
            'foreignKey' => 'first_id'
        ),
        'Second' => array(
            'className' => 'Second',
            'foreignKey' => 'second_id'
        ),
        'Third' => array(
            'className' => 'Third',
            'foreignKey' => 'third_id'
        )
    );
}

The models are perfectly setup, but now inserting/updating/deleting from the main/join table should be done correctly or they are of no use.
Model::saveMany() and Model::saveAssociated(), using the option 'deep' etc. need to be used. Read about it here. You also need to think about ON DELETE RESTRICT/CASCADE for these join tables and model them appropriately.

A: Look up ACL. It is complicated, but it is what you need (especially if you need the flexibility in setting up who can moderate what page)


text:
Q: Asterisks in front of array names in Groovy? I'm a bit new to Groovy, so I'm sure this is one of those extremely obvious things...but it's difficult to search for via Google.
In other languages, asterisks tend to represent pointers. However, in this snippet of Groovy code:
byte[] combineArrays(foo, bar, int start) {
  [*foo[0..<start], *bar, *foo[start..<foo.size()]]
}

I can only imagine that that's not the case. I mean, pointers? Groovy?
I'm assuming that this code intends to pass the members of foo and bar as opposed to a multidimensional array. So what exactly do the asterisks mean?
Thanks a lot for your help.

A: When used like this, the * operator spreads a List or Array into a list of arguments. That didn't help at all, did it? How about an example instead? Say we have this function:
def add(Number a, Number b) {
  return a + b
}

And this List
def args = [1, 2]

We shouldn't do this:
add(args)

because the function expects two numeric arguments. But we can do this:
add(*args)

because the * operator converts the List of 2 elements into 2 arguments. You can use this operator with Lists and Arrays.


text:
Q: How to set value with NX option and expire using ServiceStack.Redis? I'm using ServiceStack.Redis to execute commands on REDIS.
I would like to simply set value with expire and NX option (which is : set only if not exists).
SET resource_name my_value NX PX 30000
The problem is that ServiceStack.Redis client has only two methods:
client.SetValue() // <-- this one has Timespan expire argument
client.SetValueIfNotExists() // <-- this one doesn't

Is there a way to do this ?

A: I see a public bool SetValueIfNotExists(string key, string value, TimeSpan expireIn) in RedisClient.cs, line 183
Please mention what version are you using if you don't see it in your included package.


text:
Q: How to set Caps Lock as Hyper (and change modifiers) using xkb? This is currently my .xsessionrc file:
xmodmap -e "remove Mod4 = Hyper_L" -e "add Mod3 = Hyper_L" -e "lock = Hyper_L" -e "keysym Caps_Lock = Hyper_L" &
bspwm &
xfdesktop -D &

What I did was unset Hyper_L as a Mod4 modifier (which is taken by the Super key), remove it from the Lock modifier (because it also made uppercase letters), set it to Mod3 and then bind the Caps_Lock key as Hyper_L.
This works, but I'd like to achieve this using setxkbmap. I know that I can just use setxkbmap -option caps:hyper but I should also set the appropriate modifiers and I have no idea on how to do this.
Also, is .xsessionrc the appropriate file to put such commands?


text:
Q: c# ASP.NET Controls collections code block nonsense What can cause:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

I ask because, the code does not contain code blocks. Anywhere. There is not a single <%= %> block on any page in the entire site. All i have are the <%@ %> directive lines.
Edit:
Below is the code causing the error.
/// <summary>
/// Adds javascript variables to a page so that ASP control ID are accessable via Javascript. The
/// variable names are ASP_ControlID.
/// </summary>
/// <param name="page">The Page to add the javascript to</param>
/// <param name="ctls">The controls to make accessable</param>
public static void addJavascriptIDs(Page page, params Control[] ctls)
{
    Literal litJS = new Literal();
    litJS.Text = getJavascriptIDs(ctls);
    page.Form.Controls.Add(litJS);  ////////// <-- Error Here
}

/// <summary>
/// Returns a string containing the javascript to allow javascript to access
/// ASP controls.
/// </summary>
/// <param name="ctls">The HTML and javascript to create the javascript variables</param>
/// <returns>The script</returns>
public static string getJavascriptIDs(params Control[] ctls)
{
    string js = "\n<script type=\"text/javascript\">\n";
    foreach (Control ctl in ctls)
        js += "\tvar ASP_" + ctl.ID + " = '" + ctl.ClientID + "';\n";
    js += "</script>\n\n";

    return js;
}

This is the Page_Load function:
protected void Page_Load(object sender, EventArgs e)
{
    formHowHear.Attributes.Add("onChange", "displayOther(this);");
    LoadValues();
    if (!IsPostBack)
    {
        LoadDefaults();
        BindValidation();
    }
    else
    {
        Submitted();
    }
    CMSUtil.addJavascriptIDs(this, formEmail1, formEmail2, formUsername);
    CMSUtil.addJavascriptIncludes(Page,
        ResolveUrl("~/js/jquery-1.4.2.min.js"),
        ResolveUrl("~/admin/js/TVCMS.js")
        );
}

A: maybe you have some custom control that contains <% %>, for example ajaxcontroltoolkit calendar. i had that same problem once, and the only solution was to remove that control.
try removing/commenting pieces of code so you can locate exactly what causes the problem.
EDIT: not sure if this corrects the problem, but this is the correct way to inject js:
public static void addJavascriptIDs(Page page, params Control[] ctls)
{
    string js = "";
    foreach (Control ctl in ctls)
        js += string.Format("var ASP_{0} = '{1}';", ctl.ID, ctl.ClientID);
    page.ClientScript.RegisterClientScriptBlock(typeof(object), "IDs", js, true)
    /* http://msdn.microsoft.com/en-us/library/bahh2fef.aspx */
}
public static void addJavascriptIncludes(Page page, params string[] scripts)
{
    foreach (string script in scripts)
        page.ClientScript.RegisterClientScriptInclude(typeof(object), script, page.ResolveUrl(script));
    /* http://msdn.microsoft.com/en-us/library/kx145dw2.aspx */
}


text:
Q: Problemas con jQuery y css en angular2 Estoy desarrollando una aplicación web en angular2 donde esta formada por la siguiente estructura: una cabecera, un menú lateral izquierdo desplegable, el contenido de la app en la parte derecha y un footer al final.
Mi problema es como lograr que el height del menú siempre llegue hasta el footer cuando el contenido de la página es muy grande y que cuando el contenido de la página sea muy pequeño el footer se quede en el pie de la pantalla.
He visto varios ejemplos de realizar esto con jQuery que funcionan bien cada vez que se recarga la página o con el $(window).resize(function () {}); pero como en angular su contenido cambia sin recargar la página no me funcionan.
Quisiera que alguien me mostrara un ejemplo de como realizar esto en angular2. Saludos

A: Lo primero, no juntes jQuery y Angular, o uno o el otro.
Lo segundo, prueba con esto y me dices.
<div (window:resize)="onResize($event)">

+
onResize(event) {
  event.target.innerWidth;
}

o
@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

Suponiendo que los traget globales son window, document, and body.
Fuente


text:
Q: How to set framerate for IMFSourceReader I'm using Media Foundation for video capture in the following simplified algorithm:

*

*Call MFCreateDeviceSource to get capture source

*Call MFCreateSourceReaderFromMediaSource to create source reader

*Enumerate formats of source reader and select desired

*SetCurrentMediaType on IMFSourceReader to set desired format.

*Call ReadSample on IMFSourceReader synchronously to get samples

Question:
How to set framerate so ReadSample will return frames at specified framerate?
I tried to set framerate in 4. with MFSetAttributeRatio( format, MF_MT_FRAME_RATE, num, denom ) with no luck. Seems that some cameras give me samples at 30 fps, some at 15 fps and they dont respect fps set in format. I also checked MF_MT_FRAME_RATE_RANGE_MAX and my fps is valid.
I've got webcam which gave me 30 fps when using DirectShow and format says it supports 30fps. But I can get only 15 from it using Media Foundation.

A: Found the answer for myself.
One can't set framerate on IMFSourceReader.
One should set desired format on IMFMediaSource and then wrap it with IMFSourceReader.


text:
Q: What is T_Echo and T_Print There's alot of questions asking for help troubleshooting errors when T_Echo and T_Print arise, but what does the T_ mean?

A: It stands for "token". PHP source code is split into tokens, then interpreted. This process is known as tokenization.
See this page for a list of PHP tokens.
You can see for yourself how tokenization works by running token_get_all() on a piece of PHP code.
The reason why these often come up in basic troubleshooting questions is that the OP has made a syntax error, and the parser encounters an unexpected token as a result of that.


text:
Q: boost::asio server - detect failure to listen to server port I have a boost::asio based server which works fine, except that I'm trying to add a check that nothing else is accepting connections on the same port. If I create two of the servers, one of them consistently accepts the connections, but the other does not report any error ( which of the two accepts all connections appears to be random ).
The relevant bits of the server class ( it's a template which uses a base class which has Accepted() and typedefs for the connection type to create ) are:
        MessageServer ( boost::asio::io_service &io, unsigned short port_num )
            : BaseServerType ( io ), acceptor_ ( io, boost::asio::ip::tcp::endpoint ( boost::asio::ip::tcp::v4(), port_num ) ) {
            Listen();
        }
        void Listen () {
            boost::system::error_code ec;
            acceptor_.listen ( boost::asio::socket_base::max_connections, ec );

            if ( !ec ) {
                start_accept();
            } else {
                // not reached even if a separate process
                // is already listening to that port
                connection_pointer new_connection;
                BaseServerType::Accepted ( new_connection );
            }
        }

    private:
        void start_accept() {
            connection_pointer new_connection ( CreateConnection ( acceptor_.io_service() ) );

            acceptor_.async_accept ( new_connection -> Socket(),
                                     boost::bind ( &MessageServer::handle_accept, this, new_connection,
                                                   boost::asio::placeholders::error ) );
        }

        void handle_accept ( connection_pointer new_connection, const boost::system::error_code &error ) {
            if ( !error ) {
                BaseServerType::Accepted ( new_connection );
                new_connection -> Start();
                start_accept();
            } else {
                // never reached
                new_connection.reset();
                BaseServerType::Accepted ( new_connection );
            }
        }

        boost::asio::ip::tcp::acceptor acceptor_;

acceptor.listen() doesn't throw either.
How is a failure to listen to a server port reported in boost::asio?

A: boost::asio::ip::tcp::acceptor constructor you use has a default argument reuse_address = true. this sets SO_REUSEADDR socket option. disabling this option you'll receive error on acceptor.listen(). more info about SO_REUSEADDR here
Be aware that this option is treated differently on windows and linux

A: The error you want would be thrown or returned from boost::asio::ip::tcp::acceptor::bind(). The constructor you are using will exhibit this same behavior, I suggest you boil your example down to something smaller that is reproducible. It is not obvious to me how you handle exceptions thrown from your MessageServer ctor.


text:
Q: asp:TextBox Disabled style is not consistent in different Browsers ASP.NET
When TextBox1.Enabled = false; it has a gray background in FF3, but no change in IE8 or Chrome. So it's harder to tell if it's disabled or not. Is there any more general way to make the disable textbox rendered more consistent on a top-level? So I don't need to change this for every page or every website? Please advise, thanks.

A: You could set a CSS style to handle disabled text controls to render them consistently.  For example, something like the following:
input[type="text"][disabled] {
    background-color: #ECECEC;
    border: solid 1px #7F9DB9;
    color: #CCCCCC;
}

For IE7 support (and possibly even IE8), a !DOCTYPE must be specified or CSS attribute selectors will not work.  Unfortunately, if you require support for IE6 this will not work and you have to use a CSS class on any text input instead.

A: You can assign a CSS class to it using the CssClass property and control it as much as you want.
More on the CssClass property here.
Sample CSS:
.DisabledTextBox {
  background-color: #C0C0C0;
  border: solid 1px #A0A0A0;
  color: #A0A0A0;
}

Then use the CssClass like this:
<asp:TexbBox id="DisabledTextBox" CssClass="DisabledTextBox" value="Some Value" />


text:
Q: check_nrpe and non-fixed counter names For some counters I have noticed Windows convently does provide a stable name for them, for example:
\.NET Data Provider for SqlServer(_lm_w3svc_3_root-1-123412341234[6789]\Number of Free Conections

Where god knows what 1234 is and 6789 is the PID. These counters don't present any sort of _Total instance either. Normally I monitor perfmon counters using check_nrpe from Nagios but am not sure how I might work with these that have dynamic names -- any ideas?


text:
Q: VT-x is not available (VERR_VMX_NO_VMX) when starting ubuntu in Virtualbox My operating system is windows 10 64 bit.I want to have ubuntu on my system for some development.
So I have installed VirtualBox and Kept ubuntu v18.04.2 in it.
But while Starting I am getting this error "The native API dll was not found (C:\Windows\system32\WinHvPlatform.dll) (VERR_NEM_NOT_AVAILABLE).
VT-x is not available (VERR_VMX_NO_VMX)."

How to fix it?

A: It is a known issue when running 64-bit VMs in VirtualBox 6.x on Windows 10.
The culprit is Windows Defender Application/Device Guard.

*

*Method 1
To disable it go to Local Group Policy Editor (Win+R->gpedit.msc) and disable Turn on Virtualization Based Security
Local Computer Policy > Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security

Disable Virtualization Based Security in Local Group Policy Editor
Then you need to run the below commands in command line as an Administrator:
mountvol X: /s
copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y
bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"
bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:
mountvol X: /d

where X: is your unused drive letter (can be any other drive letter)
Reboot you computer and confirm disabling Device Guard and Virtualization Based Security by pressing F3 at boot.
After that your virtual machines will be working again.

*

*Method 2
Another way to disable Device Guard is to use PowerShell script.
Download the script from Microsoft: https://www.microsoft.com/en-us/download/details.aspx?id=53337
Run the script as an Admin:
.\DG_Readiness.ps1 –Disable -AutoReboot

A: I found the answer and like to share with you.

*

*Enable Virtualization during your BIOS time

*Disable the Hyper-V role through Settings(problem faced by me)

*

*Right click on the Windows button and select 'Apps and Features'.

*Select Programs and Features on the right under related settings.

*Select Turn Windows Features on or off.

*Select Hyper-V and disable it.

A: I found the answer and like to share with you .
1.Enable Virtualization during your BIOS time
2.Disable the Hyper-V role through Settings(problem faced by me)
 a)Right click on the Windows button and select 'Apps and Features'.

 b)Select Programs and Features on the right under related settings.

 c)Select Turn Windows Features on or off.

 d)Select Hyper-V and disable it

A: Please check the following link:
https://stackoverflow.com/a/38111013/15374795
This answer belongs to -- credit Tj Kellie please do not add like for me.
Note: open Command Prompt by right click on that and click on "Run as administration".
To turn Hypervisor off, run this from Command Prompt (Admin) (Windows+X):
bcdedit /set hypervisorlaunchtype off

and reboot your computer. To turn it back on again, run:
bcdedit /set hypervisorlaunchtype on

If you receive "The integer data is not valid as specified", try:
bcdedit /set hypervisorlaunchtype auto

Important note: after turning off the Hypervisor and restarting the system it is mandatory to turn on the Hypervisor because with out Hypervisor you can not use the git repository on your windows.

A: useful page
mine is Winows 10, just enabling 2 Virutal options which are 'Disable ' during BIOS time by default, has worked smooth.
thanks.


text:
Q: Tab key is not working using HTML and javascript I have one issue in Tab key enter using HTML.I am explaining my code below.

   User Name :

      <input type="text" name="uname" id="uname" class="form-control" placeholder="add user Name" ng-model="login_name" ng-minlength="6" ng-keypress="clearField('uname');" >

This field is too short.The min length of your user name should be 6.

   <button class="btn btn-xs btn-success"ng-mousedown="hideShowPassword();" ng-mouseup="hideShowPassword();" ng-mouseleave="hidePassAfterLeave();"  ></button>
   Password :

      <input type="{{inputType}}" name="pass" id="passno" class="form-control" placeholder="password" ng-model="password" ng-minlength="8" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[_!@#\$%\^&\*])(?=.{8,})/" ng-keypress="clearField('passno');" >

In the above code suppose user's focus first in the user name field.In this condition when user is pressing tab key focus is not moving to password field but 2 times pressing the tab key the focus is happening on password field.Here i need for first time pressing tab key the focus should go to password field.Please help me.

A: Set attribute
tabindex="-1"

to the posts you want to skip
Check this fiddle:
JSFIDDLE


text:
Q: Intermittent exception: App engine throws null pointer excetion. Not sure if this has to do with any URL connection issue App engine always throws this exception. I am not sure what i am doing wrong.
javax.servlet.ServletException: Exception in MY job classjava.lang.NullPointerException
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:37)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:50)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)


text:
Q: React-Native Android actions error: 'undefined is not an object (evaluating 'action.type')' i'm using React Native v.43.0-rc.3 and have this error in my Android emulator when i hit my toggle button:
undefined is not an object (evaluating 'action.type')

My toggle button is connected to a function in /action/index.js:
export const toggleUpdateSwitch = (showUpdates) => {
  // error goes away when i remove this line below ----+v
  AnalyticsTracker.trackEvent({"category": "profile", "action" : "toggle", "label": "section/updates"})

  async dispatch => {
    ToastAndroid.show(TOGGLE_UPDATES_NO_DATA_MESSAGE, ToastAndroid.LONG, ToastAndroid.CENTER);
    const response = await fetch('http://my.url.com/doSomething', { headers, method: 'GET' });
  }
}

So i added the line above (AnalyticsTracker), and that's what causes the error when i toggle. Any ideas?
Emulator error screenshot:

A: I had an issue like this before. You have to put the tracker code inside your async dispatch. From my experience, whenever I have async dispatch in my functions, I always get this error if I have synchronous code outside of it. I don't have a clear idea of why this is happening, but I know that fixed it for me.
My theory is that when you do an async, you are starting a different thread. By having synchronous code outside of it, there is something happening on the main thread but it is not returning anything. Hence you get undefined is not an object when you do action.type because the by default I think RN expects an object with a type attribute to be returned back, but you aren't returning anything back.


text:
Q: Let thread wait for dialog input I have programmed a structure that works like this:
Activity discoveryActivity - UI thread
 ↕ Calls through interface
Service discoveryService   - Bound service running on UI thread
 ↕ Actions through Handler.post(↑) or functions (↓)
Runnable connectionThread  - Socket networking

At some point the connectionThread needs a String to continue.

*

*So I make a call with Handler.post(..) to the discoveryService which

*notifies the discoveryActivity to show an AlertDialog
The user needs about 20 seconds to input the data and will confirm the input.
Problem 1: What will the thread do in the meantime?
Now I need to make my way down to the Thread again.
Getting to discoveryService is easy
Problem 2: How can I get the thread working again without restarting? The thread is in a complex loop with a few Sockets right now!
My first idea was to keep the thread running
// Inside run()
while(stringWrapper.get() == null) {
    Thread.sleep(500);
}

// Outside run()
void setStr(String s) { stringWrapper.set(s); }

But that is inefficient
Then I read about wait() and notify()
I tried that on the thread itself and on the StringWrapper (A simple class that holds a reference to a String)
I am helpless right know and I think wait() and notify() are the right way to go?
Can you give me a hint where I should implement these and on which object they would be called?
TL;DR: I want to let a thread pause until it receives data

A: Not 100% sure what you're trying to accomplish, but you may be able to use a SettableFuture (from Google Guava library) to solve your issue.
private final SettableFuture<String> stringFuture = SettableFuture.create();

// Inside run()
// This will block your thread until stringFuture is set, or until the given timeout has expired.
final String string = stringFuture.get(1, TimeUnit.MINUTES);

// Outside run()
public void setStr(final String s) {
    stringFuture.set(s);
}


text:
Q: is for loop allowed in autoValue Collection2? Would it be possible to create 'updatesHistory.$.date' (where $ is from 0 to n) using autoValue? My for statement looks like it cannot be executed in autovalue function.
// Whenever the "content" field is updated, automatically
// update a history array.
updatesHistory: {
type: [Object],
optional: true,
autoValue: function() {
  var content = this.field("content");
  if (content.isSet) {
    if (this.isInsert) {
      return [{
          date: new Date,
          content: content.value
        }];
    } else {
      return {
        $push: {
          date: new Date,
          content: content.value
        }
      };
    }
  } else {
    this.unset();
  }
}
},
'updatesHistory.$.date': {
type: Date,
optional: true
},
'updatesHistory.$.content': {
type: String,
optional: true
},


text:
Q: Pandas groupBy multiple columns and aggregation In dataframe have 4 columns col_A,col_B,col_C,col_D.Need to group the columns(col_A,col_B,col_C) and aggregate mean by col_D. Below is the code snippet I tried and it worked
df.groupby(['col_A','col_B','col_C']).agg({'col_D':'mean'}).reset_index()
But in addition to the above result, also require the group by count of ('col_A','col_B','col_C') along with aggregation. Any help on this please.

A: Using Named Aggregation:
result = (
    df.groupby(['col_A', 'col_B', 'col_C'], as_index=False)
      .agg(mean=('col_D', 'mean'), count=('col_D', 'count'))
)

For the count columns, you have 2 choices in choosing the aggregate function:

*

*count=('col_D', 'count') will ignore any NaN value in col_D

*count=('col_D', 'size') will include NaN values in col_D


text:
Q: bash: 'export: command not found There is a mistake every time a new terminal is opened,
error: "bash: 'export: command not found"
I only copy export all_proxy="" and export ALL_PROXY="" to terminal,then when I open a new terminal,in the picture of the situation will be appear.
This is picture:

I input the command:
grep export ~/.bashrc

ouput:

I input the command:
env SHELLOPTS=xtrace \
    BASH_XTRACEFD=7 \
    PS4='[${BASH_SOURCE:-$BASH_EXECUTION_STRING}:$LINENO]> ' \
    7> >(grep ') bash -l

output:

A: Assuming you've copy-pasted that command as-is, it's complaining about the 'export command being not found where that ' is the U+2018 left single quotation mark non-ASCII character (not to be confused with the ASCII ' apostrophe/single-quote (U+0027) or ASCII ` backtick/grave accent (U+0060) character).
Since that character is not special in any way to bash, a command line like:
'export foo=bar'

(where ' is U+2019, the right single quotation mark)
Is interpreted as running the 'export command with foo=bar' as argument. Had you written:
'export foo=bar'

instead, that is with those U+2018 and U+2019 replaced with ASCII apostrophe, a character that is special to bash as it's a quoting operator, that would have been treated as running the export foo=bar command with no argument. There is no such command. That is not what you want either.
You want
export foo=bar

or
'export' 'foo=bar'

That is to run the export command with a foo=bar argument.
Here, you'll need to remove that U+2018 character (and possibly the corresponding U+2019 character if any) wherever you've inserted it in your ~/.bashrc or elsewhere. Wherever you copy-pasted that code from, those characters were not intended to be copied.
To find where that bogus command has been introduced if not in ~/.bashrc (though your latest edit shows it is in your ~/.bashrc indeed), you could try running:
env SHELLOPTS=xtrace \
    BASH_XTRACEFD=7 \
    PS4='[${BASH_SOURCE:-$BASH_EXECUTION_STRING}:$LINENO]> ' \
    7> >(grep ') bash -l

(the $PS4 would be ignored by shells running as root with bash-4.4 or newer however, which seems to be your case, which is why you see ++ instead of the file name and line number).

A: It looks like you have edited your .bashrc file.
I can replicate this error exactly if I put
''export'

as the last line in my .bashrc
To check it just execute
grep export ~/.bashrc

If grep gives an output like the above then edit it out of your ~/.bashrc file.
Edit: From your last post edit you can see that you have 2 lines starting 'export delete them both from ~/.bashrc.


text:
Q: How can I get the get the nodes for a bus route using OSMNX I want to get all the nodes representing bus stops along a specific bus route in Open Street Map using OSMNX.
I tried getting the bus stops for a place;
routes = osmnx.geometries_from_place('London, United Kingdom', tags= {'highway':'bus_stop'})
then using the route_ref attribute, however most of these values are NaN. Instead I thought it would be better to identify relations for specific bus routes so I could get each node, however I don't understand what tags I should be using. I know the relations exist, when viewing OSM, but tags like {'type':'route', 'route':'bus','line':'bus'} return an empty dataframe.
Can anyone please clarify how I can fix this, and help with misunderstands that I may have about using the right tags.
An example of what I would like to find:


text:
Q: How To Add ShortCut Keys to JTextField? I am Stuck in some Step that I Can't Add a Shorcut Key like: CTRL+SPACE to my program  , I am Searching for  one week and I could'd find any
answers .

A: You'll want to look at the Java Tutorial for a good overview of Key Bindings.
Here's a quick example:
import java.awt.event.*;
import javax.swing.*;

public class KeyBindings extends Box{
    public KeyBindings(){
        super(BoxLayout.Y_AXIS);
        final JTextPane textArea = new JTextPane();
        textArea.insertComponent(new JLabel("Text"));
        add(textArea);

        Action action = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.setText("New Text");
            }};
         String keyStrokeAndKey = "control SPACE";
         KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
         textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
         textArea.getActionMap().put(keyStrokeAndKey, action);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new KeyBindings());
        frame.pack();
        frame.setVisible(true);
    }
}


text:
Q: y values in a bar plot according to a colormap I have already searched on the forum, finding this, but my question is bit different.
As you can see from the code and the image below, I have created a map with colormap "virdis".
How can I create individual bar-plots with the same colormap? I would like to color the 4 color-bars (that now are colored with simple colors) so that the values on the y axes correspond to those of the colorbar, is it possible?
I have this matrix:
matrix=[[ 0  0  0  0 17 25 29 35 36 41]
 [16 22 17 10  9 21 23 27 26 22]
 [ 8 19 13 16 13  5  4 11  5  4]
 [ 3 11 10  8  7  1  0  0  0  0]]
in this code:
fig, ax = plt.subplots(figsize=(7, 10))

im = ax.imshow(matrix, cmap='viridian')

ax.set_xticks([0,1,2,3,4,5,6,7,8,9])
ax.set_xticklabels(['0.5','1.0','1.5','2.0','2.5','3.0','3.5','4.0','4.5','5.0'])
ax.set_xlabel('Redshift')
ax.set_yticks([-0.5,0.5,1.5,2.5,3.5])
ax.set_yticklabels(['50k','10k','1k','0.1k','0'])
ax.set_ylabel('counts')

divider = make_axes_locatable(ax)
axHistx1 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx1.xaxis.set_tick_params(labelbottom=False)
axHistx2 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx2.xaxis.set_tick_params(labelbottom=False)
axHistx3 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx3.xaxis.set_tick_params(labelbottom=False)
axHistx4 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx4.xaxis.set_tick_params(labelbottom=False)

cbaxes = fig.add_axes([0.125, 0.03, 0.774, 0.04])
cbar=fig.colorbar(im, label='match num.', cax = cbaxes, orientation="horizontal", boundaries=np.linspace(0,50,1001),
                  ticks=[0,10,20,30,40,50])
cbar.set_clim(0,50)

#print(matrix)
row0 = np.array(matrix[0,:])
row1 = np.array(matrix[1,:])
row2 = np.array(matrix[2,:])
row3 = np.array(matrix[3,:])
col0 = np.array(matrix[:,0]).T
col1 = np.array(matrix[:,1]).T
col2 = np.array(matrix[:,2]).T
col3 = np.array(matrix[:,3]).T
col4 = np.array(matrix[:,4]).T
col5 = np.array(matrix[:,5]).T
col6 = np.array(matrix[:,6]).T
col7 = np.array(matrix[:,7]).T
col8 = np.array(matrix[:,8]).T
col9 = np.array(matrix[:,9]).T

zbin = [0,1,2,3,4,5,6,7,8,9]
row0 = row0.ravel();row1 = row1.ravel();row2 = row2.ravel();row3 = row3.ravel();

axHistx1.bar(zbin, row3, color='orange', alpha=0.5, edgecolor=['orange']*len(zbin))
axHistx1.set_ylim(0,50)
axHistx1.set_ylabel('match')
axHistx2.bar(zbin, row2, color='r', alpha=0.5, edgecolor=['r']*len(zbin))
axHistx2.set_ylim(0,50)
axHistx2.set_ylabel('match')
axHistx3.bar(zbin, row1, color='g', alpha=0.5, edgecolor=['g']*len(zbin))
axHistx3.set_ylim(0,50)
axHistx3.set_ylabel('match')
axHistx4.bar(zbin, row0, color='cornflowerblue', alpha=0.8, edgecolor=['cornflowerblue']*len(zbin))
axHistx4.set_ylim(0,50)
axHistx4.set_ylabel('match')
ax.axis('tight')

plt.show()

A: To colorize bars you could loop over the bars and set the color. This is shown e.g. in this question Plot histogram with colors taken from colormap for histograms. For bars it is easier, as shown e.g. in How can I convert numbers to a color scale in matplotlib?
bars = plt.bar(x, y, color=list_of_colors)

Now you need to find out which color you would actually like to give the bars. To this end you would rely on the colormap and the norm from the image which is produced earlier on,
plt.bar(x, y, color=im.cmap(im.norm(y)))

Using loops to get rid of the redundant code would also make sense as  well using subplots instead of make_axes_divisable.
import numpy as np
import matplotlib.pyplot as plt

matrix=[[ 0,  0,  0,  0, 17, 25, 29, 35, 36, 41],
     [16, 22, 17, 10,  9, 21, 23, 27, 26, 22],
     [ 8, 19, 13, 16, 13,  5,  4, 11,  5,  4],
     [ 3, 11, 10,  8,  7,  1,  0,  0,  0,  0]]

fig, axes = plt.subplots(nrows = 5, sharex=True, figsize=(6, 8),
                         gridspec_kw=dict(height_ratios=[1,1,1,1,3]))
fig.subplots_adjust(top=0.95, bottom=0.05)
ax = axes[-1]
im = ax.imshow(matrix, cmap='viridis', aspect="auto")

ax.set_xticks([0,1,2,3,4,5,6,7,8,9])
ax.set_xticklabels(['0.5','1.0','1.5','2.0','2.5','3.0','3.5','4.0','4.5','5.0'])
ax.set_xlabel('Redshift')
ax.set_yticks([-0.5,0.5,1.5,2.5,3.5])
ax.set_yticklabels(['50k','10k','1k','0.1k','0'])
ax.set_ylabel('counts')

#cbaxes = fig.add_axes([0.125, 0.03, 0.774, 0.04])
cbar=fig.colorbar(im, label='match num.', ax = axes[-1],  pad=0.2,
                  orientation="horizontal", boundaries=np.linspace(0,50,1001),
                  ticks=[0,10,20,30,40,50])
cbar.set_clim(0,50)

zbin = [0,1,2,3,4,5,6,7,8,9]

for i, ax in enumerate(axes[:-1]):
    y = np.array(matrix)[i,:]
    bars = ax.bar(zbin, y, color=im.cmap(im.norm(y)))
    ax.set_ylim(0,50)
    ax.set_ylabel('match')

plt.show()


text:
Q: Joining a Bag of Tuples into a Single String without any Custom Pig UDFs How do I concatenate a bag of tuples (ex: {(664),(823),(8),(47),(35),(27),(13),(16),(4),(8),(6)}) into a single string with Pig Latin that does not rely on writing a custom UDF?

A: this is an example for a UDF concatenating strings which are tuples in a bag assuming there is 1 item in each tuple (string delimiter in the output will be an '_'):
#!/usr/bin/python

@outputSchema("schema:chararray")
def convertBagToStr(acctBag):
    return "_".join([str(i[0]) for i in sorted(acctBag)])

in the Pig script :
register '$udf_dir/myUDF.py' using jython as funcs;

a = foreach mygroup generate funcs.convertBagToStr(mybag) as bag_str;

A: There is no way to do this in just Pig Latin. According to Programming Pig, bags are unordered collections of tuples. Thus, trying to concatenate them gives an ambiguous result unless you were able to specify an ordering—which is possible through a custom UDF.


text:
Q: jqPlot - Different color bars based on value range for each data point in series I need to change the color of a bar chart conditionally for each data point in one series. 1 data point in the series needs to have different thresholds for the color than the other 4 data points.
I tried to implement the suggestions found at this SO post, but I'm getting a JS error that the object doesn't have the method get.
This is the data I'm working with:

Series 2 needs to have colors varied. The data to produce these series are here

*

*threshold data contains [ [2,1], [4,2], [6,3], [3,4], [8, 5] ]

*results data contains [ [6,1], [6,2], [4,3], [6,4], [6, 5] ]

The results data refer to the blue bar chart lines and threshold data to the orange line.
For element one of results to element 4, I need the following results:
if the first element of the inner array is >= 0 and <= 4, the bar should be red
if the first element of the inner array is >=5 and <= 7, the bar should be yellow
if the first element of the inner array is >=8 and <= 11, the bar should be green.
For element five of results, I need:
if the first element of the inner array is >= 0 and <= 5, the bar should be red
if the first element of the inner array is >= 6 and <= 11, the bar should be green.
As an example, if resultsSeries[0][0] === 4 then bar color should be red.
At this point, I'm fine with even iterating over the chart somehow after it has been generated and changing it that way but I'm not sure how to do that. I inspected the elements on it and just got a canvas and I don't quite understand how jqPlot is affecting the items within it or what it has named them.
Link to jsFiddle.net
It results in the following error:
Uncaught TypeError: Object [object Object] has no method 'get'
jqplot.barRenderer.js:280
$.jqplot.BarRenderer.draw jqplot.barRenderer.js:280
Series.draw jquery.jqplot.js:1065
drawSeries jquery.jqplot.js:2735
draw jquery.jqplot.js:2249
$.jqplot jquery.jqplot.js:164
(anonymous function) jqplot_example.html:71
n jquery.min.js:2
o.fireWith jquery.min.js:2
e.extend.ready jquery.min.js:2
c.addEventListener.C

A: When you want to override it, you should implement all its methods. This is from the source code and you need to implement get and setColors methods.
function (colors) {
    colors = colors || $.jqplot.config.defaultColors;
    var idx = 0;

    this.next = function () {
        if (idx < colors.length) {
            return colors[idx++];
        }
        else {
            idx = 0;
            return colors[idx++];
        }
    };

    this.previous = function () {
        if (idx > 0) {
            return colors[idx--];
        }
        else {
            idx = colors.length-1;
            return colors[idx];
        }
    };

    // get a color by index without advancing pointer.
    this.get = function(i) {
        var idx = i - colors.length * Math.floor(i/colors.length);
        return colors[idx];
    };

    this.setColors = function(c) {
        colors = c;
    };

    this.reset = function() {
        idx = 0;
    };

    this.getIndex = function() {
        return idx;
    };

    this.setIndex = function(index) {
        idx = index;
    };
}

A: seriesColors: value < threshold ? ["#ff0000"] : ["#00ff00"];


text:
Q: Approximating musical pitch function (the function $2^x$) I have an old digital synthesizer and I would like to understand how its pitch control was implemented. A perfect representation of a given pitch in an equal temperament scale with the concert pitch of $440$ is given by
$$f(x)=2^{x/1200}\cdot440,$$
where different values of $x$ output different pitches and in this case we consider the values $x=300-1200, 310-1200, 320-1200,...,1500-1200$. In musical terms the output is an octave of pitches starting from middle C, in ten cent intervals.
The synthesizer uses $24$ bit arithmetic for representing pitches, and a sampling rate of $88200$ samples per second, this means representing only pitch values of the form $y\cdot \frac{88200}{2^{24}}$ is possible, for integer $y$. After recording, we obtain the following values $y$, and would like to find a function that goes through all of the points.
49767, 50052, 50344, 50635, 50927, 51225, 51519, 51820, 52118, 52421, 52725, 53029, 53336, 53645, 53955, 54268, 54584, 54900, 55219, 55538, 55860, 56182, 56510, 56835, 57166, 57497, 57819,
58156, 58490, 58831, 59171, 59514, 59860, 60207, 60556, 60905, 61258, 61613, 61971, 62330, 62691, 63053, 63417, 63785, 64155, 64526, 64900, 65276, 65656, 66036, 66418, 66804, 67181, 67570,
67961, 68356, 68751, 69149, 69550, 69954, 70358, 70765, 71175, 71588, 72004, 72420, 72840, 73262, 73687, 74112, 74541, 74975, 75409, 75847, 76284, 76728, 77171, 77627, 78076, 78532, 78988,
79443, 79905, 80367, 80831, 81299, 81770, 82244, 82721, 83201, 83684, 84170, 84656, 85145, 85637, 86135, 86633, 87137, 87639, 88149, 88659, 89172, 89689, 90220, 90743, 91268, 91797, 92328,
92863, 93401, 93941, 94485, 95035, 95585, 96138, 96693, 97255, 97820, 98385, 98956

Contrasting the values of $y$ with the perfect estimates $y_{est}=\text{round}(f(x) \cdot \frac{2^{24}}{88200})$ gives the following plot for $y_{est}-y$

Trying out the "obvious" polynomial approximations such as min-max polynomial for estimating $2^x$ and deriving a suitable approximation does not appear to work. As can be seen the above error function is very jagged and that is essentially why. I would like to ask for possible ideas on what methods could have been used to compute the output pitch values on the synthesizer?


text:
Q: Line break after printing array's element So I have this code which checks if an element of array starts with letter Ա/ա, and prints it by adding into a paragraph. But I can not make every word start from a new line.
for (var i = 0; i < aremove.length; i++) {
  aremove = [...new Set(aremove)].sort()
  if (/^[Աա]/.test(aremove[i])) {
    var word = document.createTextNode(aremove[i])
    document.getElementById("p").appendChild(word)
  }
}

If I add +"
", it's not breaking the line but simply adds
 to words. If I add .join("
") it returns "TypeError: aremove[i].join is not a function" or "word.join is not a function" and so on...

A: By help of Teemu's comment
for (i = 0; i < aremove.length; i++) {
  aremove = [...new Set(aremove)].sort()
  if (/^[Աա]/.test(aremove[i])) {
    word = document.createTextNode(aremove[i])
    linebreak = document.createElement("br")
    document.getElementById("girq").appendChild(word)
    document.getElementById("girq").appendChild(linebreak)
  }
}

I have created a "br" element, and as I can't append an element and text node at once, I appended it separately.


text:
Q: How to randomly select from list within 24 hours once? How do I randomly select from a list but only change values after every 24 hours.
Suppose I have: main_list = [1,2,3,4,5,6,7,8,9]
and I want to see 5 random values, let's say rand_list == 3,4,7,8,1 But  I don't want to update my rand_list for next 24 hours.
What I am trying :
reading current date : 14

Is there any way I can create indexes on the basis of date because it will not change values until date changes?
Like, If it's 14 today , it generates these indexes on the basis of 14: 4,2,8,1,3 . Now as soon it will be 14 , it will again generate same indexes, and I will see same list through-out the day. Is this something we can achieve within python and how?
EDIT:
day = 14

random.seed(day)
print(random.random())

print(random.random())

print(random.random())

print(random.random())

print(random.random())
it generates these 5 numbers : 0.10682853770165568 0.7025855239868555 0.6520420203142754 0.9403523895661179 0.27111522656032316

How do I map these constant numbers to List indexes ?

A: The random module has a lot of flexibility.  If you want 5 choices you can get them all at the same time.
import random
random.seed(day)
rand_list = random.choices(main_list, k=5)

If you'd rather have indexes into your main list rather than values from it, that's easy too.
rand_indexes = random.choices(range(len(main_list)), k=5)


text:
Q: Do you need to run as admin to do Netsh port forwarding using cmd? Simple question I need to know if Netsh port forwarding works without the command prompt running as administrator.
Meaning that I will be running the classic command prompt.
Thank you.

A:  I have tried this netsh command in my cmd with and without admin rights and here is the result:

 As you can see, in both case results turned out to be same and tried
netsh wlan name="" key=clear too, and the results was same, so my conclusion is you'll need not to run your cmd as admin unless you want to make some changes in the computer like, installing/uninstalling directories or programs etc..,


text:
Q: Replacing part of &str in Rust Vec I have written the following code:
use std::str::{from_utf8};

struct JSONPointer {
    segments: Vec<String>
}

fn build_json_pointer(s: Vec<String>) -> JSONPointer {
    JSONPointer { segments: s.iter().map(|x| x.replace("~1", "/").replace("~0", "~")).collect() }
}

fn main() {
    let v = vec!["foo".to_string(), "bar".to_string(), "baz~1".to_string()];
    let p = build_json_pointer(v);

    println!("Hello world! {:?}", p.segments);
}

This all works well with Strings, but ideally my JSONPointer struct would contain a Vec<&str> (if only for learning purposes). The issue I run into takes place in the call to map the replaces a few reserved strings. No matter the combination of conversions I use, I am always told that my borrowed value does not live long enough.
I understand that I am taking a reference to a local value and trying to return it (leading to a possible use-after-delete error), but I can't seem to find a way to take a copy of the string.
EDIT: Updated to minimum reproducible form
I realize now that when I was referring to wanting a "copy" (heap allocated), that's exactly what String is. There was talk about a cleaner way of doing this possibly though.

A: If you are worried about needlessly allocating strings, there is the possibility of using a Cow:
use std::borrow::Cow;

struct JSONPointer<'a> {
    segments: Vec<Cow<'a, str>>,
}

fn replace_if<'a>(s: Cow<'a, str>, from: &str, to: &str) -> Cow<'a, str> {
    if s.contains(from) {
        Cow::Owned(s.replace(from, to))
    } else {
        s
    }
}

fn build_json_pointer<'a>(s: &[&'a str]) -> JSONPointer<'a> {
    let segments = s
        .iter()
        .copied()
        .map(Cow::Borrowed)
        .map(|x| replace_if(x, "~1", "/"))
        .map(|x| replace_if(x, "~0", "~"))
        .collect();

    JSONPointer { segments }
}

fn main() {
    let v = vec!["foo", "bar", "baz~1"];
    let p = build_json_pointer(&v);

    println!("Hello world! {:?}", p.segments);
}

This has the advantage that it doesn't need to allocate any memory when no replacements need to be made, but has the downside that each pattern has be be searched twice. It could potentially be even more efficient with a structure like a rope.
For your original case that accepted a String, you could do something similar without Cow by keeping the original String and not unconditionally replacing it:
struct JSONPointer {
    segments: Vec<String>,
}

fn replace_if(s: String, from: &str, to: &str) -> String {
    if s.contains(from) {
        s.replace(from, to)
    } else {
        s
    }
}

fn build_json_pointer(s: &[String]) -> JSONPointer {
    let segments = s
        .iter()
        .cloned()
        .map(|x| replace_if(x, "~1", "/"))
        .map(|x| replace_if(x, "~0", "~"))
        .collect();

    JSONPointer { segments }
}

fn main() {
    let v = vec!["foo".to_string(), "bar".to_string(), "baz~1".to_string()];
    let p = build_json_pointer(&v);

    println!("Hello world! {:?}", p.segments);
}


text:
Q: Does receiving mail in App Engine still work? I having trouble receiving mail in App Engine using the Mail API. I've done it before following the instructions here.
I know that page now says that "This solution is no longer recommended: This page describes how to use a superseded App Engine service. Apps that use this service can only run in App Engine and will need to upgrade to a recommended solution..."; however, the recommended solution page only discusses using a third-party service like Sendgrid (and others) to SEND mail.
I already have a Sendgrid implemented for sending, my need/issue is RECEIVING mail.
Does anyone know if the receiving of email at an @[PROJECT_ID].appspotmail.com address still works or has a new way of being implemented?
After configuring everything, I get no activity in the Mail Handler servlet when I send an email, but I don't get a delivery failure notice either.


text:
Q: Cannot centre Button variant I am working on a React project and I am trying to centre my Button variant to the centre of the home screen. However, I can't seem to do so. Does anyone have any idea how to do so?
My code
import React from "react";
import { Link } from "react-router-dom";
import "./App.css";
import Fancyline from "./Fancylines";
import lock from "./lock.png";
import { Typography, Button, Card, Grid } from "@material-ui/core";
import homepage1 from "./homepage1.png";

function Login() {
  return (
    <div
      style={{
        minHeight: "100vh",
        backgroundImage: `url(${homepage1})`,
        backgroundPosition: "center",
        backgroundSize: "cover"
      }}>

      <Link to="/Language">
        <Button variant="contained" color="secondary" size="large">
          CONTINUE
        </Button>
      </Link>

  );
}

export default Login;

A: I can see in your code that you are using Material-ui. To achieve what you are asking for, simply use Material-ui Grid component with following props.
<Grid
  container
  direction="row"
  justify="center"
  alignItems="center"
>

the complete code will look like this:-
import React from "react";
import { Link } from "react-router-dom";
import "./App.css";
import Fancyline from "./Fancylines";
import lock from "./lock.png";
import { Typography, Button, Card, Grid } from "@material-ui/core";
import Grid from '@material-ui/core/Grid';
import homepage1 from "./homepage1.png";

function Login() {
  return (
    <Grid
      container
      direction="row"
      justify="center"
      alignItems="center"
    >
      <Link to="/Language">
        <Button variant="contained" color="secondary" size="large">
          CONTINUE
        </Button>
      </Link>
    </Grid>
  );
}

export default Login;

A: You can use flexbox for your container:
function Login() {
  return (
    <div
      style={{
        minHeight: "100vh",
        backgroundImage: `url(${homepage1})`,
        backgroundPosition: "center",
        backgroundSize: "cover",
        display: 'flex';               // Flexbox styling here
        flexDirection: 'column';
        justifyContent: 'center';
      }}>

      <Link to="/Language">
        <Button variant="contained" color="secondary" size="large">
          CONTINUE
        </Button>
      </Link>

  );
}

A: Use css display: flex, align-items: center & justify-content: center
CodeSandbox Demo
function Login() {
  return (
    <div
      style={{
        minHeight: "100vh",
        backgroundImage: `url(${homepage1})`,
        backgroundPosition: "center",
        backgroundSize: "cover",
        display: "flex",
        justifyContent:"center",
        alignItems:"center"
      }}>

      <Link to="/Language">
        <Button variant="contained" color="secondary" size="large">
          CONTINUE
        </Button>
      </Link>

  );
}

A: you can use absolute position:
<Button variant="contained" color="secondary" size="large"
           style={{position:"absolute,
           top:"50%",left:"50%",
           transform:"translate(-50%,-50%)"
             }}>
              CONTINUE
            </Button>

A: Here is my solution
function Login() {
  return (
    <div
      style={{
        minHeight: "100vh",
        backgroundImage: `url(${homepage1})`,
        backgroundPosition: "center",
        backgroundSize: "cover",
        display: flex;
        align-items: center;
        justify-content: center;
      }}>

      <Link to="/Language">
        <Button variant="contained" color="secondary" size="large">
          CONTINUE
        </Button>
      </Link>

  );
}

just add this in you parent div.
display: flex;
align-items: center;
justify-content: center;


text:
Q: Get path to CGridView images from external javascript I have an external js file, where I manually add a row to the table generated by CGridView.
My question is how to pass the path to the images in CButtonColumn (like the update or delete button)? I dont want to use the fixed path, cause when I move it to another server it may result in wrong paths (assets folder may change right?).


text:
Q: Android Studio google map not working I am new to android and m trying to implement google map in my app.
i generated API Key following all the procedures mentioned but i am not getting the output. It is simple showing grey area with google written on left side of the page . my code is as follows . i have generated apk file and testing in mobile.I have enabled Google Maps Android API also
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment" />

AndroidManisfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.namrathasrinivas.maps" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
        <!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
             Google Maps Android API v2, but are recommended.
        -->
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />
            <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="AIzaSyACVUB1GlGgdtbiJEK-C0P35jKTOZvJfCQ" />

            <uses-library android:name="com.google.android.maps" />
            <activity
                android:name=".MapsActivity"
                android:label="@string/title_activity_maps" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

Build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

A: You need to enable the Google Maps Android API in the https://console.developers.google.com then only you can able view the map


text:
Q: Python Selenium Download keeps hitting Firefox download dialog I'm working on a simple script that downloads a file from some URL and it needs to be stored at a desired location. Somehow I keep running into firefox's download dialog. I've created a FirefoxProfile():
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/path/to/file')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
"application/pdf")

The snippet above is in like a thousand other SO solutions, so i've been banging my head for hours now. I'm hoping that somebody who is more involved with Selenium knows whats up.
I'm currently on Python 3.4.8, 3.5 and 3.6 give the same results.
Solution:
add profile.set_preference("pdfjs.disabled", True)

A: I think it's because the default setting in Firefox for pdf is - preview.
Try to add below code:
profile.set_preference("pdfjs.disabled", True)
profile.set_preference("plugin.scan.Acrobat", "99.0")
profile.set_preference("plugin.scan.plid.all", False)
profile.set_preference("plugin.disable_full_page_plugin_for_types", "application/pdf")

A: You may missing assigning the profile to driver
driver = webdriver.Firefox(firefox_profile=profile)

Check if path is correct
/path/to/file

You care put pdf , is your file is pdf only?
 profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
    "application/pdf")

More file format flags  :
"browser.helperApps.neverAsk.saveToDisk","text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml")

Use below code:
profile = webdriver.FirefoxProfile()

profile.set_preference("browser.download.folderList", 2)

profile.set_preference("browser.download.manager.showWhenStarting", False)

profile.set_preference("browser.download.dir", 'PATH TO DESKTOP')

profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
"application/pdf")

driver = webdriver.Firefox(firefox_profile=profile)

driver.get("Name of web site")


text:
Q: Would this code cause memory leak? I have the following two classes
export class T{
  constructor(
    public c:string,
    public s:string,
    public t:string
  ){}
}

export class ST{
  's-t':Array<T>;
  constructor(
    st:Array<T>
  ){
    this['s-t'] = st;
  }
}

In the .ts file of my Angular component, I create a variable
 st:ST;

then initialise it in the constructor
this.st=new ST([]);

And when I get a response from the server, I reassign st to the body of the response.
this.st = JSON.parse(response['additional-info']);

As I am not freeing the previously allocated memory (this.st = new ST([]]), would there be a memory leak?

A: Javascript's garbage collector automatically frees unreferenced objects.


text:
Q: SSL error "ssl_error_bad_cert_domain" after moving Magento I changed my Magento directory today. I ran these commands through phpMyAdmin before transfering files:
UPDATE core_config_data SET value = 'http://www.yourdomain.com/'
WHERE path = 'web/unsecure/base_url';

UPDATE core_config_data SET value = 'https://www.yourdomain.com/'
WHERE path = 'web/secure/base_url';

After that I cleared cache and session folders under var, everything seemed to work OK, but I'm getting error when trying to checkout

(Error code: ssl_error_bad_cert_domain)

How can I fix that?

A: Okay, I got it figured out. The certificate was for "mysite.com", but in Magento under System - Configurations - Web - Secure I had put "https://www.mysite.com/" so after I changed it to "https://mysite.com/" it works fine.


text:
Q: MySQL Timeout in IO Operation My Visual Studio 2013 web application uses entity framework accessing the database on a remote MySQL server. The application was working fine but all of a sudden it started showing "MySQL Timeout in IO Operation" for all my sql operations. Nothing has changed in the query or the tables. I can access the remote database using mysql workbench fine.
There is no specific code that does this exception it's just any simple operation that I do on mysql, here's a sample code:
public IList getalltblarticle_source()
{
    return db.tbltitles.ToList();
}

A: It turned out to be a slow internet connection problem.


text:
Q: how to insert in syspath before debugging in PyCharm I wish for a specific module to be inserted at the head of the syspath before I debug a file so that this module is picked up instead of a different version of the module in a release location.
e.g. run this code after I click the Debug button in PyCharm:
import sys; sys.path.insert(0, "/my/local/path")

does anybody know how to do this in PyCharm?
at the moment I'm copying in this line of code at the top of the file I am debugging but this is messy and I shouldn't be messing with live code like that in case i make a commit by mistake.

A: +1 to your question. And I found the answer here https://stackoverflow.com/a/15282950/707580.

*

*use virtualenvwrapper

*run (yourvenv)$ add2virtualenv /my/local/path
If you know about virtualenv, I think the above bullets are straight forward. If not, leave me a comment and I will try to elaborate what's useful.