Q: Messaging.MassEmailMessage class doesn't work when we set a list of case ids as whatids. It works fine if we don't set whatids Please help me fix my issue with Messaging.MassEmailMessage class. It doesn't work when I set a list of contactIds as my targetObjectIds and set a list of case ids as whatids. It works fine if i don't set whatids.
//This is a Utility Class that sends out eamils when a ticket comment is update
//June 14, 2014
public class MassEmailHelper {

   public MassEmailHelper(){}

   public static void notifyAll(List<Case> ticketsToNotify, Boolean setActivity)
{
        Integer num = 0;
        MassLists__c massEmail;
        List<MassLists__c>massEmailList = new List<MassLists__c>();

        Set<ID> ParentTicketIDs = new Set<ID>();
        List<Contact> ContactListIDs = new List<Contact>();

        List<Id> CaseAccountIds = new List<Id>();

      /* //Get the Account ID associated with the ticket comment that has been updated
      ParentTicketList = [SELECT Id, AccountId, Notify_All__c, Mass_Notification__c,
                       Status FROM Case WHERE Id IN: ParentTicketIDs];*/

       for(Case c: ticketsToNotify)
            if(c.Notify_All__c==true)
                CaseAccountIds.add(c.AccountId);

       System.debug('The size of account List is: :' + CaseAccountIds.size());
      //Get all the ids for the contacts to email. Bascially, all support site users from the Accounts for the tickets
      //ContactsToEmailIdList = [Select Id, AccountId From Contact where  AccountID in :CaseAccountIds and Receive_Support_Notifications__c=true];

        Map<Id, Account> mapAccounts = new Map<ID, Account>([Select Id, (Select Id, Email From Contacts where
                                     Receive_Support_Notifications__c=true) from Account where Id IN :CaseAccountIds]);

        Integer batchSize =240;
        List<Messaging.Email> mailList = new List<Messaging.Email>();
        Messaging.Massemailmessage mail = new Messaging.Massemailmessage();
        List<Id> contactList=new List<Id>();
        Id[] caseList = new List<Id>();
        string TemplateName = '{Customer} Ticket has been updated';
        system.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> fetching email template');
       EmailTemplate e = [select Id,Name,Subject,body, HtmlValue from EmailTemplate where name like :templateName+'%'];
     //  templateName='test4';
       // EmailTemplate e = [select Id,Name,Subject,body, HtmlValue from EmailTemplate where name like :templateName];
        Account accWithContacts;
        mail.setTemplateId(e.Id);
        mail.setSaveAsActivity(false);
        system.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Set initial params for email');

        for(Case caseObj:ticketsToNotify ){
            if(caseObj.Notify_All__c == true){
                    accWithContacts = mapAccounts!=null ? mapAccounts.get(caseObj.AccountId): null;
                    System.debug('XXXXXXXXXXXXX accWithContacts  '+accWithContacts );
                    if( accWithContacts !=NULL && accWithContacts.Contacts!=NULL)
                        for(Contact contactObj: accWithContacts.Contacts){
                           if(contactList.size()>batchSize){
                           System.debug('XXXXXXXXXXXXX I am in 55');
                                mail.setWhatIds(caseList);
                                mail.setTargetObjectIds(contactList);
                                mailList.add(mail);
                                mail = new Messaging.Massemailmessage();
                                mail.setTemplateId(e.Id);
//                              mail.setSaveAsActivity(setActivity);
                                contactList = new List<Id>();
                                caseList=new List<Id>();
                            }
                            caseList.add(caseObj.Id);
                            contactList.add(contactObj.Id);
                           /* insertUpdateTicketInfo(num, setActivity,massEmail, contactObj,e,
                            caseObj,massEmailList );
                            num++;*/
                     }
                     System.debug('XXXXXXXXXXXXX caseList '+caseList);
                     System.debug('XXXXXXXXXXXXX contactList'+contactList);
                }
            else{
                                       System.debug('XXXXXXXXXXXXX I am in 76');
                    if(caseObj.ContactId!=null){
                                               System.debug('XXXXXXXXXXXXX I am in 78');
                        if(contactList.size()>batchSize){
                                                   System.debug('XXXXXXXXXXXXX I am in 80');
                            mail.setWhatIds(caseList);
                            mail.setTargetObjectIds(contactList);
                            mailList.add(mail);
                            mail = new Messaging.Massemailmessage();
                            mail.setTemplateId(e.Id);
  //                        mail.setSaveAsActivity(setActivity);
                            contactList = new List<Id>();
                            caseList=new List<Id>();
                        }
                        caseList.add(caseObj.Id);
                        contactList.add(caseObj.ContactId);
              //          mailPrimaryContact(setActivity, mail, caseObj, e, mailList);
                         System.debug('XXXXXXXXXXXXX caseList2 '+caseList);
                     System.debug('XXXXXXXXXXXXX contactList2'+contactList)  ;
                    }
                    if(caseObj.Additional_Contact_1__c!=null){
                       if(contactList.size()>batchSize){
                            mail.setWhatIds(caseList);
                            mail.setTargetObjectIds(contactList);
                            mailList.add(mail);
                            mail = new Messaging.Massemailmessage();
                            mail.setTemplateId(e.Id);
    //                      mail.setSaveAsActivity(setActivity);
                            contactList = new List<Id>();
                            caseList=new List<Id>();
                        }
                        caseList.add(caseObj.Id);
                        contactList.add(caseObj.Additional_Contact_1__c);
//                       mailPrimaryContact(setActivity, mail, caseObj, e, mailList);
                    }
                    if(caseObj.Additional_Contact_2__c!=null){
                        if(contactList.size()>batchSize){
                            mail.setWhatIds(caseList);
                            mail.setTargetObjectIds(contactList);
                            mailList.add(mail);
                            mail = new Messaging.Massemailmessage();
                            mail.setTemplateId(e.Id);
      //                    mail.setSaveAsActivity(setActivity);
                            contactList = new List<Id>();
                            caseList=new List<Id>();
                        }
                        caseList.add(caseObj.Id);
                        contactList.add(caseObj.Additional_Contact_2__c);
//                        mailPrimaryContact2(setActivity, mail, caseObj, e, mailList);
                    }
              }
        }
          system.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Case List Size '+caseList.size());
        system.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Contact List Size '+contactList.size());
        if(contactList.size()>0){
        System.debug('XXXXXXXXXXXXX caseList 131'+caseList);

            mail.setWhatIds(caseList);
            mail.setTargetObjectIds(contactList);
  //        mail.setUseSignature(false);
            mailList.add(mail);
        }

        //send email
            System.Debug('>>>>>>>>>>>>>>>>>>>>>>>>>> The mail List size is: '  +mailList.size() );
            if(mailList!=null && !mailList.isEmpty() && mailList.size() > 0){
                for(Messaging.Email m: mailList)
                        System.debug('Contact List size '+((Messaging.Massemailmessage)m).getTargetObjectIds().size()
                        +' and what id size '+((Messaging.Massemailmessage)m).getWhatIds().size());
                 try{

                      List<Messaging.Sendemailresult> srs =  Messaging.sendEmail(mailList, false);
                      system.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> After mass email');
                      for(Messaging.Sendemailresult sr : srs)
                          if(!sr.isSuccess())
                            system.debug('Messaging failed '+sr.getErrors()[0].getMessage());

                  }catch (Exception ex){
                       system.debug('A fatal exception occurred '+ex);
                  }
              }

            /**
            if(massEmailList!=null && !massEmailList.isEmpty() && massEmailList.size() > 0)
                system.debug('Number of emails to email from update Ticket Comments is: ' +massEmailList.size());
            insert massEmailList;
            **/

   }//end of email method

      public static void insertUpdateTicketInfo(Integer num, Boolean setActivity, MassLists__c massEmail, Contact contactObj,EmailTemplate e,
      Case caseObj,List<MassLists__c>massEmailList ){

       massEmail = new MassLists__c();
       massEmail.Set_Activity__c = setActivity;
       massEmail.filterCode__c = 'CDT';
       massEmail.Name = 'MassCommentUpdateTicket'+num;
       massEmail.ContactID__c = contactObj.Id;
       massEmail.TemplateID__c = e.Id ;
       massEmail.TicketID__c = caseObj.Id;
       massEmailList.add(massEmail);
    }
 }

I am using cases for the whatIds. I know that I can use Messaging.SingleEmailMessage. However, for this particular scenario, I need to use Messaging.MassEmailMessage. Please let me know why Messaging.MassEmailMessage is not working with cases as whatIds.
Thanks in advance!


Q: Migration from SherlockActionBar to ActionBar I just migrate to native actionBar, before, with ABS it was working great.
Now, I don't need anymore compatibility as I develop for API 16+
I changed all references, and now, my menu only shows in text, with physic button, it doesn't show up in action bar...
I don't know what am I missing...
Here is my code :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/menu_sync"
    android:icon="@drawable/ic_action_update"
    android:orderInCategory="80"
    android:showAsAction="ifRoom"
    android:title="Sync"/>
<item
    android:id="@+id/more"
    android:icon="@drawable/ic_action_core_overflow"
    android:orderInCategory="90"
    android:showAsAction="always"
    android:title="See more options">
    <menu>
        <item
            android:id="@+id/menu_send_coords"
            android:icon="@drawable/ic_action_send_coords"
            android:orderInCategory="80"
            android:showAsAction="ifRoom"
            android:title="Send Coords"
            android:visible="true"/>
        <item
            android:id="@+id/menu_foto"
            android:icon="@drawable/ic_action_device_access_camera"
            android:orderInCategory="100"
            android:showAsAction="ifRoom"
            android:title="Foto"
            android:visible="true"/>
    </menu>
</item>

