text:
Q: Can't get rid of Ask Toolbar in Windows 8 I have just installed Windows 8 and some software. I accidentally installed Ask Toolbar, and now it has a toolbar with Chrome. I can't see it in the Program & Feature, and the Extension List of Google Chrome doesn't have it too. I also installed Your Uninstaller, and there is no Ask Toolbar item in its list too.
Can anyone please help me get rid of this annoying toolbar?

A: Okay so I finally get rid of that annoying toolbar. And the problem is, some softwares silently installed Babylon Toolbar too, which is even more annoying. Here is the solution (I only list everything I've done, so I don't know which one is unnecessary):

*

*Download and Run ToolbarUtilityTool.exe from Ask.com.

*Remove Chrome completely and reinstall. (Mentioned in comment as unneeded)

*Now, a icon should appear next to the address bar (for my case, there are 2, 1 for Ask and 1 for Babylon). Right click on it and choose Uninstall.

*However, everytime I start Chrome, Babylon always starts a tab with its search engine. And even if you change the start page, it will reverse. Now go to Program & Feature in Control Panel, and remove BOTH Babylon components.

*Restart your computer (it's important). Then now set your Chrome's On Startup setting to your favorite one.

I really hate those toolbars.

A: Here are some suggestions that might help you locate a solution.

*

*Simply right-click the toolbar, should be an deactivate or uninstall option.

*Install 'Revo Uninstaller' to see if it might help ease the uninstallation process

*Download 'Ask Toolbar Remover' (this might be out-dated)

Good luck.

A: The most likely reason you can't uninstall it from Win 8's IE8 is that you still have live tiles running in the metro screen. Live tiles seem to be open pages in explorer and ASK requires you to have all screens closed before you can remove it via programs in control panel. Do this.
make sure you are logged in as admin or you have admin rights
First open control panel and go to programs then to the "Ask Update" and remove (uninstall) it.
Then go to the Metro screen and stop all your live tiles (the screens that flip like Bing)
Then reboot your machine and go back to control panel and then programs and remove "ASK toolbar".
After this you can turn your live tiles back on if you want them. Reboot and then log in as usual.
I tested this three times and it removed the offending "ASK" everytime...

A: Try this:

How do I uninstall the Toolbar?
You can easily uninstall the Toolbar using the instructions below:
Windows 7:

*

*From your computer's 'Start' button, select 'Control Panel'

*Click the "Uninstall a Program" option found under the "Programs" category

*Select the program with the Ask logo and the text "Ask Toolbar" (or our partner's brand for a custom Toolbar)

*Click 'Remove'

  You can also uninstall the toolbar directly from the toolbar

*

*Click on the chevron (down arrow) on the Option button on the toolbar

*Select "Uninstall" from the drop down menu

*Click "Yes" when asked "Are you sure you want to uninstall this product"

*Close all open web browsers

*Click "OK" on the popup window

Source

A: I finally got rid of it off of Windows 8 by contacting the ASK family. The instructions were as followed:
"- Click on the three horizontal lines icon in the upper right-hand corner of your Chrome browser.
- Go to "Settings".
- In the menu that appears click on"Extensions".
- From the list of installed Extensions, find the entry for Ask (or APN).
- Click on the trash can icon to the right of "Enable" (for the Ask/APN entry).
- Close your browser completely and reopen it. Our Toolbar extension should be removed From your Chrome browser.
Reset home page:

*

*Click on the three horizontal lines icon In the upper right-hand corner of your Chrome browser.

*In the menu that appears - under "Tools" - select "Extensions".

*From here, click on "Setting" on the left side of the page.

*Under "Show Home Button" in the "Appearance" section, click "Change"

*Enter the URL you would like to use as your home page and then click "OK".

Reset default search:

*

*Click on the three horizontal lines icon in the upper right-hand corner of your Chrome browser.

*In the menu that appears, click on "Setting" on the left side of the page.

*Under "Search" click "Manage search engines..."

*Click on "Make Default" next to your desired search provider and then click "OK".

If you are still unable to remove Ask please let us know.

*

*Ask Toolbar Support"

I hope this helps.

A:
Here is what needs to be done to remove the ASK (or Babylon) toolbar.
Even though you may close a browser it can run hidden in the background. You need to do the following:
Click CTRL+ALT+DELETE
Click Task Manager
Click to highlight and and then close any and all browsers (Chrome, IE, Firefox, etc.) that appear in the window
Uninstall the program again
Done.
http://about.ask.com/apn/toolbar/docs/default/faq/en/chrome/index.html#na36
This worked easily for me with the ASK toolbar in Windows 8
Although I wasted an hour finding the answer and therefore will never use ASK simply because they make themselves an enemy of the User, not giving us a choice.

A: I have used a program called ADwCleaner in the past to get rid of such annoyances:
AdwCleaner is a program that searches for and deletes Adware, Toolbars, Potentially Unwanted Programs (PUP), and browser Hijackers from your computer.  By using AdwCleaner you can easily remove many of these types of programs for a better user experience on your computer and while browsing the web.
The types of programs that AdwCleaner targets are typically bundled with free programs that you download from the web.  In many cases when you download and install a program, the install will state that these programs will be installed along with the program you downloaded.  Unless you perform a Custom install, these unwanted programs will automatically be installed on your computer leaving you with extra browser toolbars, adware, and other unwanted programs.  AdwCleaner is designed to search for and remove these types of programs.
AdwCleaner Usage Instructions:
Using AdwCleaner is very simple. Simply download the program and run it.  You will then be presented with a screen that contains a Search and Delete button.  The Search button will cause AdwCleaner to search your computer for unwanted programs and then display a log showing the various files, folders, and registry entries used by these programs.
To delete these unwanted programs simply click on the Delete button, which will cause AdwCleaner to reboot your computer and remove the files and registry entries associated with the various adware that you are removing.  On reboot, AdwCleaner will display a log showing the files, folders, and registry entries that were removed.
Click The Download Now @ Bleeping Computer button on the following website:
http://www.bleepingcomputer.com/download/adwcleaner/

A: I got it incidentally by installing JAVA - what a mess!
There are two tools that should be used:

*

*http://apnmedia.ask.com/media/toolbar/utilities/ToolbarUtility/ToolbarUtilityTool.exe

*http://apnmedia.ask.com/media/toolbar/utilities/ToolbarRemover.exe
Seems to work all right now...

A: I wanted to point out how to fix the problem. This issue is Chrome's fault.
The fact that the Ask.com toolbar is locked down is not malware magic - it's documented behavior of Google Chrome. While other solutions might work piecemeal for certain specific malware, the underlying fix is to remove them from Chrome.
Google created a Group Policy for Chrome that allows IT administrators to force install of an extension:

ExtensionInstallForcelist
Configure the list of force-installed apps and extensions
Data type: List of strings
Windows registry location: Software\Policies\Chromium\ExtensionInstallForcelist
Mac/Linux preference name: ExtensionInstallForcelist
Supported on:
    - Chromium (Linux, Mac, Windows) since version 9
    - Chromium OS (Chromium OS) since version 11
Supported features:
     Dynamic Policy Refresh: Yes, Per Profile: Yes
Description:
Specifies a list of apps and extensions that are installed silently, without user interaction, and which cannot be uninstalled by the user. All permissions requested by the apps/extensions are granted implicitly, without user interaction, including any additional permissions requested by future versions of the app/extension. Furthermore, permissions are granted for the enterprise.deviceAttributes and enterprise.platformKeys extension APIs. (These two APIs are not available to apps/extensions that are not force-installed.)
This policy takes precedence over a potentially conflicting ExtensionsInstallBlacklist policy. If an app or extension that previously had been force-installed is removed from this list, it is automatically uninstalled by Chromium.
For Windows instances that are not joined to an Active Directory domain, forced installation is limited to apps and extensions listed in the Chrome Web Store.
Note that the source code of any extension may be altered by users via Developer Tools (potentially rendering the extension dysfunctional). If this is a concern, the DeveloperToolsDisabled policy should be set.
Each list item of the policy is a string that contains an extension ID and an "update" URL separated by a semicolon (;). The extension ID is the 32-letter string found e.g. on chrome://extensions when in developer mode. The "update" URL should point to an Update Manifest XML document as described at https://developer.chrome.com/extensions/autoupdate. Note that the "update" URL set in this policy is only used for the initial installation; subsequent updates of the extension employ the update URL indicated in the extension's manifest.
For example, gbchcmhmhahfdphkhkmpfmihenigjmpp;https://clients2.google.com/service/update2/crx installs the Chrome Remote Desktop app from the standard Chrome Web Store "update" URL. For more information about hosting extensions, see: https://developer.chrome.com/extensions/hosting.
If this policy is left not set, no apps or extensions are installed automatically and the user can uninstall any app or extension in Chromium.

This policy should not exist. The browser belongs to the user - it is not IT's playground to install things.
Any extension installed using this group policy is malware. In order to remove it you need to delete the ExtensionInstallForecelist registry key from:
HKEY_LOCAL_MACHINE/Software/Policies/Google/Chrome/ExtensionInstallForcelist

Once the entire list of forced extensions has been deleted, it is time to prevent anyone from pushing any group policy into Chrome. You do this by denying everyone access to write to the Chrome policy node.
Navigate to the HKEY_LOCAL_MACHINE\Software\Policies\Google\Chrome node in RegEdit, right-click, and select Permissions:

Click Add, enter Everyone as the trustee to add, and click OK:

Select the Everyone trustee, and click Advanced. Select the Everyone trustee, and click Edit:

From there you want to Deny:

*

*Set value: deny

*Create subkey: Deny

and click OK all the way up.
Now Oracle can no longer force the Ask.com toolbar.
The above steps will work for any forced extension; no matter which company installed it.

A: I had a similar problem, then I used CCleaner to uninstall. One click. Very simple. [Actually, 2 clicks since there are 2 Ask Toolbar items--one is an updater.]


text:
Q: Use Android device as a simple server I need a very simple server that listens for connections, retrieves a question and simply answers yes or no. Then the connection is broken.
As my Android device is the only device that is powered on and connected to the internet 24/7, I'm thinking of using it as the server.
Is this possible, and how could I achieve this? The biggest problems that I'm facing is the ip-address, as it could be changing a lot. I'm thinking of storing it in a public dropbox file, so the client can retrieve the address from that

A: There's a whole slew of reasons why you shouldn't use your android device as a server, but I won't go into those. I'll just assume you have a good reason for doing what you want to do.
Since your question is very general, the best I can do is give you a very general answer. You'd implement a server on android like you would any other server using java using sockets. For a simple java implementation of a socket based server, checkout this tutorial. The tricky part is going to be getting your IP address to share with clients so that they can connect to your device. As nick suggested, dyndns might be an option here, but I'm not sure if they have a mobile client.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I make the collector, specifically for each person So I have a bot, then I want to make the bot can collect a message, then reply if he detect a spesific word, but the problem is my bot keep creating new collector if someone type the tekong, so when the bot detect the word it will gonna respond twice, depend on how many collector are created. How do I make the bot so that 1 person can only create 1
Here's my code
client.on("message", (message) => {

    if (message.content.toLowerCase().startsWith('tekong')) {
        message.channel.send('Bot is collector messages...')

        let filter = m => m.content.includes('test') && m.author.id === '744882468741709824'

        let collector = message.channel.createMessageCollector(filter, {max: 1})

        collector.on('collect', indonesia => {
            console.log(indonesia.content);
        })

        collector.on('end', m => {
            console.log(`Collected ${m.size} items`)
            if (m.size === 1) {
                message.channel.send('Congratulations your enchantments is works!')
            }
        })
    }

A: You can just simply make a Set ( Array would also be an option, but I prefer Set as its easier to delete entries):
let blocked = new Set();

Then inside your message event you can use:
if (message.content.toLowerCase().startsWith('tekong')) {
     if(blocked.has(message.author.id)) return;
     blocked.add(message.author.id);

If you are done and want the user to allow to use the command again, you can simply use:
blocked.delete(message.author.id);


text:
Q: Assigining Data from firestore get to a variable Im trying to assign variables to their respected value from the firestore database using the get doc function, I've noticed it does not assign or update the values what so ever.
I've tried to work with async and awaits but cannot seem to make it work.
getFromDatabase(nameOfCollection,nameOfDocument){

    const db = firebase.firestore();
    var docRef = db.collection(nameOfCollection).doc(nameOfDocument);
    docRef.get().then(function(doc) {
        if (doc.exists) {

         outvariable = doc.data().anyfield; // THIS IS WHAT I WANT
         console.log(" Document data:", doc.data());
        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

  }

im expecting outvariable = doc.data().anyfield

A: Most likely you're confused by the fact that data is loaded from Firestore asynchronously. It's not so much that the data isn't assigned to the values, because it really is. It just happens at a different time than you expect.
It's easiest to see this by adding some simple logging statements around the code that loads data:
const db = firebase.firestore();
var docRef = db.collection(nameOfCollection).doc(nameOfDocument);
console.log("Before starting to load data");
docRef.get().then(function(doc) {
  console.log("Got data";
});
console.log("After starting to load data");

When you run this code, the output is:

Before starting to load data
After starting to load data
Got data

This is probably not what you expected, but it's actually completely correct. The data is loaded from Firestore asynchronously (since it may take some time), and instead of waiting, the main code continues. Then when the data is available, your callback function is called with that data.
This means that any code that requires the data from the database must be inside the callback, or be called from there. So the console.log(" Document data:", doc.data()) in your original code should work fine. But a similar console.log outside of the callback won't work, because it runs before the data is available.
This is an extremely common source of confusion for developers new to this type of API. But since most modern web/cloud APIs, and many other APIs, are asynchronous, it's best to learn how to work with them quickly. For that, I recommend reading:

*

*get asynchronous value from firebase firestore reference

*Doug's blog post on why Firebase APIs are synchronous

*Firestore query in function return

*NodeJS, Firestore get field

*How do I return the response from an asynchronous call?

A: The data can be extracted with .data() or .get() to get a specific field.
For example: doc.get(anyfield);
More info can be found on the official documentation.


text:
Q: Create a dynamic list from a master worksheet using VBA I am struggling to work out what I need to do next. After spending a long time searching online I have found the following code that nearly does what I want
Dim LastRow As Long
LastRow = Worksheets("Data Input").Cells(Rows.Count, "B").End(xlUp).Row
With Worksheets("Sheet7").Range("A3:A" & LastRow)
  Intersect(Worksheets("Data Input").Columns("A:A"), Worksheets("Data Input").Range("A1:A" & LastRow).EntireRow).Copy .Range("A1")
  With .Offset
    .Replace "ARL", "=ARL", xlPart
    On Error Resume Next
    .Offset(1).SpecialCells(xlConstants).EntireRow.Delete
    On Error GoTo 0
    .Replace "=ARL", "ARL", xlPart
  End With
End With
End Sub

I have a Master sheet (Data Input), and the code above  searches Column A for the Letters "ARL" and places them in column A on the sheet (Sheet7). I cannot seem to work out how to get the code to enter data from multiple columns based on the search from column A.
Once a row has been found with the search "ARL", I want the code to transfer the data on the row from Columns (A,G,H,Q,R,S,T,U,V,W) on "Data Input" into Columns (A-J) on "Sheet7" based on the search criteria. I also want to make sure this is dynamically done whenever the "Data Input" data is updated or changed in any of the columns selected.
Any suggestions on where to look to find the answer to this problem would be greatly appreciated.

A: Try the next code, please. I used column A:A to determine the last row. If you need it to be B:B (like in your original code), please adapt it where LastRow takes a value:
Sub TESTCopyReplaceDelete()
 Dim LastRow As Long, shD As Worksheet, sh7 As Worksheet

 Set shD = Worksheets("Data Input")
 Set sh7 = Worksheets("Sheet7")
 LastRow = shD.cells(Rows.count, "A").End(xlUp).row

 With sh7.Range("A2:A" & LastRow)
    'shD.Range("A2:W" & LastRow).Copy .Range("A1")'copy all the range and delete the useless columns after
    .Range("A1:W" & LastRow - 1).value = shD.Range("A2:W" & LastRow).value
    .Range("B2:F" & LastRow & ",I2:P" & LastRow).EntireColumn.Delete
    .Replace "ARL", "=ARL", xlPart
    On Error Resume Next
     .SpecialCells(xlConstants).EntireRow.Delete
    On Error GoTo 0
    .Replace "=ARL", "ARL", xlPart
 End With
End Sub

Edited:
Test the next version, please. It keeps the first 5 rows, even if the values in A1 does not start with "ALR" and it fits the columns width in "Sheet7". I did not understand what exactly "I still have a problem of the page formatting being changed" means. Nothing from the page were the data is copied is changed when the range is copied... If you maybe hoped that the column width will be kept, this does not happen, so the next code fit the columns width:
Sub TESTCopyReplaceDeleteBis()
 Dim LastRow As Long, shD As Worksheet, sh7 As Worksheet
 Dim rng As Range, arr As Variant, i As Long

 Set shD = Worksheets("Data Input")
 Set sh7 = Worksheets("Sheet7")
 LastRow = shD.cells(Rows.count, "A").End(xlUp).row

 sh7.Range("A1:W" & LastRow).value = shD.Range("A1:W" & LastRow).value
 sh7.Range("B:F,I:P").EntireColumn.Delete
 sh7.Range("A:J").EntireColumn.AutoFit

 With sh7.Range("A6:A" & LastRow)
    .Replace "ARL", "=ARL", xlPart
    On Error Resume Next
     .SpecialCells(xlConstants).EntireRow.Delete
    On Error GoTo 0
    .Replace "=ARL", "ARL", xlPart
 End With
End Sub

If you also need some format to be copied, please state it.

A: Here is a terrible Excel solution (but some Excel wizard might improve on it):
The first four formulas go to cells A2, B2, C2, D2:
=IF($N2="","",INDEX('Data Input'!A:A,SUM($N$1:$N2)))
=IF($N2="","",INDEX('Data Input'!G:G,SUM($N$1:$N2)))
=IF($N2="","",INDEX('Data Input'!H:H,SUM($N$1:$N2)))
=IF($N2="","",INDEX('Data Input'!Q:Q,SUM($N$1:$N2)))

Now cell D2 is copied until J2.
The following two formulas go to N2 and O2 (they can be moved afterwards):
=IFERROR(MATCH("ARL",INDIRECT(O2,TRUE),0),"")
=ADDRESS(SUM(N$1:N1)+1,1,4,1,"Data Input")&":"&ADDRESS(1048576,1,4,1)


text:
Q: setErrors({ backend: true }) not working because formcontrol has value or because of the ngfor loop I believe my setErrors function is not working because the formcontrol has value
product.component.ts
  ngAfterViewInit() {
    this.isPriceErrorSub = this.store.select(getCreateProductsError(this.index, 'isPriceError')).subscribe(err => {
      console.log(err);
      if(err) {
        this.eurosFormControl.setErrors({ backend: true });
        this.centsFormControl.setErrors({ backend: true });
        this.chaschan.markForCheck();
      }
    });
    this.isAmountErrorSub = this.store.select(getCreateProductsError(this.index, 'isAmountError')).subscribe(res => {
      if (res) {
        console.log('jasfnjafn')
        this.amountFormControl.setErrors({ backend: true })
        this.chaschan.markForCheck();
        this.chaschan.detectChanges();
      }
    });
    this.isDescriptionErrorSub = this.store.select(getCreateProductsError(this.index, 'isDescriptionError')).subscribe(res => {
      console.log(res);
      if (res) {
        this.descriptionFormControl.markAsTouched();
        this.descriptionFormControl.setErrors({ backend: true });
        this.chaschan.markForCheck();
      }
    })
  }

  constructor(
    private chaschan: ChangeDetectorRef,
    private store: Store
  ) {
    this.index = 0;
    this.product = {
      euros: 0,
      cents: 0,
      amount: 0,
      description: '',
    }
    this.errorStateMatcher = new MyErrorStateMatcher();
    this.euros = 0;
    this.eurosFormControl = new FormControl(this.product.euros, [
      Validators.required
    ]);
    this.cents = 0;
    this.centsFormControl = new FormControl(this.product.cents, [
      Validators.required
    ])
    this.amount = 0;
    this.amountFormControl = new FormControl(this.product.amount, [
      Validators.required,
      Validators.min(1)
    ])
    this.description = '';
    this.descriptionFormControl = new FormControl(this.product.description, [
      Validators.required
    ]);

    this.productsCount = this.store.select(getCreateProductsCount);
    this.isErrorSub = of().subscribe();
    this.isGrabProductsSub = of().subscribe();
    this.isPriceErrorSub = of().subscribe();
    this.isAmountErrorSub = of().subscribe();
    this.isDescriptionErrorSub = of().subscribe();
   }

product.component.html

      <mat-form-field class="full-width"><input matInput disabled placeholder="{{ 'Product ' + (index + 1) }}" value="Price" type="text"></mat-form-field>

      <mat-form-field class="full-width" style="text-align: end;">
        <input matInput [formControl]="eurosFormControl"  [(ngModel)]="euros" [errorStateMatcher]="errorStateMatcher" placeholder="€ 0," type="number">
        <mat-error *ngIf="eurosFormControl.hasError('backend') || centsFormControl.hasError('backend')">
          Price is required
        </mat-error>
      </mat-form-field>

      <mat-form-field class="full-width">
        <input [formControl]="centsFormControl"  [(ngModel)]="cents" [errorStateMatcher]="errorStateMatcher" matInput placeholder="00" type="number">
      </mat-form-field>

<mat-form-field class="full-width">
  <input type="text" matInput placeholder="Amount" [errorStateMatcher]="errorStateMatcher"  [formControl]="amountFormControl" [(ngModel)]="amount">
  <mat-error *ngIf="amountFormControl.hasError('backend')">
    Amount is required
  </mat-error>
</mat-form-field>
<mat-form-field class="full-width">
  <textarea matInput placeholder="Description"  [formControl]="descriptionFormControl" [errorStateMatcher]="errorStateMatcher" [(ngModel)]="description"  rows="4">
  </textarea>
  <mat-error *ngIf="descriptionFormControl.hasError('backend')">
    Description is required
  </mat-error>
  <button mat-button matSuffix *ngIf="(productsCount | async) == (index + 1)" (click)="add()">new</button>
  <button mat-button matSuffix *ngIf="(productsCount | async)! > (index + 1)" (click)="change()">change</button>
  <button mat-button matSuffix *ngIf="index > 0" (click)="clear()"><mat-icon>clear</mat-icon></button>
</mat-form-field>

Because decriptionFormControl turns red but amountFormControl, eurosFormControl and centsFormControl don't
Also product.component.html is rendered in a ngForLoop
create.component.html
<mat-toolbar>
  <button mat-button routerLink="/account">Account</button>

  <button mat-button >Logout</button>
</mat-toolbar>

Create a new invoice

Please give us information about the reciever

        <mat-slide-toggle [(ngModel)]="isIndividual">
          Individual ?
        </mat-slide-toggle>
        <mat-form-field class="full-width" *ngIf="isIndividual" @transformEnterFromLeftLeaveToRight>
          <input matInput
          placeholder="Firstname"
          [formControl]="firstNameFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="firstName"
          type="text">
          <mat-error *ngIf="firstNameFormControl.hasError('required')">
            Firstname is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" *ngIf="isIndividual" @transformEnterFromRightLeaveToLeft>
          <input matInput
          placeholder="Lastname"
          [formControl]="lastNameFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="lastName"
          type="text">
          <mat-error *ngIf="lastNameFormControl.hasError('required')">
            Lastname is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromLeftLeaveToRight>
          <input matInput
          placeholder="Company"
          [formControl]="companyFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="company"
          type="text">
          <mat-error *ngIf="companyFormControl.hasError('required')">
            Company is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromRightLeaveToLeft>
          <input matInput
          placeholder="Address"
          [formControl]="addressFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="address"
          type="text">
          <mat-error *ngIf="addressFormControl.hasError('required')">
            Address is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromLeftLeaveToRight>
          <input matInput
          placeholder="Number"
          [formControl]="numberFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="number"
          type="number">
          <mat-error *ngIf="numberFormControl.hasError('required')">
            Number is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromRightLeaveToLeft>
          <input matInput
          placeholder="Zipcode"
          [formControl]="zipCodeFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="zipCode"
          type="text">
          <mat-error *ngIf="zipCodeFormControl.hasError('required')">
            Address is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromLeftLeaveToRight>
          <input matInput
          placeholder="City"
          [formControl]="cityFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="city"
          type="text">
          <mat-error *ngIf="cityFormControl.hasError('required')">
            City is required
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width" @transformEnterFromRightLeaveToLeft>
          <input matInput
          placeholder="Country"
          [formControl]="countryFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="country"
          type="text">
          <mat-error *ngIf="countryFormControl.hasError('required')">
            Country is required
          </mat-error>
        </mat-form-field>

        <mat-form-field class="full-width" @transformEnterFromLeftLeaveToRight>
          <input matInput
          placeholder="VAT-number"
          [formControl]="VATNumberFormControl"
          [errorStateMatcher]="errorStateMatcher"
          [(ngModel)]="VATNumber"
          type="text">
          <mat-error *ngIf="VATNumberFormControl.hasError('required')">
            VAT-number is required
          </mat-error>
        </mat-form-field>
          <app-product  *ngFor="let product of (products | async); let i = index" [index]="i" [product]="product"></app-product>
        <button mat-raised-button class="full-width" (click)="submit()" *ngIf="(productsCount | async)! > 0">submit</button>

A: Because product changes you have to do this.amountFormControl.markAsTouched()


text:
Q: Automatically select Instagram in UIDocumentInteractionController or UIActivityViewController UIDocumentInteractionController and UIActivityViewController both present menus for sharing images out to other networks. After hitting Instagram, you are presented with a nice modal that allows you to post to Instgram without leaving the app. My question is, how do I automatically show that modal without showing the menu?
This app called Sounds does it so I know it's possible, but I can't find any documentation online about how it's done. Here is the current code I have which shows the menu:
    NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.ig"];
    NSData *imageData=UIImagePNGRepresentation(cardImage);
    [imageData writeToFile:saveImagePath atomically:YES];
    NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];

    UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
    docController.UTI = @"com.instagram.exclusivegram";
    docController = [self setupControllerWithURL:imageURL usingDelegate:self];
    [docController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:self.view animated:YES];

Here's the menu:

Here's what I want to automatically show:

A: You're able to use UIActivityViewController to show up Instagram as long there is just an UIImage inside the activity items.
It won't show up if you add more items like text, url etc.
This is a bad limitation made by Instagram.
Like so:
NSMutableArray *items = [NSMutableArray array];
[items addObject:[UIImage ...]];

// show view
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items
                                                                             applicationActivities:nil];
[vc presentViewController:activityVC animated:YES completion:nil];

A: The code I used to share image on instagram
import UIKit
import Photos

class SocialShare: NSObject {
    static let shared = SocialShare()

    func postImageToInstagram(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(SocialShare.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
        if error != nil {
            print(error)
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
        if let lastAsset = fetchResult.firstObject as? PHAsset {
            let localIdentifier = lastAsset.localIdentifier
            let u = "instagram://library?LocalIdentifier=" + localIdentifier
            UIApplication.sharedApplication().openURL(NSURL(string: u)!)
        }
    }
}

No anywhere you want to use just call
SocialShare.shared.postImageToInstagram(UIImage(named: "1"))

A: Here's a Swift 4 class that implements Zuhair's answer.
import Foundation
import Photos

class InstagramSharer: NSObject {
    static let shared = InstagramSharer()

    func post(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }

    @objc
    private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        guard error == nil else {
            return
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if let lastAsset = fetchResult.firstObject {
            let localIdentifier = lastAsset.localIdentifier
            let url = "instagram://library?LocalIdentifier=" + localIdentifier
            UIApplication.shared.openURL(URL(string: url)!)
        }
    }
}

Usage
InstagramSharer.shared.post(image: #YOUR_IMAGE#)

A: To remove the other applications from being displayed change following lines of code (Just flip them):
docController.UTI = @"com.instagram.exclusivegram";
docController = [self setupControllerWithURL:imageURL usingDelegate:self];

So that the .UTI variable is set after overriding the docController object.
EDIT: If you are attempting to directly open the Instagram application with the information filled out and ready to share check out the iPhone hooks here.


text:
Q: Mercurial - handling filename conflicts Some Context:
I'm trying to implement K. Scott Allen's technique for database schema versioning and, due to the continuous development of this particular project, have chosen to use a simpler 1.sql, 2.sql, 3.sql, ..., n.sql numbering scheme instead of the versioning scheme that is mentioned there.
However, this often leads to the scenario where a change to the schema in two different branches results in the same new file, {n+1}.sql being created.
I'm using Mercurial as my version management software, specifically TortoiseHG on Windows with the default diff software. When I merge a development branch into stable, Mercurial detects a conflict, but offers to merge the two files. Ideally, one of them needs to be renamed to {n+2}.sql.
This can be done in two ways: firstly, one could defer the commit on the merge and edit the files there. However, at this stage, the merged file {n+1}.sql is a messy combination of some or none of either file.
The second method is to undo the merge, go to the development branch, rename the file, recommit, re-merge.
My Question:
Is it possible to get Mercurial to treat files that were each created in separate branches differently to files that were merely modified in different branches when it comes to merging?
Ideally, if I were faced, post-merge, pre-commit with {x+1}.sql and {x+1}.sql.mergebranch then it would be clear which file needed to be renamed and life would be simpler.

A: There's two options, one more difficult, the other a bit more hasslesome.
The first is to find and configure or create a diff tool which handles the merges of those files as you see fit. You can also define specific diff tools for specific file types. So this is what you might want to look for
Alternatively, and a bit hackish, you can simplify your current process for the merge. Execute the merge and prior to commit fix it:

*

*revert the {x+1}.sql to the previous version: hg revert -rHASH1 {x+1}.sql

*create the 2nd sql file: hg cat -rHASH2 {x+1}.sql > {x+2}.sql
where HASH1 and HASH2 are the changesetIDs of the two parents of the merge.


text:
Q: C# array with a specific format please I need to create a C# array with following exact format:
  var sampledata =  {
                      {Day: "Sunday", Quantity: 15},
                      {Day: "Monday", Quantity: 20},
                      {Day: "Tuesday", Quantity: 80}
                    }

can we create something like the above in C#. if yes, please how?
thanks...

A: var sampledata = new[] {
    new { Day = "Sunday",  Quantity = 15 },
    new { Day = "Monday",  Quantity = 20 },
    new { Day = "Tuesday", Quantity = 80 }
};

try a Array or a List of anonymous Types (http://msdn.microsoft.com/en-US/en-en/library/bb397696.aspx)

A: Use object and array together?
class Order
{
    public String Day;
    public int    Quantity;
}

Order[] orderArray = new Order[3];
orderArray[0].Date = "Sunday";
orderArray[0].Quantity = 15;
...


text:
Q: No web processes running Error - Deploying Django on Heroku I am using the tutorial to deploy Django. [http://devcenter.heroku.com/articles/django] After I do a git push heroku master, there are no web processes.
Process  State  Command
-------  -----  -------

On the log it looks like the following.
2012-04-13T03:48:45+00:00 heroku[slugc]: Slug compilation started
2012-04-13T03:49:32+00:00 heroku[api]: Config add PYTHONUNBUFFERED, PYTHONPATH, PATH,
LD_LIBRARY_PATH, LANG, PYTHONHOME, LIBRARY_PATH, PYTHONHASHSEED by zach@gmail.com
2012-04-13T03:49:32+00:00 heroku[api]: Release v2 created by zach@gmail.com
2012-04-13T03:49:34+00:00 heroku[api]: Release v3 created by zach@gmail.com
2012-04-13T03:49:34+00:00 heroku[api]: Deploy d1263ef by zach@gmail.com
2012-04-13T03:49:34+00:00 heroku[web.1]: State changed from created to down
2012-04-13T03:49:35+00:00 heroku[slugc]: Slug compilation finished
2012-04-13T03:50:19+00:00 heroku[router]: Error H14 (No web processes running) -> GET
growing-winter-4952.herokuapp.com/ dyno= queue= wait= service= status=503 bytes=

Any ideas? I was able to get this to work with another app.  Thank you.
Also when I do a heroku scale web=1                 I get this
Scaling web processes...  !    Record not found.

A: I had the exact same problem. At first, when I ran heroku scale web=1, I got the same 'Record not found' error as you. But I waited a few minutes and ran it again, and it worked.
If your build fails on the first push for some reason, then heroku doesn't automatically give you a web process, and the 'Record not found' error might've cropped up because something was off with the build at that point.

A: This is most likely the result of scaling your web processes down to zero through the client.
$ heroku ps:scale web=0

Use the heroku ps command to determine the state of your web processes., and you should take a look at the Error Codes to understand the Heroku functionality.


text:
Q: autocomplete parser I am currently using Jquery and a webservice to retrieve values for an autocomplete textbox. After the values are returned from the web service, I get an alert with "parser error" as the warning. Why is this?
Jquery

$(document).ready(function() {

    $.ajax({
        type: "POST",
        url: "/Service/WSDataService.asmx/GetStates",
        dataType: "json",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            var datafromServer = data.d.split(":");
            $("[id$='txtautofromDB']").autocomplete({
                source: datafromServer
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
        }
    });
}

web service
        [WebMethod]
        public string GetStates()
        {
            StringBuilder sbStates = new StringBuilder();
            List<string> stringlist = new List<String>();
            stringlist.Add("alabama");
            stringlist.Add("boston");
            stringlist.Add("abernathy");
            /*XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/Data/States.xml"));*/
            try
            {
                foreach (string xnl in stringlist)
                {

                    sbStates.AppendFormat("{0}:", xnl);
                }

                sbStates = sbStates.Remove(sbStates.Length - 1, 1); //Removes the extra ":"
            }
            catch (Exception ex)
            {
                string exp = ex.ToString();     //Setup a breakpoint here
                //to verify any exceptions raised.
            }
            return sbStates.ToString();
        }

A: How you have it now there is no reason to expect a JSon object.  Request just a generic string based response and it should work fine.
If you want to stick with the JSon object approach try returning a list of strings and then when it's deserialized into the JavaScript you'll have just that, a list of strings.
Update (How to get string via ajax):
$.ajax({
        url: "/Service/WSDataService.asmx/GetStates",
        success: function(data) {
            var datafromServer = data.split(":");
            $("[id$='txtautofromDB']").autocomplete({
                source: datafromServer
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
        }
    });

A: Thats most likley because your response string isn't json parsable. Change the dataType parameter to this:
dataType : text

But why are you using POST to get some data? You should change that to GET


text:
Q: how to ADD IP address in Windows 10 using C# I want to add multiple IP addresses in my Ethernet port.
I tried below both way

*

*using Management Class
public void setIP()
    {
        string myDesc = "Realtek USB GbE Family Controller";
        string gateway = "10.210.255.1";
        string subnetMask = "255.255.255.0";
        string address = "10.210.255.102";

        var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
        var networkCollection = adapterConfig.GetInstances();

        foreach (ManagementObject adapter in networkCollection)
        {
            string description = adapter["Description"] as string;
            if (string.Compare(description,
                myDesc, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                try
                {
                    // Set DefaultGateway
                    var newGateway = adapter.GetMethodParameters("SetGateways");
                    newGateway["DefaultIPGateway"] = new string[] { gateway };
                    newGateway["GatewayCostMetric"] = new int[] { 1 };

                    // Set IPAddress and Subnet Mask
                    var newAddress = adapter.GetMethodParameters("EnableStatic");
                    newAddress["IPAddress"] = new string[] { address };
                    newAddress["SubnetMask"] = new string[] { subnetMask };

                    adapter.InvokeMethod("EnableStatic", newAddress, null);
                    adapter.InvokeMethod("SetGateways", newGateway, null);

                    Console.WriteLine("Updated to static IP address!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to Set IP : " + ex.Message);
                }
            }
        }
    }

*Using PowerShellSCript in C#
private string RunScript()
    {

              string scriptText = "$iplist = \"10.210.255.102\"" + "," + " \"10.210.255.103\"" + "\nforeach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}";

        // create Powershell runspace

        Runspace runspace = RunspaceFactory.CreateRunspace();

        // open it

        runspace.Open();

        // create a pipeline and feed it the script text

        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);

        // add an extra command to transform the script
        // output objects into nicely formatted strings

        // remove this line to get the actual objects
        // that the script returns. For example, the script

        // "Get-Process" returns a collection
        // of System.Diagnostics.Process instances.

        pipeline.Commands.Add("Out-String");

        // execute the script

        var results = pipeline.Invoke();

        // close the runspace

        runspace.Close();

        // convert the script result into a single string

        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        return stringBuilder.ToString();
    }

Both are not working, my code working properly it's not going inside catch,
but not able to add IP,
even I can add IP using running power script file from Windows PowerShell, but the same script is not working inside C#,
all I am trying to add a number of IP address in Single Ethernet card
Note: yes I have Admin rights, I already perform this manually and using PowerShell tool power script.
one more thing,
every time i have to right-click window PowerShell and run as administrator to run my scrip

A: for the Powershell solution, it can be a real pain to get a script working in c#. Usually I prefer using the Powershell class, you can try this approach:
Using Scripts:
var Ps = PowerShell.Create();
//you can create the variable like this:
Ps.AddCommand("Set-Variable").AddParameter("Name", "tsinfo").AddParameter("Value", result);
Ps.Invoke();
//Execute your script
Ps.Commands.Clear();
Ps.AddScript("foreach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}");
Ps.Invoke();

Or using Commands:
var iplist = new List<string> { "10.210.255.102", "10.210.255.103"};
foreach(var ip in iplist){
    Ps.Commands.Clear();
    Ps.AddCommand("New-NetIPAddress").AddParameter("InterfaceAlias", "Ethernet").AddParameter("IPAddress", ip).AddParameter("PrefixLength", 24);
    Ps.Invoke();
}

Hope it'll help

A: Problem Solved, Run Exe As a administratoror, Run Visual studio as a Administrator .
I go further and added multiple IP addresses, and Subnet makst in Single Ethernet card
var newAddress = adapter.GetMethodParameters("EnableStatic");
                        newAddress["IPAddress"] = new string[] { address, address1 };
                        newAddress["SubnetMask"] = new string[] { subnetMask,subnetMask };

                        var cal1 = adapter.InvokeMethod("EnableStatic", newAddress, null);


text:
Q: Javascript accessing values of map through key objects that have equal fields but are not the same in memory The following code prints undefined because in memory a and b are not the same.
let map = new Map();

let obj1 = {value1: 1, value2: 2};
let obj2 = {value1: 1, value2: 2};

map.set(obj1, 'someValue');
console.log(map.get(obj2));

I'm looking for a way to access the value stored 'someValue' with key the object obj1 with another key obj2 that is equal in terms of fields.

A: I would suggest you to create hash from your object. Plain stringify might fail in case your properties are in different order. For example:
JSON.stringify({a: 1, b:2}) !== JSON.stringify({b: 2, a:1})

You can use module like hashcode or object-hash to create hash, like:
map.set(encode().value(obj1), 'someValue')

A: You could take the entries of the object and sort them for getting a comparable JSON.

function getEntries(object) {
    return JSON.stringify(Object
        .entries(object)
        .sort(([a], [b]) => a.localeCompare(b))
    );
}

var map = new Map(),
    obj1 = { value1: 1, value2: 2 },
    obj2 = { value2: 2, value1: 1 };

map.set(getEntries(obj1), 'someValue');
console.log(map.get(getEntries(obj2)));


text:
Q: Convert columns to rows and repeat row labels in google sheets I am trying to convert table 1 to the format in table 2. How can I do it in google sheets ?
Thank you very much.
Table 1 -

Table 2 -

A: use:
=ARRAYFORMULA(QUERY(TO_TEXT(SPLIT(FLATTEN(
 A3:A&"×"&B2:E2&"×"&TEXT(B1:E1, "dd/mm")&"×"&B3:E), "×")),
 "where Col4 is not null", ))


text:
Q: How do I get Windows 8 to measure startup impact? I did an inplace upgrade from Windows 7 Ultimate to Windows 8 Pro, and am just getting used to Windows 8. Under the Task Manager → Startup tab, I see there's an option showing "start up impact".
Despite few reboots, the impact is still in "Not measured" state. What should I do to get Windows to measure this report the impact to me?

A: This could happen with some of the third party apps where windows is unable to determine the impact.
You can either leave it unrecognized or can try with third party measurement app like Tune Up Utilities.
I suggest you to leave it unrecognized if it doesn't matter a lot to you.

A: I tried with the cold boot too but it doesn't measure the impact too. I tried also by disable the program and a proper shutdown and then again enable the program and did a cold boot again but nothing changed. SO there is no way to manually(according to me, if someone has idea he is most welcome) measure the startup impat.
So I recommend to use third party apps like Soluto which can measure the startup time and also show the solution to make it fast. Or you can use Argus Boot Accelerator for startup items.
Another tool that can measure the startup time is BootRacer, which is free for non-commercial use. The latest version of BootRacer adds support for Windows 8. Now its also available in Windows store.

A: I had the same issue on several clean loads.
Loaded Intel Rapid Storage Technology driver last.
Don't know all the technicals to it, but it worked for me.


text:
Q: react redux добавление товара в корзину Я делаю магазин книг. Сделал большею часть функционала по видеоуроку, но вижу магазин можно дополнить. Подскажите как сделать функцию добавление товара в корзину и чтобы был счетчик на корзине сколько добавилось товаров.
reducer разделён на 2 части.
shopping-cart.js
const updateCartItems = (cartItems, item, idx) => {

  if (item.count === 0) {
    return [
      ...cartItems.slice(0, idx),
      ...cartItems.slice(idx + 1)
    ];
  }

  if (idx === -1) {
    return [
      ...cartItems,
      item
    ];
  }

  return [
    ...cartItems.slice(0, idx),
    item,
    ...cartItems.slice(idx + 1)
  ];
};

const updateCartItem = (book, item = {}, quantity) => {

  const {
    id = book.id,
    count = 0,
    title = book.title,
    total = 0 } = item;

  return {
    id,
    title,
    count: count + quantity,
    total: total + quantity*book.price
  };
};

const updateOrder = (state, bookId, quantity) => {
  const { bookList: { books }, shoppingCart: { cartItems }} = state;

  const book = books.find(({id}) => id === bookId);
  const itemIndex = cartItems.findIndex(({id}) => id === bookId);
  const item = cartItems[itemIndex];

  const newItem = updateCartItem(book, item, quantity);
  return {
    orderTotal: 0,
    cartItems: updateCartItems(cartItems, newItem, itemIndex)
  };
};

const updateShoppingCart = (state, action) => {

  if (state === undefined) {
    return {
      cartItems: [],
      orderTotal: 0
    }
  }

  switch(action.type) {
    case 'BOOK_ADDED_TO_CART':
      return updateOrder(state, action.payload, 1);

    case 'BOOK_REMOVED_FROM_CART':
      return updateOrder(state, action.payload, -1);

    case 'ALL_BOOKS_REMOVED_FROM_CART':
      const item = state.shoppingCart.cartItems.find(({id}) => id === action.payload);
      return updateOrder(state, action.payload, -item.count);

    default:
      return state.shoppingCart;
  }
};

export default updateShoppingCart;

book-list.js
const updateBookList = (state, action) => {

    if (state === undefined) {
      return {
        books: [],
        loading: true,
        error: null
      };
    }

    switch (action.type) {
      case 'FETCH_BOOKS_REQUEST':
        return {
          books: [],
          loading: true,
          error: null
        };

      case 'FETCH_BOOKS_SUCCESS':
        return {
          books: action.payload,
          loading: false,
          error: null
        };

      case 'FETCH_BOOKS_FAILURE':
        return {
          books: [],
          loading: false,
          error: action.payload
        };

      default:
        return state.bookList;
    }
  };

  export default updateBookList;

actions index.js
const booksRequested = () => {
  return {
    type: 'FETCH_BOOKS_REQUEST'
  }
};

const booksLoaded = (newBooks) => {
  return {
    type: 'FETCH_BOOKS_SUCCESS',
    payload: newBooks
  };
};

const booksError = (error) => {
  return {
    type: 'FETCH_BOOKS_FAILURE',
    payload: error
  };
};

export const bookAddedToCart = (bookId) => {
  return {
    type: 'BOOK_ADDED_TO_CART',
    payload: bookId
  };
};

export const bookRemovedFromCart = (bookId) => {
  return {
    type: 'BOOK_REMOVED_FROM_CART',
    payload: bookId
  };
};

export const allBooksRemovedFromCart = (bookId) => {
  return {
    type: 'ALL_BOOKS_REMOVED_FROM_CART',
    payload: bookId
  };
};

const fetchBooks = (bookstoreService, dispatch) => () => {
  dispatch(booksRequested());
  bookstoreService.getBooks()
    .then((data) => dispatch(booksLoaded(data)))
    .catch((err) => dispatch(booksError(err)));
};

export {
  fetchBooks
};

на данный момент 2 товара из сервиса
export default class BookstoreService {

    data = [
      {
        id: 1,
        title: 'Production-Ready Microservices',
        author: 'Susan J. Fowler',
        price: 32,
        coverImage: 'https://images-na.ssl-images-amazon.com/images/I/41yJ75gpV-L._SX381_BO1,204,203,200_.jpg'},
      {
        id: 2,
        title: 'Release It!',
        author: 'Michael T. Nygard',
        price: 45,
        coverImage: 'https://images-na.ssl-images-amazon.com/images/I/414CRjLjwgL._SX403_BO1,204,203,200_.jpg'}
    ];

    getBooks() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (Math.random() > 0.75) {
            resolve(this.data);
          }
        }, 700);
      });
    }

}

A: Для добавления счетчика на корзине сколько добавилось товаров необходимо в компоненте AppHeader получать items из Redux. Далее имея товары в корзине мы можем отображать их колличество. Получается примерно так:
import React from "react";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";

import cartIcon from "./shopping-cart-solid.svg";
import "./app-header.scss";

const AppHeader = ({ total }) => {
  const items = useSelector((state) => state.items);
  console.log(`items`, items);

  const itemsInCartCount = items.length;

  return (

      <Link to={"/"} className="header__link">
        Menu
      </Link>
      <Link to="/cart" className="header__link">

        Total: {total} $
        {!!itemsInCartCount &&  Items in cart: {itemsInCartCount}}
      </Link>

  );
};

export default AppHeader;


text:
Q: Download HTML Table as excel in firefox Cannot export HTML Table in excel if there is # in the text, Ho w can I escape #?

            Title

            #test

A: I have tested the code, it is working.You can try like below;

 <meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

            Title

            #test

<button onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel"> Export to Excel</button>

A: Working snippet :)

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
    template = '<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
{table}
',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      })
    }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {
      worksheet: name || 'Worksheet',
      table: table.innerHTML
    }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

        Title

        #test

    <input type="button" onclick="tableToExcel('tableToExcelId', 'W3C Example Table')" value="Export to Excel">


text:
Q: Can we access props passed to the component in a custom function this may sound silly but I can't find a guide to this.
what I'm trying to do is changing a variable named update in parent.
and in the parent DOM do :
 <Child update={this.state.update} />

and in the child instead of picking it up between render and return (with const {update} = this.props) and only being able to use it in the DOM, I'd like to pick it up in the  section between the constructor and render and use it in a function there.

A: You can access the props to the component anywhere in the component whether it be the constructor, lifecycle functions, render or custom functions.
The only thing that you need to know is that constructor, lifecycle methods and render function are already have binding to the context of the React component, but for custom function you need to add binding yourself. Binding can be done in the constructor or by declaring the functions as arrow functions.
Check this answer on why you need to bind custom functions: Why do we need to bind function and eventHandlers in React and what is the difference between the different binding methods
For your case
<Child update={this.state.update} />

where Child could be
class Child extends React.Component {
    componentDidMount() {
        const {update} = this.update || {};
        console.log(update);
        this.somefunc();
    }
    somefunc = () = {
       const {update} = this.update || {};   //After function is binded, you can do the same thing here too
        console.log(update);
    }
}

A: React has a lifecycle of functions called on a component: https://reactjs.org/docs/react-component.html
On startup of component you can use componentDidMount()
if you want to change state based on props change use: componentWillReceiveProps()
Otherwise if you want the result of that function to use as data for in your view (but just manipulated). Than make a seperate function also called: computed property of computed function. (because the result is computed based on current state/props). React will make sure you don't re-render/compute unnecessary.


text:
Q: ubuntu 20.04 error undefined symbol: FT_Property_Set There was a python2 project which was working fine on Ubuntu 16.04, but when i created virtualenv to set-up the project for python2 all is working fine except PDF generation error via using python pdfkit module
/usr/bin/wkhtmltopdf: symbol lookup error: /usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/ls -ld : undefined symbol: FT_Property_Set
$ wkhtmltopdf --version
wkhtmltopdf 0.12.5
$ dpkg -S /usr/bin/wkhtmltopdf
wkhtmltopdf: /usr/bin/wkhtmltopdf
$ ldd /usr/bin/wkhtmltopdf | grep local
libfreetype.so.6 => /usr/local/freetype/2_10_1/lib/libfreetype.so.6 (0x00007faf8693a000)

$ sudo find / -type f -name *freetype*.so* 2> /dev/null
/snap/gnome-3-28-1804/128/usr/lib/x86_64-linux-gnu/libfreetype.so.6.15.0
/snap/gnome-3-28-1804/145/usr/lib/x86_64-linux-gnu/libfreetype.so.6.15.0
/home/me/.local/lib/python3.8/site-packages/opencv_python.libs/libfreetype-8d3bcff4.so.6.14.0
/home/me/Downloads/freetype/freetype-2.10.1/objs/.libs/libfreetype.so.6.17.1
/home/me/.nvm/versions/node/v14.15.0/lib/node_modules/framework7-cli/node_modules/sharp/vendor/lib/libfreetype.so.6.17.1
/home/me/Android/Sdk/emulator/lib64/qt/lib/libfreetype.so.6
/usr/local/freetype/2_10_1/lib/libfreetype.so.6.17.1
/usr/lib/x86_64-linux-gnu/libfreetype.so.6.17.1
/usr/lib/x86_64-linux-gnu/vlc/plugins/text_renderer/libfreetype_plugin.so
/work/mine/lamp74/common/lib/libfreetype.so.6.8.0

A: You have locally compiled version of LibFreetype. To make things run smooth you have to remove such library and use official packaged version.
Open terminal and type:
sudo rm -rf /usr/local/freetype
sudo apt-get install --reinstall libfreetype6 libfreetype-dev

and then retry running wkhtmltopdf or your Python script which uses it.

A: Eventually It`s resolved after several days.
Nothing caused by the home file folder. This is actual caused of QT lib dynamically loading issue. After several setting done at system end and environment var settings , nothing works.
In end I have to Download a precompiled binary (which is QT patched) from https://wkhtmltopdf.org/ as per your OS version.
In my case was:
https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.focal_amd64.deb
which landed installed at : /usr/local/bin/wkhtmltopdf
and then after it works like charm.
Thx, @N0rbert for trying to help.
-:)


text:
Q: What is the alternative to `TiXmlNode::FirstChild(const char *)` in TinyXML-2? I am updating code that uses the legacy TinyXml library, to use new TinyXML-2 version instead.
While editing, I noticed that the function TiXmlNode::FirstChild(const char *) has no direct replacement in TinyXML-2.
My questions are:

*

*Is there a convenient replacement for the aforementioned function that I missed?

*In case there isn't, how should the example code below be updated for TinyXML-2?

// TiXmlElement *element; // assume this was correctly loaded
TiXmlNode *node;

if ((node = element->FirstChild("example")) != nullptr)
{
    for (TiXmlElement *walk = node->FirstChildElement();
        walk != nullptr;
        walk = walk->NextSiblingElement())
    {
        // ...
    }
}

A: tinyxml2 has
const XMLElement * XMLNode::FirstChildElement (const char *value=0) const
Your code block is much the same:
if (auto example = element -> FirstChildElement ("example")
{
   for (auto walk = example -> FirstChildElement();
        walk;
        walk -> NextSiblingElement())
   {
   // walk the walk
   }
}

Or you might look at my add-on for tinyxml2 with which your snippet would be:
for (auto walk : selection (element, "example/")
{
   // walk the walk
}


text:
Q: How to Vuestic DataTable displays values from properties of objects? I'm using Vuestic in my vue project and I need to display values from a property that is in a object, I have something like this:
myObject: {
  subObject: {
    name
  }
}

I have a list of myObject and I need to display the name of the subObject in the DataTable. My DataTable is pointing to headers object:
headers: [
  { key: 'subObject.name', label: 'Name' }
]

Is that possible?

A: Yes, it is defintely possible.
This feature was not supported until this commit on Jun 23.
Therefore, since v1.4.2 of vuestic-ui was released on Jun 24, you can use dot notation in keys to retrieve nested properties for data tables.
Here is a working example: link.

A: Correct me if I'm wrong but it sounds like you would like to create an array of myObject.subObject.name values from another array of myObject objects?
You can do that with Array.prototype.map:
myObjectArray.map((obj) => {
  return {
    key: obj.subObject.name,
  };
});

the above code would take an array like this:
myObjectArray = [
  { subObject: { name: "a" } },
  { subObject: { name: "b" } },
  { subObject: { name: "c" } },
]

and return this:
[
  { key: "a" },
  { key: "b" },
  { key: "c" },
]

you could assign the result to a computed property.  I'm not sure where your label values comes from but I'm sure you could modify the above code to include it


text:
Q: R: for loop on different sub samples I try to create descriptive statistics for different groups of refugees. I want to use a for loop which creates the same tables always for a certain sub sample of my refugees data base. I create multiple sub groups for different countries using a list.
I tried:
all <- refugees
syr <- subset(refugees[refugees$nation_vorher == "MSYR"])
all$arrival_y <- format(as.Date(all$arrival), format("%Y"))
all$gebj <- as.integer(all$gebj)
syr$arrival_y <- format(as.Date(syr$arrival), format("%Y"))
syr$gebj <- as.integer(syr$gebj)

countries = list(all, syr)

results <- vector(mode = "integer", length = length(countries))

for (i in 1:length(countries)){
  refugees <- countries[i]

  arr2007 <- subset(refugees[refugees$arrival_y == "2007" & refugees$gebj <= 1992])
  arr2011 <- subset(refugees[refugees$arrival_y == "2011" & refugees$gebj <= 1996])
  arr2016 <- subset(refugees[refugees$arrival_y == "2016" & refugees$gebj <= 2001])
  arr2020 <- subset(refugees[refugees$arrival_y == "2020" & refugees$gebj <= 2005])
}

... more code below

The code works perfectly if I run it without the loop. However, when I run the loop I get the following Error:
Error in subset.default(refugees[refugees$arrival_y == "2007" & refugees$gebj <=  :
argument "subset" is missing, with no default
I hope you can help me, thanks!
EDIT some lines of data:
     ID arrival      nation_vorher    bez_stsl gebj gesl arrival_y
     1    2005-01-01          MSYR     Serbien 1955    F      2007
     2    2009-02-23          MAFG        <NA> 1953    M      2009
     3    2002-08-27          MSYR     Serbien 1976    M      2016
     4    2004-07-01          <NA>        <NA> 1943    F      2016
     5    2005-05-30           MKS      Kosovo 1977    F      2020


text:
Q: Evaluate $\int_0^k \frac{\cos x}{1+\sin^{2}x}{}x = \frac{\pi}{4}$ for the value of $k$ Evaluate $\int_0^k \frac{\cos x}{1+\sin^{2}x}{}x = \frac{\pi}{4}$ for the value of $k$.
My approach :
Let $1+\sin^{2}x = t \implies dx = \frac{dt}{2 \sin x \cos x}$
and the integral changes to   $\frac{1}{2}\int_1^{1+sin^{2}k} \frac{1}{t \sqrt{t-1}}dt$
Now if I put $t = sec^{2} \theta \implies dt = 2 \sec^{2} \theta \tan\theta d\theta$ which leaves us with $\int \frac{1}{tan \theta} d\theta$ Solving this I get $-cosec^{2} \theta$
Is it correct ? By the end I am confused with the values of limits of integral. How do I calculate $k$ ? Also, is there any oter shorter way of solving this ?

A: The integrand function is the derivative of $$\arctan ( \sin x)$$
so that you have to solve
$$\arctan (\sin k ) = \frac{\pi}{4}$$
$$\sin k = 1$$
$$k = \frac{\pi}{2} + 2m \pi\ \ \ \ , m \in  \Bbb{Z}$$

A: $$\int_0^k \frac{\cos(x)\ \text{d}x}{1 + \sin^2(x)}$$
Substitute
$$y = \sin(x) ~~~~~~~ \text{d}y = \cos(x)\ \text{d}x$$
Extrema will rum from $\sin(0) = 0$ to $\sin(k)$
$$\int_{0}^{\sin(k)} \frac{\text{d}y}{1 + y^2} = \arctan(y)\bigg|_0^{\sin(k)}$$
So in the end you have to solve this:
$$\arctan(\sin(k)) - \arctan(0) = \frac{\pi}{4}$$
That is
$$\arctan(\sin(k)) = \frac{\pi}{4}$$
$$\sin(k) = \tan\left(\frac{\pi}{4}\right)$$
Which happens for $\sin(k) = 1$ namely
$$k = \frac{\pi}{2}\left(1 + 4n\right) ~~~~~~~~~~~ n\in\mathbb{Z}$$


text:
Q: Can I search getJSON for certain value and then execute the right PHP? As part of my web app I created a button that on click event should send push message to user mobile device (android or ios)
I am standing against two challenges:
First: Checking the value in order to decide if I need to pass it to the android or ios PHP script.
I don't know how to code it in JS but on PHP it should be something like this:
<?php
$token= 'APA34324324343';
$findme   = 'APA';
$pos = strpos($token, $findme);

if ($pos === false) {
    exec("ios_push.php $token > /dev/null &");
} else {
    exec("andorid_push.php $token > /dev/null &");
    }
?>

Second: Writing the correct syntax in the $.getJSON function that will take the $value and pass it on to the correct PHP script.
This is what I have right now:
    '<button onclick="' .
    "var activeValue = $(this).siblings('.user_token_value');" .
    "var activeCaption = $(this).siblings('.user_token_caption');"  .
    "$.getJSON(
    'send_push.php?id=" . $rowData['token'] .

Any help will be appreciated
Thanks in advance
Abraham


text:
Q: Android Sensors using continuous mode to capture Sensor data every 10 milliseconds I am trying to capture Accel, Gyro, Mag data at 100hz which is a sampling rate every 10 milliseconds, the usual rates do not fit this pattern GAME is 20ms, and NORMAL is 200ms then you have FASTEST which is 0ms.
I can see that Android introduced Sensor direct channels and sensor reporting mode contiuous which can be set using sampling_period_ns. However i cannot see any documentation or examples anywhere on how to fully implement this. Can anyone who has experience please let me know. at the moment i am using the onChange callback with is unsuitable:
    private void registerListener() {
        SensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
        SensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_GAME);
        SensorManager.registerListener(this, pressure, SensorManager.SENSOR_DELAY_GAME);
        SensorManager.registerListener(this, magnetic, SensorManager.SENSOR_DELAY_GAME);
    }

Then I handle the events in onSensorChanged, however this is 20ms not the required 10

A: According to the document on registerListener method you can specify the rate in ms. For the third parameter samplingPeriodUs the document states

int: The rate sensor events are delivered at. This is only a hint to the system. Events may be received faster or slower than the specified rate. Usually events are received faster. The value must be one of SENSOR_DELAY_NORMAL, SENSOR_DELAY_UI, SENSOR_DELAY_GAME, or SENSOR_DELAY_FASTEST or, the desired delay between events in microseconds. Specifying the delay in microseconds only works from Android 2.3 (API level 9) onwards. For earlier releases, you must use one of the SENSOR_DELAY_* constants

Thus you can try a sampling period of 10 ms. If it is slower then you can do nothing about it. But if is faster then you can try Thread.sleep for a few ms or for kotlin use
delay with runBlocking.

A: You can't. While you can give a hint to the system about your desired acquisition rate, it might still pick a different rate or even deviate from the rate it has chosen (especially if the sensor is used for other tasks in parallel). Also, since it simply hands the data over to your listener, there is no way you can delay the acquisition.
I have not yet tried SensorDirectChannel myself, but it does not seem to solve your problem. Here the documentation states for all selectable frequency presets that

the actual rate is expected to be between 55% to 220% of nominal rate.

Your best bet is to simply request a rate that is high enough for your needs (or maybe SENSOR_DELAY_FASTEST) and discard the events that arrive too soon. Depending on your use case, it might be sufficient to simply discard anything arriving before 10ms have elapsed (simply compare to last non-discarded timestamp) or to actually interpolate between values to get something that matches exactly your desired timestamps.
Also note, that the sensors you listed typically have very different maximum sampling rates. While accelerometer and gyroscope almost always at least reach 100 Hz (i.e. 10ms period), there are many magnetometers that will not go beyond 50 Hz. You can check out the statistics from several thousand users running their sensors at SENSOR_DELAY_FASTEST as well as individual devices here.


text:
Q: rails content_for rendering content twice I use fields_for as so:
<%= f.fields_for :task_comments, @task_category.task_comments do |task_comment_builder| %>
  <%= render 'field', f: task_comment_builder %>
<% end %>

My fields partial contains the following:
<% content_for :dynamic_field do %>
  <%= f.text_field :comment %>
<% end %>

<%= render 'shared/dynamic_field' %>

dynamic_field partial contains this:

  <%= yield :dynamic_field %>

What happens is if there are 3 task comments, instead of displaying the comment field once for each task_comment, it displays the comment field twice for each task_comment.
What might I be doing wrong?

A: Rather than using content_for, I decided to use render layout, which does the job:
<%= f.fields_for :task_comments, @task_category.task_comments do |task_comment_builder| %>
  <%= dynamic_fields task_comment_builder do |f| %>
    <%= render 'field', f:f %>
  <% end %>
<% end %>

  # application_helper.rb
  def dynamic_fields(f, options = {}, &block)
    options[:id] ||= "#{f.object.class.name.underscore}_#{f.object.object_id}"
    render layout: "shared/dynamic_fields", locals: {f: f, options: options}, &block
  end

# shared/_dynamic_fields.html.erb

  <%= link_to(raw(''), '#', class: 'btn btn-danger remove-field', style: "float: right;") %>

    <%= yield f %>


text:
Q: How to fetch/count millions of records in mongodb with nodejs We have a collection with millions of records in mongoDB. its taking lots of time and time out to count and create pagination with these records. whats the best way to do it using nodejs. I want to create a page where I see records with pagination, count, delete, search of records. Below is the code which doing query to Mongo with different conditions.
crowdResult.find({ "auditId":args.audit_id,"isDeleted":false})
            .skip(args.skip)
            .limit(args.limit)
            .exec(function (err, data) {
                if (err)
                    return callback(err,null);
                console.log(data);
                return callback(null,data);
            })

A: If the goal is to get through a large dataset without timing out then I use the following approach to get pages one after another and process the paged resultset as soon as it becomes available:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f
Please focus on the following lines to get a quick idea of what the code is doing before diving deeper:

*

*Let getPage() handle the work, you can set the pageSize and query to your liking:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L68

*Method signature:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L29

*Process pagedResults as soon as they become available:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L49

*Move on to the next page:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L53

*The code will stop when there is no more data left:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L41

*Or it will stop when working on the last page of data:
https://gist.github.com/pulkitsinghal/2f3806670439fa137210fc26b134237f#file-sample-js-L46
I hope this offers some inspiration, even if its not an exact solution for your needs.


text:
Q: Movie about a boy who goes back in time to stop a building from burning down It's about a boy who goes back in time to save a building from getting burned down, or something like that. I think a little girl from that time was helping him, and no one from that time can see him. I think one of the family members in the past was planning on burning it down.
Anyone know what this is?

A: The Amazing Mr. Blunden

A mysterious, very old solicitor Mr. Blunden visits Mrs. Allen and her young children in her squalid, tiny Camden Town flat and makes her an offer she cannot refuse. The family become the housekeepers to a derelict country mansion in the charge of the solicitors. One day the children meet the spirits of two other children who died in the mansion nearly a hundred years previously. The children prepare a magic potion that allows them to travel backwards in time to the era of the ghost children. Will the children be able to help their new friends and what will happen to them if they do??

From the longer synopsis:

Lucy and James take the potion and travel back to 1818. They meet Tom who excitedly reckons they have come from America - the new world - where one day he hopes to go. They quickly realise no adults can see them, the exception being Bella who has the mind of a child. They spook her into getting her mother to release Georgie from the cellar.

....

Lucy and James realise the nursery where Sara and Georgie sleep is above the library where the fire will start. They try unsuccessfully to get the keys off Mrs Wickens and rush outside to see Mr Wickens carrying a bundle of wood to the fire he has just started outside the library.


text:
Q: How to write a Jenkins plugin that analyses sonar output? Can anyone suggest the best approach to writing a Jenkins/Hudson plugin, that will analyse the output of a "Sonar" action?
The idea is that I want to do something like this:
a. Checkout Code > b. Run Sonar > c. Email the developers their violations

Now, how would you write the c. part? I am not sure where to start.
Is anyone an expert in Jenkins plugins?

A: You could use the "Build Breaker" Sonar plugin to break the Jenkins build whenever it detects a violation.

A: The first thing I would do is to write the code that will find the (new) violations for each developer. For this you need some Sonar knowledge.
Then take a look at a plugin that does something similar to what you want to accomplish. As you want to send mails as a post-build step, I would suggest taking a look at the ext-email Plugin.
The Plugin-Tutorial in the Jenkins Wiki is a very good starting point to get you set up to start coding.
Great plugin idea btw, I'm very interested in the resulting plugin :-)


text:
Q: Laravel Eloquent - Attach vs. SyncWithoutDetaching What is the difference between syncWithoutDetaching and attach in Laravel?

A: Let's assume that you have auto-increment primary key id in your pivot table, you will notice:

*

*attach() will add the new records to the pivot table, and pre-existed relations will get fresh ids.

*sync() will remove all existed relations and set only provided in current request, with fresh ids too.

*syncWithoutDetaching() will not remove all existing relations missing from the one provided in current process, then the pre-existed rows won't get new ids.

A: Two things:

*

*attach() will always add a new record to the pivot table, whereas syncWithoutDetaching() will only add a new record if one does not exist.

Let's say you have orders and items.
$order->items()->attach(1);
$order->items()->attach(1);

// $order->items()->count() === 2

$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);

// $order2->items()->count() === 1

*attach() returns null, whereas syncWithoutDetaching() returns an array showing what was attached/detached/updated.

A: attach() will add new records even if they already exist.
sync() will remove records that don't exist in the sync(), leave untouched those that already do, and add the ones that don't.
syncWithoutDetaching() is the same as sync() but doesn't remove anything.
So
1: Apple, 2: Banana, 3: Carrot

attach(['Apple', 'Date']) -> 1: Apple, 2: Banana, 3: Carrot, 4: Apple, 5: Date
Note: there are two Apples
but
sync(['Apple', 'Date']) -> 1: Apple, 4: Date
and
syncWithoutDetaching(['Apple', 'Date']) -> 1: Apple, 2: Banana, 3: Carrot, 4: Date
sync(Array, false) is the same as syncWithoutDetaching():
public function syncWithoutDetaching($ids)
    {
        return $this->sync($ids, false);
    }

In short, by default sync() detaches.


text:
Q: How to import some VueJS libraries separately, not to put all of them in only main.js file? In a VueJS application, I am currently importing font awesome libraries in main.js, however, it seems messy, so I would like to import the libraries not in main.js file, but in plugin.js, for example.
Is there any way to import libraries separately to use them globally?
I would be grateful if you could answer this. Thank you in advance.
main.js is here


text:
Q: haskell reverse polish notation being new to haskell I decied to try and implement a mini reverse polish notation function:
Takes in a list of type int and a string operator ('*','+','/','-')
apply the operator to the tail element and the tail-1 element
return the resultant list with the two elements involved in the operation popped off and the resultant element appended to the tail as such:
Where e0 = original element at index 0

r = result of the operation:

result = [e0,e1,e2...r] (elements popped off: eN, eN-1)

This is the code I have so far:
import Data.List
import System.IO

step :: [Int] -> String -> [Int]
step stack operator
    | (x:y:ys) "*" = (x * y):ys
    | (x:y:ys) "+" = (x + y):ys
    | (x:y:ys) "-" = (x - y):ys
    | (x:y:ys) "/" = (x / y):ys

And it gives me the following compile error:
• Couldn't match expected type '[Char] -> Bool'
                  with actual type '[a3]'
    • The function 'x : y : ys' is applied to one argument,
      but its type '[a3]' has none
      In the expression: (x : y : ys) "/"
      In a stmt of a pattern guard for
                     an equation for 'step':
        (x : y : ys) "/"

I believe this is the result of an error in my syntax,
any help is welcome!

A: You've implemented the function correctly, but your syntax is slightly wrong - you've used guards when you want to use pattern matching:

*

*Pattern matching is used when you want to decompose a parameter into smaller parts or treat it in several cases; whereas

*Guards are used when you want to select one branch of a function based on a boolean condition, similarly to an if/then/else expression. (So the condition of a guard has to be a valid expression of type Bool.)

In your code, you've used guards, but you really want pattern matching, like this:
step :: [Int] -> String -> [Int]
step (x:y:ys) "*" = (x * y):ys
step (x:y:ys) "+" = (x + y):ys
step (x:y:ys) "-" = (x - y):ys
step (x:y:ys) "/" = (x / y):ys

However, this will still give an error:
* No instance for (Fractional Int) arising from a use of `/'
* In the first argument of `(:)', namely `(x / y)'
  In the expression: (x / y) : ys
  In an equation for `step': step (x : y : ys) "/" = (x / y) : ys

This error is fairly clear: you're trying to / an integer, but integers are not Fractional, so you can't do that. If you want integer division, you can replace it with div x y, otherwise you can change Int to Float in the type signature to allow non-integer values.
However, even after this change, there is still a subtle bug: what happens if your list has less than two elements, or an unsupported operator is used? The correct thing to do here is to pattern match at the end by using step _ _ = (something), where _ is a special syntax which matches anything. (Or you can also use step stack operator = (something), if you want to refer back to stack and operator for something like an error message.
EDIT: In the comments below @chepner suggested another way to do this using both pattern matching and guards:
step :: [Int] -> String -> [Int]
step (x:y:ys) op
    | op == "*" = (x * y):ys
    | op == "+" = (x + y):ys
    -- etc.
    | otherwise = (some error case)

This again illustrates the difference between the two: pattern matching is used to decompose the first argument into x, y and ys, while guards are used with boolean conditions (with otherwise actually being defined in the Prelude as being equal to True).


text:
Q: Is there an equivalence between a graded vector space and its degree-shifted counterpart? I am studying graded vector spaces and I have a simple question. Let me denote by $\mathbb Z_2=\mathbb Z\text{mod}2=\{-1,0,+1\}$. Now let's perform a shift by an integer $k$ and get the set $\mathbb Z_2+k=\mathbb Z\text{mod}2+k=\{k-1,k,k+1\}$.
Intuitively, I have the feeling that the two sets $\mathbb Z_2$ and $\mathbb Z_2+k$ are equivalent, in that a $\mathbb Z_2$-graded vector space has the same decomposition in vector subspaces as a $\mathbb (\mathbb Z_2+k)$-graded vector space. The only difference is the degrees of the homogeneous elements in each space, which are naturally shifted by $k$.
Is the $(\mathbb Z_2+k)$-graded vector space the same as the initial $\mathbb Z_2$-graded vector space?
If yes, is it because of some sort of isomorphism between the two sets $\mathbb Z_2$ and $\mathbb Z_2+k$?


text:
Q: Java Default Authentication vs arguments for proxy I've searched a lot for this topic, but didn't understand exactly why if I try to consume a web service in my java application I would fail without implementing with this snippet as well:
final String authUser = "myUser";
    final String authPassword ="******";
    Authenticator.setDefault(
       new Authenticator() {
          public PasswordAuthentication getPasswordAuthentication() {
             return new PasswordAuthentication(
                   authUser, authPassword.toCharArray());
          }
       }
    );

...I don't like to "sculpt" my credentials here, or in a property file.
i'd prefer to use the "Run as" vm arguments...so if I comment the code above and run my app with:
-Dhttps.proxyHost=proxy.test.it
-Dhttp.proxyPort=3128
-Dhttp.proxyUsername=myUser
-Dhttps.proxyPassword=****
-Danypoint.platform.proxy_username=myUser
-Danypoint.platform.proxy_password=****
-Danypoint.platform.proxy_host=proxy.test.it
-Danypoint.platform.proxy_port=3128
-Djava.net.useSystemProxies=true
-Dhttp.nonProxyHosts=...

or...
    System.setProperty("http.proxyUser", authUser);
    System.setProperty("http.proxyPassword", authPassword);
    System.setProperty("http.nonProxyHosts","myHost");
    System.setProperty("useSystemProxies","true");

it won't work. I really don't get it.
Thanks for support!

A: I'm not sure exactly what you're trying to achieve, but if you pass in your data through the vm arugments like this
-Dhttp.proxyUsername=myUser
-Dhttps.proxyPassword=****

You would access the data like this.
String authUser = System.getProperty("http.proxyUser");


text:
Q: Run Method in the Thread class not being called I am a pretty new guy to the world of threading, have been trying to solve this problem for a week now.
The run method in the Thread class is not being called for some reason, I dont know why ( but would love to know)
        ProcessBuilder processBuilder = new ProcessBuilder();

        processBuilder.command("/bin/sh", "-c", "echo \"w30000001z,none,16488,,181075\nw30000001z,none,16488,,181082\n\" | /home/beehive/bin/exec/tableSize");
        Process process = processBuilder.start();
        process.waitFor();

        InputStream stdin = process.getInputStream();
        OutputStream stdout = process.getOutputStream();
        InputStream stderr = process.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(stdin));
        BufferedReader error = new BufferedReader(new InputStreamReader(stderr));
        StreamGobbler errorStream = new StreamGobbler(process.getErrorStream(), "ERROR");
        StreamGobbler outputStream = new StreamGobbler(process.getInputStream(), "OUTPUT");

        errorStream.start();
        outputStream.start();
        errorStream.join();
        outputStream.join();

tableSize is a python executable which takes input through its stdin, processes it and outputs a few lines of text. I need to collect this output and do some further processing on it.
There is a separate thread to process the output on the inputStream and errorStream. This thread class is as shown below.
/* StreamGobbler.java */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

class StreamGobbler extends Thread
{
    InputStream is;
    String type;
    OutputStream os;

    StreamGobbler(InputStream is, String type)
    {
        this(is, type, null);

    }
    StreamGobbler(InputStream is, String type, OutputStream redirect)
    {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }

    public void run()
    {
        try
        {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);

            System.out.println("Ajay" + type);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
            {
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe)
            {
            ioe.printStackTrace();
            }
    }
}

For some reason, the run method in the StreamGobbler class is not being called. However the constructor of this class is being executed.
Any help would be much appreciated.

A: You need to start the stream gobblers before you call process.waitFor().
The stream gobblers read and discard the external processes output / error streams so that the external process doesn't block while trying to write.  But the way you have it, the process has to have finished writing (and exited) before you attempt to gobble the output.
Result - deadlock ... if the external process writes too much to its output streams.

Actually, I think that the primary problem is that your Java code does not write anything to inputStream.  So, the external process just sits there waiting for input that never arrives ... and process.waitFor() waits for the external process.   Deadlock.
The correct order of things should be:

*

*build the process and start it.

*build the gobblers and start them.

*open the input stream.

*write stuff to input stream.

*close input stream.

*call process.waitFor() and check the processes return code.

*look at the output captured by the gobblers

A: You need consume the STDOUT and/or STDERR before Process.waitFor(), here's an excellent article:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2

A: 1) Try removing the waitFor() if it is not required. It only makes the executing thread wait until the process execution is completed.


text:
Q: How to run Webdriver.io heedlessly in node.js I am running this in node.js
//test.js
var webdriverio = require('webdriverio');
webdriverio
    .remote({desiredCapabilities: {browserName: 'firefox'}})
    .init()
    .url('https://www.google.com')
    .end()

But I get a FireFox browser with every iteration. Is there a way to run this without browser but have browser functionality (i.e. the browser doe not open).
Thanks

A: Yes, you should take a look at phantomjs
You'll want to download phantomjs and run your selenium server with the following argument: -Dphantomjs.binary.path=PATH_TO_PHANTOMJS_EXE
Then you'll want to start selenium with the following option:
{desiredCapabilities: {browserName: 'phantomjs'}}


text:
Q: Merge a data.table and a list I want to add a list into my data.table. Lets consider this data.table:
dt = data.table(id = 1:3)

lst <- list()
lst[[2]] <- cbind(a=10:12, b=5:7)

dt[-nrow(dt), lst:=lst]

dt
#   id               lst
#1:  1
#2:  2 10,11,12, 5, 6, 7
#3:  3

Is it possible to "unlist" the lst, so that the data.table will look like this?
      id  a  b
1.0:  1
2.0:  2
2.1:  2   10 5
2.2:  2   11 6
2.3:  2   12 7
3.0:  3

There is also a speed issue, as the data I am working with consists of billions of rows.

A: An option as mentioned in comment:
rbindlist(list(dt,
        rbindlist(lapply(lst, as.data.table), idcol='id')),
    use.names=TRUE, fill=TRUE)[order(id)]

output:
   id  a  b
1:  1 NA NA
2:  2 NA NA
3:  2 10  5
4:  2 11  6
5:  2 12  7
6:  3 NA NA

A: You can run a lapply across the list, and add the rows to an empty row if the item in the list is non-empty:
dt <- data.table(id = 1:3)

lst <- list()
lst[[2]] <- cbind(a=10:12, b=5:7)

create_table <- function(x, lst) {
  if (!is.null(lst[[x]])) {
    # Empty row plus items in list
    rbindlist(
      list(data.table(id = x), data.table(id = x, lst[[x]])),
      use.names = TRUE, fill = TRUE
    )
  } else {
    data.table(id = x)
  }
}

aux_lst <- rbindlist(
  lapply(seq(lst), create_table, lst = lst),
  use.names = TRUE, fill = TRUE
)

aux_lst[dt, on = .(id)] # Keeps all IDs in dt

If the list is named and the id column relates to those names, then replace seq with names

A: Some reformatting is needed, but you can use rbindlist:
# create all entries in lst
length(lst) <- nrow(dt)

# identify table sizes
lens     = sapply(lst, NROW)

# use data.tables instead of matrices
# fill empty tables with a blank template
template = data.table(a=NA_real_, b=NA_real_)
dtlist   = replace(lapply(lst, as.data.table), lens == 0, list(template))

# expand dt to match tables
replens  = pmax(lens, 1L)
cbind(dt[rep(1:.N, replens)], rbindlist(dtlist))

   id  a  b
1:  1 NA NA
2:  2 10  5
3:  2 11  6
4:  2 12  7
5:  3 NA NA

A: library(data.table)

dt = data.table(id = 1:3)

lst <- list()
lst[[2]] <- cbind(a=10:12, b=5:7)

unique(rbindlist(lapply(1:length(lst), function(i) {
  data.table(id = i, lst[[i]])[dt, on = .(id)]
}
  ), fill=TRUE))[order(id)]

   id  a  b
1:  1 NA NA
2:  2 NA NA
3:  2 10  5
4:  2 11  6
5:  2 12  7
6:  3 NA NA


text:
Q: search end users ipaddress by their username Hi I'm trying to do a PowerShell search that I'm able to input the end users SAMaccountName and it to push out the computer IPv4 address that they are logged into.
When trying to run the script it asks for a Class: and wont give me an IPv4 address for the user.
$selectUser = Read-Host 'What is the endusers username?'
$compname = Get-ADComputer -Filter * -Properties ipv4Address | select Name
ForEach($device in $compname) {
    $usr = Get-WmiObject –ComputerName $device | Select-Object UserName
    if($usr -eq $selectUser){
        $compip = Get-ADComputer -Filter * -Properties ipv4Address | select ipv4Address
    }
}

cmdlet Get-WmiObject at command pipeline position 1
Supply values for the following parameters:
Class:
PS C:\Windows\system32>

A: Just as the prompt indicates, you need to supply a value for the -Class parameter of Get-WmiObject; it's required.  Based on your use of the UserName property, it looks like you want the Win32_ComputerSystem class...
$usr = Get-WmiObject –ComputerName $device -Class Win32_ComputerSystem | Select-Object UserName

Also, because you are using the (positional) -Property parameter of Select-Object to retrieve the UserName property, $usr will not contain the UserName property directly but instead an object with a single UserName property.  Your condition in the following if statement, $usr -eq $selectUser, will not behave as you expect.
To fix this, compare against the $usr.UserName property instead...
if($usr.UserName -eq $selectUser){

Alternatively, to have $usr store the UserName text directly you can use the -ExpandProperty parameter of Select-Object...
$usr = Get-WmiObject –ComputerName $device -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName
if($usr -eq $selectUser){

...or use member syntax to retrieve the UserName property...
$usr = (Get-WmiObject –ComputerName $device -Class Win32_ComputerSystem).UserName
if($usr -eq $selectUser){


text:
Q: beginSheetForDirectory ... Deprecated I have following code which works fine, however when I updated to Lion I started getting warnings that this method has been deprecated and suggests that I use "beginSheetModalforWindow".  How would you translate the following to code to use that?
[savePanel beginSheetForDirectory: NULL
                                 file: fileName
                       modalForWindow: mWindow
                        modalDelegate: self
                       didEndSelector: @selector(savePanelDidEnd:returnCode:contextInfo:)
                          contextInfo: NULL];

A: It's actually beginSheetModalForWindow:completionHandler:, and you'd do something like this:
[savePanel setNameFieldStringValue:fileName];
[savePanel beginSheetModelForWindow:mWindow completionHandler:^(NSInteger result) {
    if (result == NSFileHandlingPanelOKButton) {
        // do the save
    }
}];


text:
Q: When using MVC in PHP,Should 1 Controller be able to load a entire dynamic user profile? Im almost scared to ask questions around here these days because I useually get flammed on and told my question is dumb, but here it goes anyways...
Im new to MVCs and im starting to get the hang of them, but one thing im unsure about is if 1 controller is suppose to load a entire profile that has multiple components (i.e a notification beacon, a friend feed, a list of friends that displays thumbnails , a place to post statuses ect...)for the purposes of this post assume im asking if alll the loading for a entire facebook profile should be done in one controller?
Or do i separate each dynamic component into its own MVC and then glue them all together in one main controller or....?
another idea i had was that maybe u do separate each component , but instead of having one main controller you call them as needed in the index.

A: You could use one controller for the Profile (using your example) and have multiple models fetch and process all the data you need to show. This way even a big page can result in an easy to understand controller that is not so big.


text:
Q: Xamarin Forms - Binding Multiple TextCells in one ListView I am having trouble binding multiple TextCells in a ListView. It works fine if there's only one, but gives XamlParseException on adding more. The same Exception occurs while trying to bind a Label. That's why I had to use a TextCell. What's the solution?
<ListView x:Name="pList">
    <ListView.ItemTemplate>
      <DataTemplate>
        <TextCell x:Name="a" Text="{Binding ReceiverName}" TextColor="White" />
      </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

A: From your comment on one of the answers, it looks like this is what you want
    <ListView x:Name="pList">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <ViewCell.View>
                <StackLayout>
                  <Label Text="{Binding ReceiverName}" TextColor="White" />
                  <Label Text="{Binding SecondText}" TextColor="White" />
                  <Label Text="{Binding ThirdText}" TextColor="White" />
                </StackLayout>
              </ViewCell.View>
             </ViewCell>
           </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

This will display 3 Labels vertically.The problem you were having is that the DataTemplate can't have more than one child. The standard way around that is to use a layout control such as StackLayout.
Please see this page for more information: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/controls/layouts/

A: Guessing from the code you've pasted I'd say that the problem is that you give the control a name. Remove the a:Name and try again.
If that doesn't help, post the exception details as well.

A: you need to add the "ViewCell" inside the data template like this:
<ListView x:Name="pList">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <ViewCell.View>
          <TextCell x:Name="a" Text="{Binding ReceiverName}" TextColor="White" />
        </ViewCell.View>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

A: TextCell also has a detail attribute :
<TextCell x:Name="a" Text="{Binding ReceiverName}" Detail="{Binding AnotherName}" TextColor="White" />