In my Activity :
public class DashBoard extends BaseActivity { //BaseActivity extends ActionBarActivity
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

I tried to change the menu xml to another one ( google example), but it did not work.
I made a search fro any reference to Sherlock* and replace all of them
In my manifest I have :
  <application
    ...
    android:theme="@style/Theme.AppCompat" >

In my style.xml I have :
     <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <!-- nothing API level dependent yet -->
</style>

    <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

I've followed each step of :
http://www.grokkingandroid.com/migrating-actionbarsherlock-actionbarcompat/
What are the common issues when migrating from ActionBarSherlock to ActionBarCompat?
ActionBarCompat menu item is not showing
I don't know what more can I do???
Any help would be appreciated !

A: I think you should change your style.xml and your Android Theme since you don't ne the Android appcompat libarary anymore.
styles.xml:
<style name="AppBaseTheme" parent="@style/Theme.Holo.Light.DarkActionBar">
<!-- nothing API level dependent yet -->
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

AndroidManifest.xml:
    <application
        android:theme="@style/AppTheme"
    ...


Q: Can someone explain an S-Statistic analysis? What exactly is an S-Statistic analysis, and what does this equation represent?
$(D-F)^2/σ^2$
I understand that σ is the uncertainty of D, but that's about it.


Q: how can i add a timeout function to javascript?

$('.btn').click(function() {
  $(this).toggleClass('spinner');
});

and i want to add a timeout function to it i added it like this but it does not work, any ideas why?

$('.btn').click(function() {
  $(this).toggleClass('spinner');
   setTimeout(function() {
       $this.button('reset');
   }, 8000);

});


Q: Forming Hessian Approximations from Exchangeable Data In optimisation and elsewhere, it is of interest to approximate the Hessian of a function $f$, given only evaluations of $\nabla f$ at some collection of points $\{ x^i \}_{i = 1}^N$. That is, given data $D_N = \{ ( x^i, \nabla f ( x^i ) ) \}_{i = 1}^N$, one forms a matrix $H$ such that for $x$ near $\{ x^i \}_{i = 1}^N$, $H \approx \nabla^2 f ( x )$.
The approximation which I'm most aware of is the BFGS scheme, which arises as a Quasi-Newton method in optimisation. One aspect of this scheme is that it processes the data $D_N$ sequentially, that is, it requires the interpretation that the pairs $( x^i, \nabla f ( x^i ) )$ arrived in some meaningful order (or, it requires making an arbitrary choice of ordering). Moreover, the scheme forms a sequence of approximate Hessians $\{ H^i \}_{i = 1}^N$, such that (roughly speaking), for each $i$, one has that $H^i \approx \nabla^2 f ( x^i )$.
I appreciate that the BFGS scheme is used for the purposes of optimisation, and is not designed to form a global approximation of the Hessian. I understand also that this is basically a good thing; as one is only trying to find a minimiser of $f$, a local approximation is more or less sufficient. In any case, the first point I want to make is that given data $D_N$, which do not naturally admit a sequential structure, BFGS is arguably an unnatural procedure for forming a Hessian approximation.
So, suppose the following:

*

*I have the data $D_N$.

*I want to form an approximation of the Hessian which is valid for $x$ near $\{ x^i \}_{i = 1}^N$.

*I want my approximation $H = H ( D_N )$ to be invariant under the ordering of the set $D_N$, i.e. the approximation procedure doesn't care which order the data arrived in.

My question is: Is there a standard, efficient procedure for approximating the Hessian of a function from data, which obeys condition (3) above?
Note that BFGS fails condition 3 in general.
My naive attempt at describing such a procedure was to define
\begin{align}
\hat{H} = \text{argmin}_H \left\{ \sum_{i \neq j} \| \left[ \nabla f ( x_i ) - \nabla f ( x_j ) \right]- H \left[  x_i - x_j \right]\|_2^2 \right\}
\end{align}
or something of this form, i.e. encourage the matrix $H$ to `interpolate' the gradients, and then perhaps pick the simplest such $H$ (simplest w.r.t. e.g. nuclear or $\ell^1$ norm). But this is not obviously possible to solve efficiently, especially for high-dimensional systems.

A related question is the following:

*

*I have the data $D_N$, and the ordering of the data is a priori meaningful.

*I want to form an approximation of the Hessian which is valid for $x$ near $\{ x^i \}_{i = 1}^N$.

*I want my approximation $H = H ( D_N )$ to be invariant under the direction of time, i.e. suppose the data was instead given as

\begin{align}
D'_N &= \{ ( y^i, \nabla f ( y^i ) ) \}_{i = 1}^N \\
\text{where } y^i &= x^{N + 1 - i}.
\end{align}
Then, I want that $H (D'_N) = H ( D_N )$.
As before, my question is whether such a procedure exists, can be implemented efficiently, etc. Again, note that BFGS fails this new condition 3 in general.


Q: Error installing mariadb-server mariadb-client on Chromebook I'm trying install wordpress locally on my chromebook following these instructions.
I successfully ran:
`
sudo apt update
sudo apt upgrade
sudo apt install nano

`
But then get an error when I try to run
`
sudo apt install mariadb-server mariadb-client -y

`
Here's the error from my terminal:
`
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libdbi-perl : Depends: perlapi-5.32.0
E: Unable to correct problems, you have held broken packages.

`
I'm a complete newb at Linux and spend hours googling / trying solutions to no avail. Any help is appreciated.


Q: undefined method `stringify_keys' for "/users/sign_out":String (Devise gem) In my project i am using devise gem .And also using link_to_if url helper because when users not isn't signed in , it will provide  new_user_session_path and also when they signed in it will provide destroy_user_session_path. For this at first I tried this code:
  <%=
      link_to_if(current_user.nil?, "Sign in", new_user_session_path) do
        link_to(user_signed_in?, "Sign out", destroy_user_session_path, method: :delete )
      end
  %>

its says "wrong number of arguments (4 for 3)"
Then I tried this code:
  <%=
      link_to_if(current_user.nil?, "Sign in", new_user_session_path) do
        link_to(user_signed_in?, "Sign out", destroy_user_session_path)
      end
  %>

its says "undefined method `stringify_keys' for "/users/sign_out":String"
Please help me out of this.

A: You're using a condition in your link_to call, just remove the first argument like this :).
link_to("Sign out", destroy_user_session_path)


Q: localstorage not defined ionic 2 i'm trying to import "local storage" from 'ionic-angular' and it says me
"LocalStorage is not defined"..
in addtion I got this error

RangeError: Maximum call stack size exceeded
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:153:20)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)

first time I got these error on this morning. yesterday I worked fine with another ionic 2 project.
by the way, that's my code
   import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import {Storage,LocalStorage} from 'ionic-angular';

/*
  Generated class for the Admin page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-admin',
  templateUrl: 'admin.html'
})
export class AdminPage {
  data: any;
  public local: Storage;
  public getsession:any;

  constructor(public navCtrl: NavController) {
    this.data={};
    this.data.title="";
    this.data.desc="";
    this.local=new Storage(LocalStorage);
    this.local.set('session','true');

    this.getsession=this.local.get('session');
    this.getsession.then((value)=>{
      let x=value;
      console.log(x);

    })

  }

  ionViewDidLoad() {

  }

}

A: The ionic storage has moved to '@ionic/storage'
as of rc.0
so
import { Storage } from '@ionic/storage';

You can't specify whether its localstorage/sql or anything. But it uses each in order until its able to use one.
Just create an instance and use it
new Storage().set("key","value");

A: Old Question... but it just came up in my Google Results:
import { Storage } from '@ionic/storage';

Current as of RC4


Q: HTTP Post by android always return result 0 i supposed to send http post to web service in the form
POST[messageTitle, messageContent, messageFrom]
it's like array with the name post
i searched around and some people said i should do :
nameValuePairs.add(new BasicNameValuePair("POST[]", messageTitle.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("POST[]", messageContent.getId()));
nameValuePairs.add(new BasicNameValuePair("POST[]", messageFrom.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request

        try {
            HttpResponse response = httpclient.execute(httppost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    Log.d("Cat", stringBuilder.toString());
}

but it returned {"result":0}
and supposed to return {"result":"row"}


Q: How to change the existing html text in a D3 rect? How to change the existing html text in a D3 rect to something else on the click of a button. There is an image on the top right corner of a D3 rect. When I click on that image the text inside the rect has to change to another html text like This is new text . It would be great if anyone could help me figure out a way to do it.
<!DOCTYPE html>

https://jsfiddle.net/passionateCoder/prh2acot/
I am not able to add an image to the JSFiddle.

A: This should work.

img.on('click', function () {
        txt.text('this is new text')
        });

Or for innerHTML:
img.on('click', function () {
        txt.html('this is new text')
        });

Remember that you cannot use traditional HTML in SVG Texts. Read here:
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text


Q: How to run on the page typed js I'm currently working on a project which requires me to run by the user typed javascript in the form of a string.
I've tried adding an empty <script> tag to the html and appending the string (containing the users freshly typed (after the page was loaded) javascript) to this script tag but this doesn't work. (since the code inside the script tag will be run immediately after the page is loaded).
So I tried a different approach. I wrapped the js string inside of a function like so:
function runCode() { userString }
This is what the string I now append to the empty script tag looks like:
var code = "function runCode() { "+ userString +" }"
However this still doesn't work. The code (userString) shows up in the script tag according to the chrome dev tools, but trying to run the function causes the following error:
Uncaught ReferenceError: runCode is not defined
Does somebody know how this works? What is the proper way for me to do this?
Some background:
The project I'm working on is an online tool to draw using js. The goal here is to use the two.js library and link it to a modified textarea. (codemirror) Clicking the button will take your typed in code and use it to modify the two.js canvas on the other half of the screen.
This will make it easier to draw using the library, since you don't have to set up all the html, css and js files yourself, but instead you can focus on the code.
Note: The js you type into the textarea can by any valid js, so simple things as alerts, or even jQuery lines will work just fine.

A: Use eval() function.
However be aware that this is by design a HUGE hole of security.

A: You have to use eval(). Extract the user input from an onclick event and pass it into eval like so:
eval(userString)


Q: How do I get the real error message in HttpClient response.ReasonPhrase? My Setting
I have 2 WebApi projects with the following flow:

*

*User makes request to API 1

*API 1 makes request to API 2 on behalf of the user (using an HttpClient).

using (var client = new HttpClient())
{
    client.SetBearerToken(token);

    string endpoint = PbbSettings.Identity.Users.Delete.Replace("{userId}", userId);

    // Attempt deletion of the user
    using (var response = await client.DeleteAsync(endpoint))
    {
        // Throw exception if not succeeded
        EnsureSuccess(response);
    }
}

The Problem
So the flow of control and information works fine.
The problem is that when API 2 responds with an error, response.ReasonPhrase says "Bad Request" or "Internal Server Error", instead of the message I set in the exception.
Been spitting blood on this for a whole day now. Any insights?
More Info (TLDR)
For clarity, all my APIs have a global exception filter registered to handle errors:
public class RepositoryExceptionsHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        HandleException(context);

        base.OnException(context);
    }

    public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
    {
        HandleException(context);

        return base.OnExceptionAsync(context, cancellationToken);
    }

    /// <summary>
    /// Recognizes common repository exceptions and if necessary creates a response and updates the context.
    /// </summary>
    /// <param name="context">The context in which the exception was thrown.</param>
    private void HandleException(HttpActionExecutedContext context)
    {
        var response = CreateResponse(context.Request, context.Exception);

        if (response != null)
            context.Response = response;
    }

    /// <summary>
    /// Recognizes common repository exceptions and creates a corresponding error response.
    /// </summary>
    /// <param name="request">The request to which the response should be created.</param>
    /// <param name="ex">The exception to handle.</param>
    /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns>
    private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex)
    {
        string message = ex.Message;

        if (ex is KeyNotFoundException)        return request.CreateErrorResponse(HttpStatusCode.NotFound, message);
        if (ex is ArgumentException)           return request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
        if (ex is InvalidOperationException)   return request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
        if (ex is UnauthorizedAccessException) return request.CreateErrorResponse(HttpStatusCode.Unauthorized, message);
#if !DEBUG
        // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information
        // In development time, the programmer will need the details of the error, so this general message is disabled.
        request.CreateErrorResponse(HttpStatusCode.InternalServerError, Errors.InternalServerError);
#endif

        return null;
    }
}

This works fine between the user and API 1.
But when API 1 and API 2 do their thing, the response creation ignores the message I put in and sets the status as the reason.

A: The new CreateResponse() method:
    /// <summary>
    /// Recognizes common repository exceptions and creates a corresponding error response.
    /// </summary>
    /// <param name="request">The request to which the response should be created.</param>
    /// <param name="ex">The exception to handle.</param>
    /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns>
    private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex)
    {
        string message = ex.Message;

        HttpStatusCode code = 0;

        if      (ex is KeyNotFoundException)        code = HttpStatusCode.NotFound;
        else if (ex is ArgumentException)           code = HttpStatusCode.BadRequest;
        else if (ex is InvalidOperationException)   code = HttpStatusCode.BadRequest;
        else if (ex is UnauthorizedAccessException) code = HttpStatusCode.Unauthorized;
        else if (ex is HttpException)
        {
            // HttpExceptions are thrown when request between IdentityServer and the API server have failed.
            // IdentityServer has generated an error, the API server received it and now it needs to relay it back to the client.
            var httpException = (HttpException) ex;

            code = (HttpStatusCode) httpException.GetHttpCode();
            message = httpException.Message;
        }
        else
        {
            code = HttpStatusCode.InternalServerError;

            // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information
            // In development time, the programmer will need the details of the error, so this general message is disabled.
#if DEBUG
            message = ex.Message;
#else
            message = Errors.InternalServerError;
#endif
        }

        // For some reason the request.CreateErrorResponse() method ignores the message given to it and parses its own message.
        // The error response is constructed manually.
        return CreateErrorResponse(request, code, message);
    }

    private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, HttpStatusCode code, string message)
    {
        var content = new { Message = message };

        return new HttpResponseMessage(code)
        {
            ReasonPhrase = message,
            RequestMessage = request,
            Content = new ObjectContent(content.GetType(), content, new JsonMediaTypeFormatter())
        };
    }
}

Hope this just saved someone's day... ;)


Q: error: could not find or load main class First.class I have made program in java using netbeans. it is located in d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp. its name is First.java. it is running successfully and showing output in netbeans IDE. but when i m trying to run it through cmd its showing the above error.
PATH is set to c:\program files\java\jdk1.7.0_07\bin
classpath is set to .
i have also tried setting classpath to c:\program files\java\jdk1.7.0_07\bin but there was no change in the error..
javac First.java is running and CLASS file is getting created in the same folder where the program is.
please help me out.. i cannot debug it..

A: Most probably you are missing execution using package name.
You would be executing main class from src directory as :
D:\sudhanshu\documents\netbeansprojects\Firstapp\src> java firstapp.First

A: If your package is : somepackage,
And you have saved your .java file at: d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp
then in command prompt, go to the above directory and compile using: -
javac -d . First.java   // Don't use javac First.java

Then your class file will be created inside the folder somepackage inside the above path..
i.e. your class file will be at d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp\somepackage\First.class
Then you should go at the directory where your .java. file is saved, and run as: -
java First

From d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory..
If you want to run this class file from anywhere: -
Add d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory in your classpath..
Note: - You need to add the directory containing your package directory to classpath..

A: - If you are able to create a .class file then i think you have successfully installed your Java
Tip:
Always do a java -version on the command prompt, and if it returns with the version of JDK installed on your system, then you have successfully installed your Java.
- Now i will advice you to do this from the same directory where you class file is located to execute the file.
java First


Q: Character encoding for US Census Cartographic Boundary Files I'm trying to import the US Census cartographic boundary files (available here: http://www.census.gov/geo/www/cob/bdy_files.html ) into a GeoDjango application.  However, python is complaining about UnicodeDecodeErrors (for example, for the non-ascii characters in Puerto Rico).
The shapefile description file (*.dbf) doesn't specify what character encoding it uses; this is not defined by the spec for shapefiles.  What is the correct character encoding to use?

A: I was having the same issue with CBSA and Place data from 2010 Census full geometry shapes. These are not the clipped carto files.
IBM850 Did not work correctly for me. On a whim, I tried latin1 and it worked perfectly.

A: The US Census cartographic boundary files use the IBM850 character encoding.  Python code to properly encode these strings would be as follows:
unicode(featurestring.decode("IBM850"))


Q: Force Chromewebdriver to download text,jpg instead of opening in a new tab I have a need to download txt and jpg files that are basically links in a web page. I am using chrome webdriver to do the same. My code to set the chrome settings is as below:
 prefs = {
      :download => {:prompt_for_download => false,:default_directory => download_directory} ,
      :managed_default_content_settings => {:images => 2 },
      :webprefs =>  {:loads_images_automatically  => 'false' }
  }
  @browser = Watir::Browser.new :chrome , :prefs => prefs

When I click on these links, I the files opens in a new window instead of a download prompt. Is there a way to force chrome webdriver NOT to open these automatically?


Q: Ajax call fails in IE with requests from HTTPS to HTTP I'm making a trivial ajax CORS request from HTTPS to HTTP, and it's working fine on every browser, except IE. It's not even trying to make a request and fails immediately. There is no error messages in console.
This fails even without trying (there is no network traffic), then executed from secure site:
$.ajax({
    url:'http://foo.bar'
}).done(function() {
    alert('success');
}).fail(function() {
    alert('fail');
});

I'm using IE 10 in Standards Mode. Is there any way to make it work with HTTP? It's obvious it blocks unsecure request from secure site, but maybe it's possible to change this using browser settings?

A: Unfortunatelly there seems to be no solution for this.
Your best alternative option (for quick solution) is to implement HTTPS (directly or as a proxy for external HTTP-only service) using self-signed certificate and add it to exception list.


Q: Getting undefined when using "var" instead of "let" with Object.assign() var name = {
  nameValue: 'John'
};
console.log(name.nameValue);  // undefined
var surname = {
  surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // undefined

I am getting undefined when using var but everything is working good with let and
I am running this code on jsbin.com

A: Global scope (i.e. window in this case) already has a property name. You'll need to either create a new scope by wrapping your code with a function. Or use block scoped variable declaration let

console.log(typeof name); // string

var name = {
  nameValue: 'John'
};
console.log(name.nameValue); // undefined
var surname = {
  surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // undefined

function run() {
  var name = {
    nameValue: 'John'
  };
  console.log(name.nameValue); // John
  var surname = {
    surnameValue: 'Doe'
  };
  Object.assign(name, surname);
  console.log(name.surnameValue); // Doe
}

run();

A: Because 'name' is existed in window, you can use other name of variable
var name0 = {
  nameValue: 'John'
};
console.log(name0.nameValue);

A: (Window.)name is a specific value of the global window object that can be used (but pretty uncommon) for setting forms and hyperlinks targets.
The name property is not read only but is limited to the primitive type string. Therefore, any value that you assign to window.name will turn into a string.
This is essentially why you got undefined when used name.nameValue. name is not an object.
var name = { hello: "world!" };
console.log(name + ' - ' + name.hello); // "[object Object] - undefined"
var name = "Hello World!"
console.log(name); // "Hello World!";

A: You are setting the variable name in the global scope in window object. When you set the value of name in window object, its get method will call the toString method.
As specified in here
var name = {first:"Vignesh"};
console.log(name); //(1)
console.log(name.first); //(2)

(1) will give the value [object Object] as string instead of {first: "Vignesh"}.
(2) depicts that you are accessing an unassigned property of a string. i.e., [object Object].first which becomes undefined.
You have to declare the name object in some other scope like if...else block, function block to achieve what you need.


Q: No ads error from adcontrol I'm checking out ads in a Windows Phone app for the first time.
When I tried with the test settings, the test app showed up.
When I replace the info by the applicationID and AdUnitId from PubCenter,
nothing at all appeared (when debugging on a device).
I suscribed to the erroroccured event:
  private void AdControlInBorder_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
    {
        MessageBox.Show(e.Error.Message.ToString());
    }

And I get: "No ad available". This is about a second after the app started up.
Extra info: I'm in Belgium, checked it with the phone plugged to pc, unplugged,
I'm on wifi and I have internet available.

A: AdDUplex is just for promote your app not for gain money :) In your case, you can't have ads in debug mode. Send your app in beta test and look if ads is available. Pub center have the best fill rate in wp8  platform. But you need to choice your app usage. If you app is a type like rss flow or news you need ads because you will have a lot of users connected for a long time and frequently. If you app is a productivity app, you will add in app purchase or send your app like a paid app or donation. Don't forget if you add ads, the possibility to remove.


Q: ArcMap get coordinate system How can I get current coordinate system type from opened file?
I tried
 var coord = ESRI.ArcGIS.Geometry.esriSRProjCSType.... ???;
Can you tell me, what should I do?
UPD:
I need to save current map with all layers and geometry into a shapefile. That's why I have to get current coordinate system.

A: Assuming you have a reference to the feature class pFC:
    ERSI.ArcGIS.Geometry.ISpatialReference pSP = ((ESRI.ArcGIS.GeoDatabase.IGeoDataset)pFC).SpatialReference;
    coord=pSP.FactoryCode

coord now contains the code for the coordinate system. Note that not all projected coordinate systems are defined in esriSRProjCSType, there are more constants defined in esriSRProjCS2Type, esriSRProjCS3Type and esriSRProjCS4Type
However, a little more information in the question would maybe give a better answer.

A: You would do something like this:
dataset = "c:/data/landbase.gdb/Wetlands"
spatial_ref = arcpy.Describe(dataset).spatialReference

as per the ESRI help page here

A: Not sure by your question if you want the map spatial reference or a layer.  For a map you may use the IMap.SpatialReference Property.


Q: Infinispan file system store plus sql database I am trying to use infinispan to achieve the following:
-   n JVM instances in cluster
-   All data replicated between one node and the remaining nodes
-   Data to be backed up by the filesystem to that the node can recover from the local file store
-   I want some specific data to be persisted in the database (sql) asynchronously, but first to be written on the filesystem synchronously and once the transaction has been committed – then trigger the asynchronous persistence to the sql database
What is unclear from the documentation, it seems I will have to do everything myself – and infinispan just gives me jgroups clustering
It is unclear also how to remove data from the file store once the sql persistence successfully takes place – within an “atomic” transaction.
So data replication aside, I must be able to:

*

*Store data to the local cache (in-memory and file-system)

*Recover from the local cache (if the JVM crashes) and/or remote caches

*For some data, add to the cache, then FS, then asynchronously persist and remove from the FS

It seems that I can do all of this obviously, but Infinispan vs. me using jgroups and do it myself?

A: Infinispan allows you to chain cache stores together (by defining multiple stores within the persistence XML section), and each can be configured to either be synchronous or asynchronous (see here). However, transactional persistence stores are not supported (see here)


Q: Confused About Standard IPA I'm looking for standard IPA but every book, even dictionaries implement it differently.
for example [ɑ] and [ɑ:] or this symbol [ɛ] vs [e].
Some books omit the [i] sound which is the last sound of word happy, and some books say that this symbol equals [iː].
This also happens to [uː]. I know that colons like symbols are for length, but why is there so many differences? Even Wikipedia says:

Please note that several of these symbols are used in ways that are specific to Wikipedia and differ from those used by dictionaries.

https://en.wikipedia.org/wiki/Help:IPA_for_English
Where is the standard form that every text should obey?
And what's the role of these ones in the game? Bold ones.
[ɑ] AH
[ɜ] UR
[ɔ] AW

A: The range of sounds denoted by the symbols of the IPA are defined by the International Phonetic Association. Consider the T sound: it is pronounced differently in tick (aspirated as [tʰ]), stick (unaspirated as [t]), latter (flapped as [ɾ]), and pat (unreleased as [t̚]). The IPA is an International Phonetic Alphabet, which means it has different symbols for each sound.
However, this is not how you expect a pronunciation to be denoted in a dictionary, which traditionally use phonemic systems. Such systems represent all the different ways a phoneme can be pronounced with a single symbol. The International Phonetic Association does not define how IPA symbols should be used for representing phonemes, which is what you are asking for. Indeed, there is no universal system for representing English phonemes, and there is no institute or academy that regulates English to decree one, either.
As you have discovered, the result of this situation is that every organization that has needed a phonemic system for representing English has had to borrow someone else's system or invent their own. Though they generally overlap in much of their symbol choices, there is no universal standard for the representation of English phonemes.


Q: Transforming OLTP Relational Database to Data Warehousing Model What are the common design approaches taken in loading data from a typical Entity-Relationship OLTP database model into a Kimball star schema Data Warehouse/Marts model?

*

*Do you use a staging area to perform the transformation and then load into the warehouse?

*How do you link data between the warehouse and the OLTP database?

*Where/How do you manage the transformation process - in the database as sprocs, dts/ssis packages, or SQL from application code?

A: Personally, I tend to work as follows:

*

*Design the data warehouse first. In particular, design the tables that are needed as part of the DW, ignoring any staging tables.

*Design the ETL, using SSIS, but sometimes with SSIS calling stored procedures in the involved databases.

*If any staging tables are required as part of the ETL, fine, but at the same time make sure they get cleaned up. A staging table used only as part of a single series of ETL steps should be truncated after those steps are completed, with or without success.

*I have the SSIS packages refer to the OLTP database at least to pull data into the staging tables. Depending on the situation, they may process the OLTP tables directly into the data warehouse. All such queries are performed WITH(NOLOCK).

*Document, Document, Document. Make it clear what inputs are used by each package, and where the output goes. Make sure to document the criteria by which the input are selected (last 24 hours? since last success? new identity values? all rows?)

This has worked well for me, though I admit I haven't done many of these projects, nor any really large ones.

A: I'm currently working on a small/mid size dataware house. We're adopting some of the concepts that Kimball puts forward, i.e. the star scheme with fact and dimension tables. We structure it so that facts only join to dimensions (not fact to fact or dimension to dimension - but this is our choice, not saying it's the way it should be done), so we flatten all dimension joins to the fact table.
We use SSIS to move the data from the production DB -> source DB -> staging DB -> reporting DB (we probably could have have used less DBs, but that's the way it's fallen).
SSIS is really nice as it's lets you structure your data flows very logically. We use a combination of SSIS components and stored procs, where one nice feature of SSIS is the ability to provide SQL commands as a transform between a source/destination data-flow. This means we can call stored procs on every row if we want, which can be useful (albeit a bit slower).
We're also using a new SQL Server 2008 feature called change data capture (CDC) which allows you to audit all changes on a table (you can specify which columns you want to look at in those tables), so we use that on the production DB to tell what has changed so we can move just those records across to the source DB for processing.

A: I agree with the highly rated answer but thought I'd add the following:

* Do you use a staging area to perform the transformation and then

load into the warehouse?

It depends on the type of transformation whether it will require staging. Staging offers benefits of breaking the ETL into more manageable chunks, but also provides a working area that allows manipulations to take place on the data without affecting the warehouse. It can help to have (at least) some dimension lookups in a staging area which store the keys from the OLTP system and the key of the latest dim record, to use as a lookup when loading your fact records.
The transformation happens in the ETL process itself, but it may or may not require some staging to help it along the way.

* How do you link data between the warehouse and the OLTP database?

It is useful to load the business keys (or actual primary keys if available) into the data warehouse as a reference back to the OLTP system. Also, auditing in the DW process should record the lineage of each bit of data by recording the load process that has loaded it.

* Where/How do you manage the transformation process - in the

database as sprocs, dts/ssis packages,
  or SQL from application code?

This would typically be in SSIS packages, but often it is more performant to transform in the source query. Unfortunately this makes the source query quite complicated to understand and therefore maintain, so if performance is not an issue then transforming in the SSIS code is best. When you do this, this is another reason for having a staging area as then you can make more joins in the source query between different tables.

A: John Saunders' process explanation is a good.
If you are looking to implement a Datawarehouse project in SQL Server you will find all the information you require for the delivering the entire project within the excellent text "The Microsoft Data Warehouse Toolkit".
Funilly enough, one of the authors is Ralph Kimball :-)

A: You may want to take a look at Data Vault Modeling. It claims solving some loner term issues like changing attributes.


Q: Using Custom Font - Failed to decode downloaded font in Oracle Apex I'm trying to use some customized font in my application.
So i tried downloading Pacifico and trying to use in my application. But getting Failed to decode downloaded font and the font is not loading
Below is my CSS .
@font-face {
  font-family: 'MyWebFont';
  src:  url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

This is not working. So i tried converting this to .woff as per suggestions found in web and tried below. Even this is failing. I'm using Chrome 74.0 version . How to solve this?
@font-face {
  font-family: 'MyWebFont';
  src: url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf'),
       url('#WORKSPACE_IMAGES#Pacifico.woff')  format('woff'),
       url('#WORKSPACE_IMAGES#Pacifico.woff2')  format('woff2');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

A: Problem here is you need upload the font into /i/
@font-face {
      font-family: "Pacifico";
      src: url("http://localhost:8080/i/Pacifico.ttf");
    }

body {
    font-family: "Pacifico", serif;
    font-weight: 300 !important;
    line-height: 25px !important;
    font-size: 14px !important;
}

I don't know why Apex is not resolving the #WORKSPACE_IMAGES# but you can upload the font in the web server. In my case I'm using tomcat


Q: usort Date Assistance I am trying, unsuccessfully, to sort my list by one of my template fields ($fields[3]) which is a text input field with a date inside it. The problem is that because of the format of the date it will not sort correctly because I guess it is just comparing numbers.
I think I need to change the dateformat before sorting occurs but have so far failed to do this.
I am trying to use the usort function like so (field 3 is the one with the date in which is formatted like this dd/mm/yyyy),
if (!function_exists('do_sort')) {
    function do_sort($a, $b) {
        return $a->fields[3] > $b->fields[3];
    }}

$data = $params['data'];
usort($data, 'do_sort');
$smarty->assign('sorted', $data);

This sorts the data but as before, because I haven't changed anything, not in the correct order. Can anyone help me reformat the date prior to sorting?
Many thanks
Chris

A: Managed to do it. If anyone else is interested I used the following function:
   function date_compare($a, $b)
    {
        $t1 = strtotime($a->fields[3]);
        $t2 = strtotime($b->fields[3]);
        return $t1 - $t2;
    }
    $data = $params['data'];
    usort($data, 'date_compare');
    $smarty->assign('sorted', $data);

A: Try converting the strings to timestamps first:
function do_sort($a, $b) {
    $aval = strtotime($a);
    $bval = strtotime($b);
    if ($aval == $bval) {
        return 0;
    }
    return $aval < $bval ? -1 : 1;
}


Q: How to get and convert back user's birthdate to/from a NSTimeInterval? Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.
Again, how to convert back that NSTimeInterval to NSDate back?
I tried using different methods of NSDate but haven't succeed yet.
What I'm doing?
NSString *strdate = @"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(@"%.f", -[date timeIntervalSinceNow]);

This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.

A: NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];

Try the code below. date and anotherDate will be identical.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(@"%@", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(@"%@", anotherDate);

UPDATE:
It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:
NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.
Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.

A: This is just worked!
NSString *strdate = @"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(@"%@",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(@"%f", interval);
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(@"%@",date2);

Thanks to @sikhapol


Q: How do I retrieve disk information in C#? I would like to access information on the logical drives on my computer using C#. How should I accomplish this? Thanks!

A: If you want to get information for single/specific drive at your local machine. You can do it as follow using DriveInfo class:
//C Drive Path, this is useful when you are about to find a Drive root from a Location Path.
string path = "C:\\Windows";

//Find its root directory i.e "C:\\"
string rootDir = Directory.GetDirectoryRoot(path);

//Get all information of Drive i.e C
DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here e.g   DriveInfo("C:\\")

long availableFreeSpace = driveInfo.AvailableFreeSpace;
string driveFormat = driveInfo.DriveFormat;
string name = driveInfo.Name;
long totalSize = driveInfo.TotalSize;

A: For most information, you can use the DriveInfo class.
using System;
using System.IO;

class Info {
    public static void Main() {
        DriveInfo[] drives = DriveInfo.GetDrives();
        foreach (DriveInfo drive in drives) {
            //There are more attributes you can use.
            //Check the MSDN link for a complete example.
            Console.WriteLine(drive.Name);
            if (drive.IsReady) Console.WriteLine(drive.TotalSize);
        }
    }
}

A: What about mounted volumes, where you have no drive letter?
foreach( ManagementObject volume in
             new ManagementObjectSearcher("Select * from Win32_Volume" ).Get())
{
  if( volume["FreeSpace"] != null )
  {
    Console.WriteLine("{0} = {1} out of {2}",
                  volume["Name"],
                  ulong.Parse(volume["FreeSpace"].ToString()).ToString("#,##0"),
                  ulong.Parse(volume["Capacity"].ToString()).ToString("#,##0"));
  }
}

A: Use System.IO.DriveInfo class
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx

A: Check the DriveInfo Class and see if it contains all the info that you need.

A: In ASP .NET Core 3.1, if you want to get code that works both on windows and on linux, you can get your drives as follows:
var drives = DriveInfo
    .GetDrives()
    .Where(d => d.DriveType == DriveType.Fixed)
    .Where(d => d.IsReady)
    .ToArray();

If you don't apply both wheres, you are going to get many drives if you run the code in linux (e.g. "/dev", "/sys", "/etc/hosts", etc.).
This is specially useful when developing an app to work in a Linux Docker container.


Q: How to get the unique identifier of a metadata field? For example, the Profile has the field applicationVisibilities, which has the unique value inside application (see below). This identifies an application visibility. Another example: customPermissions has the unique value "name" per custom permission.
<applicationVisibilities>
  <!-- This --><application>standard__AllTabSet</application>
  <default>true</default>
  <visible>true</visible>
</applicationVisibilities>

Is it possible to get this information via API (pro grammatically)? I request Profile.applicationVisibilities and get application back?

A: It depends on what you want to get.
Here is the code to get list of Application Names for particular Profile
String profileName = 'System Administrator';
Profile p = [
        SELECT Id
        FROM Profile
        WHERE Name = :profileName
];

List<SetupEntityAccess> setupEntityAccesses = [
        SELECT Id, SetupEntityId
        FROM SetupEntityAccess
        WHERE Parent.ProfileId = :p.Id AND SetupEntityType = 'TabSet'
];

Set<Id> ids = new Set<Id>();
for (SetupEntityAccess setupEntityAccess : setupEntityAccesses) {
    ids.add(setupEntityAccess.SetupEntityId);
};

List<AppMenuItem> menuItems = [
        SELECT Id, Label
        FROM AppMenuItem
        WHERE ApplicationId IN :ids
];

List<String> applicationNames = new List<String>();

for (AppMenuItem appMenuItem : menuItems) {
    applicationNames.add(appMenuItem.Label);
}


Q: Nesting flexbox layout causes scrollable area to misbehave I've read various questions about scrolling within flexbox but I seem to have a slightly more complicated version of what I've seen.  I have an editor that uses flexbox and contains a toolbar with many components that is scrollable, and this works fine on its own.  However, on the live site it's wrapped in a parent which is display:flex (for reasons I won't go into but this editor isn't the only component on the page), and as soon as the editor is put within this flex parent its scrollable area becomes full width, pushing the whole page wider than it should be.
In this snippet, all the 'Thumb Example' elements are supposed to be scrollable within their parent .image-thumbs-container respecting the page's overall width:800px limit, but they lay out and push their parent wider than that.  But, if you turn off the display:flex of the .product-page element, the scrolling then works.  I built this simplified example of just the editor to demonstrate the problem, and it worked fine, took me a while to realise it was a parent element that was causing the error.
[Edit] This snippet may not work as expected within StackOverflow, please see this identical Pen: https://codepen.io/neekfenwick/pen/NWbpqZg

body {
    background-color: lightgrey;
}
.page-container {
    width: 800px;
    background-color: white;
}

.product-page {
    display: flex; /* Disable me to make scrolling work */
    flex-wrap: wrap;
}
.uploads-container {
    text-align: left;
    white-space: nowrap;
    padding: 5px;
    border: 1px solid black;
    display: flex;
    box-sizing: border-box;
}

.uploads-scroller {
    overflow-x: scroll;
    flex: 1 1 auto;
    overflow-y: hidden;
}
.image-thumbs-container {
    border: initial;
}
.image-thumb {
    display: inline-block;
    width: 100px;
    border: solid 2px grey;
    border-radius: 5px;
    margin-right: 2px;
    vertical-align: top;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="mock.css">
    <title>Mockup</title>

Page contains other content required to layout by flexbox.

File Upload
Widget Goes
Here

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Some complicated workspace content goes here.

Page contains other content required to layout by flexbox.

So, please bear in mind I don't want to alter anything above the .editor div.  A lot of our site relies on the .product-page CSS.  I can consider it, but, is it possible to fix this scrolling problem by only modifying elements from the .editor div and down?

A: You can fix this one by just setting 100% width on .editor.
Since the parent already has flex-wrap: wrap, this should work out just fine for you. The content below the editor will just wrap to below it.

.editor { /* <-- add this */
  width: 100%;
}

body {
    background-color: lightgrey;
}
.page-container {
    width: 800px;
    background-color: white;
}

.product-page {
    display: flex; /* Disable me to make scrolling work */
    flex-wrap: wrap;
}
.uploads-container {
    text-align: left;
    white-space: nowrap;
    padding: 5px;
    border: 1px solid black;
    display: flex;
    box-sizing: border-box;
}

.uploads-scroller {
    overflow-x: scroll;
    flex: 1 1 auto;
    overflow-y: hidden;
}
.image-thumbs-container {
    border: initial;
}
.image-thumb {
    display: inline-block;
    width: 100px;
    border: solid 2px grey;
    border-radius: 5px;
    margin-right: 2px;
    vertical-align: top;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="mock.css">
    <title>Mockup</title>

Page contains other content required to layout by flexbox.

File Upload
Widget Goes
Here

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Some complicated workspace content goes here.

Page contains other content required to layout by flexbox.

A: Add width: 100% to your .editor element.
Or, just in case you really needed to, add max-width: 800px to any of the following elements... .editor, .uploads-container, or .uploads-container


Q: How can I DRY out this Ruby Code How can I DRY out the following Ruby Code:
    x = 'a random string to be formated'
    x = x.split('^')[0] if x.include?('^')
    x = x.split('$')[0] if x.include?('$')
    x = x.split('*')[0] if x.include?('*')

I'm looking for the amazingly elegant ruby one liner but I'm having a hard time finding it.
It should probably be somewhat readable though.
Thanks

A: I think this might be what you're looking for

x.split(/\^|\$|\*/)

A: This works for me:
x = "a random string to be formatted"
['^', '$', '*'].each { |token|
  x = x.split(token)[0] if x.include?(token)
}

A: Based on the code you provided
x = 'a random string to be formated'

%w(^ $ *).each do |symbol|
  x = x.split(symbol)[0] if x.include?(symbol)
end

A: You're looking for this regex:
string.match(/^([^^$*]+)[$^*]?/).captures[0]

It returns all characters up the the first occasion of $, ^, or *, or the end of the string.


Q: Unable to login after modifying .profile I am a fairly new Ubuntu user. A few days ago I edited my ~/.profile and have spotted a syntax error in it. Now, when I try to log on, it sends me back to the 'greeting screen' after some errors. I do have a guest account, but no other accounts in the admin group. I've been searching for a solution, but found nothing that has worked so far. Here's what I have already tried:

*

*Launching root terminal from recovery mode in GRUB. When I tried to edit my .profile with nano/vi, it said that it was read-only.

*Launching dpkg from recovery mode. This gave me an error saying the mount was terminated with status 32.

*Booting into single user mode. This gave me the same error as no. 2; mount was terminated with status 32

*Logging in with virtual terminal. I pressed ctrl+alt+f2 in greeting screen and logged in, but there was a login loop here too; it would immediately ask for my login again after I logged in.

Any ideas?

A: When you log into recovery mode with grub, you'll have to remount / as readwrite, like:
mount -t ext4 /dev/sda1 / -o rw
you should look at the fstab
cat /etc/fstab
to see if you are supposed to use /dev/sdaX or /dev/sdbX or UUID or Device-by-id syntax.  where X is the partition of /.  After you do get in, I recommend creating a secondary account.  Make sure to add it to the additional group "wheel" or "root", but not as the main group.  Also, make sure you use visudo to add this user to the "sudoers".
Additionally, you can type
sudo passwd
to unlock your root account to prevent having to go through all this trouble again. Please do not log into your desktop as root.


Q: Is there a magic method that gets called when I write **object_identifier? Consider the use of the double-star notation in python:
instance = NotDictionary(name="", description="")
print( **instance )

Is there any way I can control the resulting value of the expression
**instance

In python?
What methods or what parent must my object have, in order to be treated as a 'expandable' dict in this instance?
For instance, in the same way I can control addition between two objects by the add and radd methods?


Q: error when defining function inside another function in fortran For some use I need to define a function inside another function inside a fortran module.
A sample code for easy comprehension is
module func
implicit none
contains

real function f(x,y)
real x,y,g

real function g(r)
real r
g=r
end function g

f=x*g(y)
end function f
end module func

use func
implicit none

write(*,*) f(1.0,1.0)
end

This is giving lots of errors in gfortran like unexpected data declaration, expected end function f, not g....etc.
What is the correct way of defining a function inside another function in fortran?

A: You use an internal subprogram, see below. Note internal subprograms themselves can not contain internal subprograms.
ian@eris:~/work/stack$ cat contained.f90
Module func

  Implicit None

Contains

  Real Function f(x,y)

    ! Interface explicit so don't need to declare g
    Real x,y

    f=x*g(y)

  Contains

    Real Function g(r)
      Real r
      g=r
    End Function g

  End Function f

End Module func

Program testit

  Use func

  Implicit None

  Write(*,*) f(1.0,1.0)

End Program testit
ian@eris:~/work/stack$ gfortran-8 -std=f2008 -Wall -Wextra -fcheck=all -O -g contained.f90
ian@eris:~/work/stack$ ./a.out
   1.00000000
ian@eris:~/work/stack$


Q: USB can not be mounted after formatting using `dd` I had formatted this usb using dd. After that the computer is not mounting the usb. It is being detected as lsusb shows

samiron@samiron-Vostro-3558:~$ lsusb
Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 002: ID 0781:558b SanDisk Corp.
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 004: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 002 Device 003: ID 8087:07dc Intel Corp.
Bus 002 Device 002: ID 064e:9209 Suyin Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

The command fdisk -l  gives:
samiron@samiron-Vostro-3558:~$ sudo fdisk -l
Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0xdbe79634

Device     Boot     Start        End    Sectors   Size Id Type
/dev/sda1  *         2046  449312767  449310722 214.3G  5 Extended
/dev/sda2       449312768 1953523711 1504210944 717.3G 83 Linux
/dev/sda5       432238592  449312767   17074176   8.1G 82 Linux swap / Solaris
/dev/sda6            2048  432238591  432236544 206.1G 83 Linux

Partition 1 does not start on physical sector boundary.
Partition table entries are not in disk order.

Disk /dev/sdb: 58.4 GiB, 62746787840 bytes, 122552320 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x7425bd9a

Device     Boot Start       End   Sectors  Size Id Type
/dev/sdb1        2048 122552319 122550272 58.4G 83 Linux

When I try to mount the following error shows:

samiron@samiron-Vostro-3558:~$ mount /dev/sdb1
mount: /dev/sdb1: can't find in /etc/fstab.

Any help to recover my usb will be appreciated

A: You need to provide a mount point:
mkdir /mnt/usb   ## Can be any directory
mount /dev/sdb1 /mnt/usb

You can setup a /etc/fstab entry to map your device to a mount point:
 /dev/sdb1   /mnt/usb                           ext4    defaults        1 2

With that entry you can use any of the following:
mount /dev/sdb1
mount /mnt/usb
mount -a   ## Mount everything in /etc/fsab


Q: connection oracle 11g with java 8 (eclipse) I can't import java.sql.*; because it said that this package is not accessible although I put ojdbc6 and also I tried ojdbc8 in the classpath but it isn't work;
[ I mention that I have oracle 11g and jdk 10 & eclipse 4 ]

A: How did you add your ojdbc driver ? A typical way is shown below:
First you need to right click your project and go for "Build Path" and go for "Configure build Path"

Then , in the "libraries" tab, click on the "Add External JARs" go to your ojdbc driver file to load it.

This is the typical way to load your ojdbc driver. Try first see whether it will help

A: If your IDE (Eclipse) gives error:
The package java.sql is not accessible

Or if compiling using javac gives error:
test\Test.java:3: error: package java.sql is not visible
import java.sql.*;
           ^
  (package java.sql is declared in module java.sql, but module Test does not read it)
1 error

Then it is because your Java 9+ project has a module-info.java file, i.e. your project is modular.
You need to add the following line to the module-info.java file:
    requires java.sql;


Q: UITableView Content Offset Increasing Unexpectedly I have a UITableView embedded in a navigation controller. When i segue from the TableView onto the next screen, i store the offset such that if i press the 'back' button, the offset on the original view remains the same, and it doesnt scroll up to the top.
var tableViewContentOffset = CGPointMake(0.0, 0.0)

override func viewWillAppear(animated: Bool) {
    super.viewDidAppear(animated)
    tableView.contentOffset = tableViewContentOffset
}

override func viewWillDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    tableViewContentOffset = tableView.contentOffset
}

This works perfectly when the view loads the first time, however each time i move onto the next screen and then return, the offset is increased by y(-64.0)
What is causing this?
First time loaded:

After Segueing and returning once:

A: You can set automaticallyAdjustScrollViewInsets to false.


Q: nginx not serving correct react build content I have a react app. When I build my app via the dev server (localhost: 3000), the app is served correctly with the correct styling etc.
However, when I serve via nginx (via docker) I get a completely different UI? Does anyone know why this may be?
I don't think it is a docker issue. I am using webpack if this is something that I may need to look at?
My nginx config:
server {
  listen    80 default_server;
  listen    [::]:80 default_server;

  root /usr/share/nginx/html;

  location = / {
    try_files $uri /index.html;
  }
}

Dockerfile:
FROM nginx:1.16-alpine
COPY nginx/default.conf /etc/nginx/conf.d/default.conf
COPY public/ /usr/share/nginx/html/

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]


Q: Azure Functions scaling and concurrency using Queue triggers and functionAppScaleLimit on the Consumption Plan I have an Azure Function app on the Linux Consumption Plan that has two queue triggers. Both queue triggers have the batchSize parameter set to 1 because they can both use about 500 MB of memory each and I don't want to exceed the 1.5GB memory limit, so they should only be allowed to pick up one message at a time.
If I want to allow both of these queue triggers to run concurrently, but don't want them to scale beyond that, is setting the functionAppScaleLimit to 2 enough to achieve that?
Edit: added new examples, thank you @Hury Shen for providing the framework for these examples
Please see @Hury Shen's answer below for more details. I've tested three queue trigger scenarios. All use the following legend:

QueueTrigger with no functionAppScaleLimit

QueueTrigger with functionAppScaleLimit set to 2

QueueTrigger with functionAppScaleLimit set to 1

For now, I think I'm going to stick with the last example, but in the future I think I can safely set my functionAppScaleLimit to 2 or 3 if I upgrade to the premium plan. I also am going to test two queue triggers that listen to different storage queues with a functionAppScaleLimit of 2, but I suspect the safest thing for me to do is to create separate Azure Function apps for each queue trigger in that scenario.
Edit 2: add examples for two queue triggers within one function app
Here are the results when using two queue triggers within one Azure Function that are listening on two different storage queues. This is the legend for both queue triggers:

Both queue triggers running concurrently with functionAppScaleLimit set to 2

Both queue triggers running concurrently with functionAppScaleLimit set to 1

In the example where two queue triggers are running concurrently with functionAppScaleLimit set to 2 it looks like the scale limit is not working. Can someone from Microsoft please explain? There is no warning in the official documentation (https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#limit-scale-out) that this setting is in preview mode, yet we can clearly see that the Azure Function is scaling out to 4 instances when the limit is set to 2. In the following example, it looks like the limit is being respected, but the functionality is not what I want and we still see the waiting that is present in @Hury Shen's answer.
Conclusion
To limit concurrency and control scaling in Azure Functions with queue triggers, you must limit your Azure Function to use one queue trigger per function app and use the batchSize and functionAppScaleLimit settings. You will encounter race conditions and waiting that may lead to timeouts if you use more than one queue trigger.

A: Yes, you just need to set functionAppScaleLimit to 2. But there are some mechanisms about consumption plan you need to know. I test it in my side with batchSize as 1 and set functionAppScaleLimit to 2(I set WEBSITE_MAX_DYNAMIC_APPLICATION_SCALE_OUT as 2 in "Application settings" of function app instead of set functionAppScaleLimit, they are same). And I test with the code below:
import logging
import azure.functions as func
import time

def main(msg: func.QueueMessage) -> None:
    logging.info('=========sleep start')
    time.sleep(30)
    logging.info('=========sleep end')
    logging.info('Python queue trigger function processed a queue item: %s',
                 msg.get_body().decode('utf-8'))

Then I add message to the queue, I sent 10 messages: 111, 222, 333, 444, 555, 666, 777, 888, 999, 000, I sent them one by one. The function was triggered success and after a few minutes, we can see the logs in "Monitor". Click one of the log in "Monitor", we can see the logs show as:

I use 4 red boxes on the right of the screenshot above, I named each of the four logs as "s1", "s2", "s3", "s4"(step 1-4). And summarize the logs in excel for your reference:

I make cells from "s2" to "s4" as yellow because this period of time refer to the execution time of the function task.
According the screenshot of excel, we can infer the following points:
1. The maximum number of instances can only be extended to 2 because we can find it doesn't exist more than two yellow cells in each line of the excel table. So the function can not scale beyond 2 instances as you mentioned in your question.
2. You want  to allow both of these queue triggers to run concurrently, it can be implemented. But the instances will be scale out by mechanism of consumption. In simple terms, when one function instance be triggered by one message and hasn't completed the task, and now another message come in, it can not ensure another instance be used. The second message might be waiting on the first instance. We can not control whether another instance is enabled or not.
===============================Update==============================
As I'm not so clear about your description, I'm not sure how many storage queues you want to listen to and how many function apps and QueueTrigger functions you created in your side. I summarize my test result as below for your reference:
1. For your question about would the Maximum Burst you described on the premium plan behave differently than this ? I think if we choose premium plan, the instances will also be scale out with same mechanism of consumption plan.
2. If you have two storage queues need to be listen to, of course we should create two QueueTrigger functions to listen to each storage queue.
3. If you just have one storage queue need to be listen to, I test with three cases(I set max scale instances as 2 in all of three cases):
A) Create one QueueTrigger function in one function app to listen to one storage queue. This is what I test in my original answer, the excel table shows us the instances will scale out by mechanism of consumption plan and we can not control it.
B) Create two QueueTrigger functions in one function app to listen to same storage queue. The result is almost same with case A, we can not control how many instances be used to deal with the messages.
C) Create two function apps and create a QueueTrigger function in each of function app to listen to same storage queue. The result also similar to case A and B, the difference is the max instances can be scaled to 4 because I created two function apps(both of them can scale to 2 instances).
So in a word, I think all of the three cases are similar. Although we choose case 3, create two function apps with one QueueTrigger function in each of them. We also can not make sure the second message be deal with immediately, it still may be processed to first instance and wait for frist instance complete deal with the first message.
So the answer for your current question in this post is setting the functionAppScaleLimit to 2 enough to achieve that? is: If you want both of instances be enabled to run concurrently, we can't make sure of it. If you just want two instances to deal with the messages, the answer is yes.


Q: Lambda referencing itself Suppose I have a global function pointer like so:
void (*Callback)(My_special_t*);

If I want to assign it a lambda I do so like so:
Callback = [](My_special_t* instance) {
   //Useful stuff
};

What I really would like to do is something like this:
Callback = [](My_special_t* instance) {
   //Useful stuff
   Callback = /* Somehow get the current lambda? */
};

So my question is this:
Is it possible to reference the a lambda object from inside of itself.....and if so how?

A: I know lambda is very cool feature and because its coolness it is overused.
Trying forcing lambda here is creating a problem.
Just define a function and problem is resolved.
void myNiceFunction(My_special_t *instance) {
    instance->doStuff();

    … … …

    if (instance->next) {
        myNiceFunction(instance->next);
    }
}

It is better since it is self documenting (if good name is provided) and it is testable (test can reach this function directly).

A: You can do it with std::function, like this:
#include <functional>
#include <iostream>

using std::cout;
using std::function;

struct My_special_t
{
};

int main()
{
  function<void(My_special_t*)> Callback;

  auto otherCallback = [](My_special_t* instance)
  {
    cout << "otherCallback " << static_cast<void*>(instance) << "\n";
  };

  Callback = [&Callback, &otherCallback](My_special_t* instance)
  {
    cout << "first callback " << static_cast<void*>(instance) << "\n";
    Callback = otherCallback;
  };

  My_special_t special;
  Callback(&special);
  Callback(&special);
}


Q: Installing JSON::XS on Mac OSX I hope you're all ready for a long adventure through my frustration:
I'm using Perl 5.10, on Mac OSX : Snow Leopard, with XCode 3.2.6.
What I am trying to do is use the module JSON::XS in a program.
This is the first time that I've ever done something with Perl, so I look up some simple example programs and try them out, and they all work. Then I go to use JSON::XS. I get:
Can't locate JSON/XS.pm in @INC (@INC contains: /Library/Perl/Updates/5.10.0 /System/Library/Perl/5.10.0/darwin-thread-multi-2level /System/Library/Perl/5.10.0 /Library/Perl/5.10.0/darwin-thread-multi-2level /Library/Perl/5.10.0 /Network/Library/Perl/5.10.0/darwin-thread-multi-2level /Network/Library/Perl/5.10.0 /Network/Library/Perl /System/Library/Perl/Extras/5.10.0/darwin-thread-multi-2level /System/Library/Perl/Extras/5.10.0 .) at part1.pl line 5.
BEGIN failed--compilation aborted at part1.pl line 5.

I do some Googling, and figure that it needs to be installed. Also in my Googling I find heavy recommendations to use cpanm. So I try installing cpanm first using cpan (which I already have).
I get a very long printout, that basically says NO, NOT OK, "chances to succeed are limited", and FAILED over and over and over again. It's too long to include in its entirety, but the bits I found interesting are:
Warning (usually harmless): 'YAML' not installed, will not store persistent state
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible
Could not read '/Users/danielgierl/.cpan/build/ExtUtils-ParseXS-3.15-VSmBrZ/META.yml'. Falling back to other methods to determine prerequisites

I look into installing YAMl, because sections of output like the above (which I got repeatedly) make me think that's the problem. Essentially it also failed, and among other reasons it gave me warnings like the above.
Another section of the output says:
make: *** No rule to make target `/System/Library/Perl/5.10.0/darwin-thread-multi-2level/CORE/config.h', needed by `Makefile'.  Stop.

I look this up online, and though I understand why it says what it does, I see no way that I could fix this, since these are Makefiles gotten from cpan or elsewhere.
Another section:
Running install for module 'version'
Running make for J/JP/JPEACOCK/version-0.9901.tar.gz
Has already been unwrapped into directory /Users/danielgierl/.cpan/build/version-0.9901-U8IMPt
Could not make: Unknown error
Warning (usually harmless): 'YAML' not installed, will not store persistent state
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible

In general lots of unknown errors. I am also trouble by the section where it tells me:
Testing if you have a C compiler
ld: library not found for -lbundle1.o
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/1C/1CnzBuv+F5y+8M5YPm6I4k+++TI/-Tmp-//ccTWRqov.out (No such file or directory)
error building /var/folders/1C/1CnzBuv+F5y+8M5YPm6I4k+++TI/-Tmp-/compilet.bundle from /var/folders/1C/1CnzBuv+F5y+8M5YPm6I4k+++TI/-Tmp-/compilet.o at /System/Library/Perl/5.10.0/ExtUtils/CBuilder/Base.pm line 213.

I cannot determine if you have a C compiler
so I will install a perl-only implementation

You can force installation of the XS version with

perl Makefile.PL --xs

I know for a fact that I have a c compiler, since gcc -v tells me that it is version 4.2.1. On the plus side, it does tell me that my kit looks good (whatever that is). If I try running the command they recommend me, I get told that there is no such file or directory.
After some more Googling, I keep seeing XCode re-re-referenced for Mac users. I already had a version of XCode, but because it might have problems, I uninstall it, then get version 3.2.6 (my OS is too old for the newer versions). The install fails for unknown reasons, and it tells me to contact the software company. However, before it fails, it does install the UNIX tools, including gcc (which I later got the latest version for), so I don't think that's the problem.
All in all, this has consumed some 6 hours of my time today, and I'm stressed and physically ill (though I was this morning before starting this futile venture, but it's been exacerbated), and I have no idea where I am supposed to go next.
I'm hoping that it's all been some stupid error that'll be remedied in 10 seconds by an experienced user, but I fear the worst. In general I've done every bit of advice I've found, from running with --sudo to sacrificing a goat to the sun gods. I'd appreciate any help.

A: You are best off leaving the system's perl alone. Instead, use perlbrew to install your own perls.
You can install cpanm without using cpan using
curl -L http://cpanmin.us | perl - App::cpanminus
for your local perl.
In addition, you might have to install the command line tools for XCode.
If you can't, you may want to look into installing build tools from MacPorts and putting those in your path ahead of the system paths, but after your local perl because you don't necessarily want to mess with a perl that MacPorts might install either.


Q: Does Netsh.exe command overwrite existing firewall rules? I'm using a netsh command that add a firewall rule on windows 2012 r2 server.
My command is like this:
Netsh.exe advfirewall firewall add rule name="name" protocol="TCP" localport=1234 dir=in enable=yes action=allow

What happen if i already have a rule with another name and same localport and protocol?
My command will overwrite that rule or it will create another one on same port?
I've tried to find any documentation, but i've found nothing about that.

A: There is a PowerShell module called NetSecurity.
You can make a statement in powershell which can tell if the rule already exist or not.
Get-NetFirewallRule you can use this command to discover which firewall rules are already defined.
https://learn.microsoft.com/en-us/powershell/module/netsecurity/?view=win10-ps


Q: How to deploy a multi-page react application in IIS server? I have created a multipage application using reactjs and have manage the routing using react router-dom. I tested it using npm start and it is working fine. The pages are properly redirecting. But when I run "npm run build" and add it to IIs server, only the home page is coming. No matter what link I click on, I am getting redirected to the home page.
I tried modifying the web.config file.
`
<?xml version="1.0"?>
<configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="React Routes" stopProcessing="true">
 <match url=".*" />
 <conditions logicalGrouping="MatchAll">
 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
 <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
 </conditions>
 <action type="Rewrite" url="/index.html" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer>
</configuration>

`
But it seems the index.html is not updated with the rest of the pages other than the homepage. My user routes are `
<BrowserRouter>

                <Routes>
                  <Route exact path="/" element={<HomepageAtm />} />
                  <Route
                    exact
                    path="/New-Registration"
                    element={<RegistrationAtm />}
                  />
                  <Route exact path="/View" element={<VIEW_ATM />} />
                  <Route exact path="/List_View" element={<LIST_VIEW />} />
                  <Route exact path="/Airport_View" element={<AIRPORT_VIEW />} />
                  <Route exact path="/Map_View" element={<MAP_VIEW />} />
                  <Route exact path="/History_Data" element={<History_Data />} />
                  <Route exact path="/ContactUs" element={<Contact />} />
                  <Route exact path="/Terminalarea_View" element={<TERMINALAREA_VIEW />} />
                </Routes>

          </BrowserRouter>

`
I also tried using HashRouter but the results were same. Except for the home page, no other pages are loading.


Q: Appending or merging consecutive line segments (contours) as one single line of same elevation value? Is there a way using python (ArcPy) or ArcGIS 10.1 tools to collect consecutive line segments having the same elevation value and appending/merging/generating one single line from them?
Each resulting line will have the same elevation value as the original segments.

A: If you are familiar with python scripts, I wrote the following code for this exact problem I was having last month.  You can create a script tool in ArcToolbox to execute the script.  When Dissolve or Unsplit line tools have numerous records, it tends to bog down and crash.  I'm guessing this is because "This tool will use a tiling process to handle very large datasets for better performance and scalability. For more details, see Geoprocessing with large datasets."  Whatever ESRI says, it does not improve performance.  I ran this on multiple shapefiles with over 400,000 total records.  The dissolve tool ran for over 72 hrs and still did not finish.  My script took less than 10 minutes.
Essentially, the tool breaks your elevation contours into shapefiles of the same value (i.e. 15 shapefiles for elevations 1ft - 15ft if your contours are 1 ft contours like mine).  It also compensates for negative values (I have sites near the coast).  The shapes are then merged, dissolved, and multipart to singlepart breaks separate lines into individual records.  You can modify the dissolve_fields variable and field name throughout the code (I've marked the locations) to cater to your needs.  I hope it helps.
# Contour_Merge_And_Dissolve.py

# Import modules
import arcpy
from arcpy import env

# Define functions
def min_max(featureClass, fieldName):
    listItems = []
    rows = arcpy.SearchCursor(featureClass)
    for row in rows:
        listItems.append(row.getValue(fieldName))
    del rows
    listItems.sort()
    listMin = listItems[0]
    listMax = listItems[-1]
    return listMin, listMax

# Arguments
contourList = arcpy.GetParameterAsText(0) #input shapefiles, ElevationContours
outFolder = arcpy.GetParameterAsText(1) #output folder

# set workspace and overwrite option
arcpy.env.workspace = outFolder
arcpy.env.overwriteOutput = True
arcpy.env.outputZFlag = "Disabled"
arcpy.env.outputMFlag = "Disabled"

# local variables
dissolveFields = ["ELEV_FT"] # change field name here

# Process: Merge
arcpy.AddMessage("Merging contours...")
arcpy.Merge_management(contourList, "contour_merge.shp")

# Get Min/Max values of ELEV_FT field
ft_min, ft_max = min_max("contour_merge.shp", "ELEV_FT") # change field name here
ft_range = ft_max - ft_min

arcpy.AddMessage("ELEV_FT MIN: " + str(ft_min))
arcpy.AddMessage("ELEV_FT MAX: " + str(ft_max))

# Set progressor
arcpy.SetProgressor("step", "Breaking apart contours...", 0, ft_range, 1)
arcpy.AddMessage("Breaking apart contours...")

# Break apart and dissolve for each ELEV_FT value
mergeList = []
counter = ft_min
while counter <= ft_max:
    arcpy.SetProgressorLabel("Breaking out " + str(counter) + "ft contours...")
    arcpy.AddMessage("Attempting " + str(counter) + "ft contours...")
    counter_str = str(counter)
    counter_str = counter_str.replace("-", "neg")
    thisLyr = "elev_" + counter_str + "_lyr"
    thisDis = "elev_" + counter_str + "_dissolve.shp"
    where_clause = '"ELEV_FT" = ' + str(counter) # change field name here
    # Make Layer
    arcpy.management.MakeFeatureLayer("contour_merge.shp", thisLyr)
    # Select by attributes
    arcpy.SelectLayerByAttribute_management(thisLyr, "NEW_SELECTION", where_clause)
    # Dissolve Layer to new shape
    arcpy.Dissolve_management(thisLyr, thisDis, dissolveFields, "", "SINGLE_PART", "DISSOLVE_LINES")
    # Add to mergeList
    mergeList.append(thisDis)
    counter += 1
    arcpy.SetProgressorPosition()

arcpy.ResetProgressor()

# Merge contours
arcpy.AddMessage("Merging dissolved layers...")
arcpy.Merge_management(mergeList, "contour_dissolve.shp")

# Multipart to singlepart
arcpy.AddMessage("Converting multipart to singlepart...")
arcpy.MultipartToSinglepart_management("contour_dissolve.shp", "contour_singlepart.shp")

# Clean up
for shape in mergeList:
    arcpy.Delete_management(shape)

A: Dissolve based on the elevation, with the multi_part parameter set to "SINGLE_PART".
Or you could dissolve normally and then Explode multi-part features.


Q: How to get nearest location based on user location from array of lat, long: react, leaflet I have a react app that shows bike stations. I want to display nearest stations on dashboard. Is there any easier way to do that with react ?

A: You can loop through all markers and look which has the shortest distance. map.distance(USER_LATLNG, BIKE_STATION_LATLNG)


Q: how to write to .txt file in UWP vb.net i am trying to have a .txt file containing a single line with a number on it. i need this txt file to be editable by the program and to be installed with it.
the .txt file will be completely overwritten when the number needs to be replaced.
how can i do this? all other tutorials refer to C# or JS I need vb.NET

A: Read this Create, write, and read a file topic about interaction with file in UWP.
To write string to StorageFile use FileIO.WriteTextAsync or FileIO.AppendTextAsync functions
Dim file As StorageFile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting)
Dim strData As String = "sample text to write"
Await FileIO.WriteTextAsync(file, strData)


Q: How to get distinct dates (yyyy-mm-dd) using AutoFixture I have a test case where I need 4 distinct dates to build my objects.
Everything I found seem to tell that AutoFixture always generate unique elements but the thing is when it generates dates, it does so considering everything down to ticks. The result is that when I do .ToShortDateString() on the result, I may end up with duplicated results.
I know I could loop until I get only distinct values but it doesn't feel right.
For now, what I have is:
string[] dates;
do
{
  dates = _fixture.CreateMany<DateTime>(4).Select(d => d.ToShortDateString()).ToArray();
} while (dates.Distinct().Count() != 4);

A: As mentioned by @MarkSeeman in this post about numbers

Currently, AutoFixture endeavours to create unique numbers, but it doesn't guarantee it. For instance, you can exhaust the range, which is most likely to happen for byte values [...]
If it's important for a test case that numbers are unique, I would recommend making this explicit in the test case itself. You can combine Generator with Distinct for this

So for this specific situation, I now use
string[] dates = new Generator<DateTime>(_fixture)
                     .Select(x => x.ToShortDateString())
                     .Distinct()
                     .Take(4).ToArray();

A: You can generate unique integers (lets say days) and then add it to some min date:
var minDate = _fixture.Create<DateTime>().Date;
var dates = _fixture.CreateMany<int>(4).Select(i => minDate.AddDays(i)).ToArray();

But I'm not sure that AutoFixture guarantees that all generated values will be unique (see this issue for example)