text:
Q: Change background color based on property I want to cheange the color of the background of a ListItem based on some property of the current member of the cursor. I'm using SimpleCursorAdapter to bind the values of the database to the ListView. What I did is to create a color selector like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_dark" />
    <item android:state_activated="true" android:state_selected="true" android:drawable="@android:color/holo_blue_dark" />
    <item android:state_selected="true" android:drawable="@color/rosa" />
    <item android:drawable="@android:color/transparent" />
</selector>

My layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/listitem_color" >
    ...
    ...

And the I have a view binder where I do the following:
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.listitem, cur, cols, to,0);
mAdapter.setViewBinder(new ViewBinder() {
    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if (columnIndex == 6) {
            boolean dudoso = cursor.getInt(columnIndex) == 1;
            TextView textView = (TextView) view;
            textView.setText(dudoso ? "dudoso" : null);
            if(dudoso)
            {
                LinearLayout ll=((LinearLayout)textView.getParent().getParent());
                ll.setSelected(true);
            }
            return true;
        }
        return false;
    }
});

But it's not working. What is the correct way to do what I want?

A: Perhaps a better way would be to write your own class that inherits from the SimpleCursorAdapter. Something like that:
public class BubbleListAdapter extends SimpleCursorAdapter {

private LayoutInflater mLayoutInflater;
/** list holding statuses determining if an item is checked/unchecked. */
protected List<Boolean> mItemsCheckedStatus;
/** Cursor. */
private Cursor cursor;
/** reference to ArdoiseDatabaseAdapter. */
private MyDatabaseAdapter mMyDatabaseAdapter;
/** application context. */
private Context context;
/** references to Users. */
private Users mUsers;

/**
 * View holder for color item.
 */
private static class ViewHolder {
    /** bubble text. */
    TextView buubleText;
    /** user name. */
    TextView userName;
}

public BubbleListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
    super(context, layout, cursor, from, to);
    this.cursor = cursor;
    mLayoutInflater = LayoutInflater.from(context);
    mMyDatabaseAdapter = MyDatabaseAdapter.getInstance();
    this.context = context;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view = mLayoutInflater.inflate(R.layout.bubble_list_item, null);
    final ViewHolder holder = new ViewHolder();
    holder.buubleText = (TextView) view.findViewById(R.id.bubble_list_text);
    holder.userName = (TextView) view.findViewById(R.id.bubble_list_user_name);
    view.setTag(holder);
    return view;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    Cursor c = getCursor();
    final ViewHolder holder;
    if (view != null) {
        holder = (ViewHolder) view.getTag();
        holder.buubleText.setText(c.getString(c.getColumnIndex(BubblesTableMetaData.BUBBLE_TEXT)));
        if (mUsers != null) {
            switch (c.getInt(c.getColumnIndex(BubblesTableMetaData.USER_ID))) {
            case MyConstans.COLOR_RED:
                holder.buubleText.setBackgroundResource(R.drawable.bubble_red_edit);
                holder.userName.setTextColor(context.getResources().getColor(R.color.bubble_red));
                holder.userName.setText(mUsers.getUser1());
                break;
            case MyConstans.COLOR_BLUE:
                holder.buubleText.setBackgroundResource(R.drawable.bubble_blue_edit);
                holder.userName.setTextColor(context.getResources().getColor(R.color.bubble_blue));
                holder.userName.setText(mUsers.getUser2());
                break;
            case MyConstans.COLOR_GREEN:
                holder.buubleText.setBackgroundResource(R.drawable.bubble_green_edit);
                holder.userName.setTextColor(context.getResources().getColor(R.color.bubble_green));
                holder.userName.setText(mUsers.getUser3());
                break;
            case MyConstans.COLOR_VIOLET:
                holder.buubleText.setBackgroundResource(R.drawable.bubble_violet_edit);
                holder.userName.setTextColor(context.getResources().getColor(R.color.bubble_violet));
                holder.userName.setText(mUsers.getUser4());
                break;
            default:
                break;
            }
        }
        view.setTag(holder);
    }
}

@Override
public Object getItem(int position) {
    Bubble bubble = null;
    if (cursor != null) {
        int index = 0;
        if (cursor.moveToFirst()) {
            do {
                if (index == position) {
                    bubble = mArdoiseDatabaseAdapter.mapBubble(context, cursor);
                }
                index++;
            } while (cursor.moveToNext());
            return bubble;
        }
    }
    return bubble;
}

/**
 * Get users.
 *
 * @return the mUsers
 */
public Users getmUsers() {
    return mUsers;
}

/**
 * Set users.
 *
 * @param mUsers
 *            the mUsers to set
 */
public void setmUsers(Users mUsers) {
    this.mUsers = mUsers;
}

@Override
public int getCount() {
    return cursor.getCount();
}
}

I hope that helped.

A: no need to take selector .... just write down "setBackgroundColor(Color.Blue)" to ur Layout via programming.....   `
if(columnIndex == 6)
{
   layout.setBackgroundColor(Color.Blue)
}

here is my selector xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/vhclistrowbackground" />
    <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@color/text_tab_unselected" />

    <!-- Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@color/text_tab_selected" />
    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@color/text_tab_unselected" />

    <!-- Pressed -->
    <item android:state_pressed="true" android:drawable="@color/text_tab_unselected" />
</selector>

A: I am not quite sure, but you could try:
    if (columnIndex == 6) {
        boolean dudoso = cursor.getInt(columnIndex) == 1;
        TextView textView = (TextView) view;
        textView.setText(dudoso ? "dudoso" : null);
        if(dudoso)
        {
            v.setSelected(true);

        }
        return true;
    }


text:
Q: Extensions to the standard environment, what is out there? \NewDocumentEnvironment from the xparse package allows accessing environment arguments also in the code that is supposed to go after the content.
environ and newenviron allow referring to the environment body by macro.
What other extensions of the standard environment are out there and what are they good for?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run sentiment So, that I can get result for every file separately I am working on Sentiment Analysis. I have 542 text files and have to get sentiment scores for each of the files separately But in 1 Loop. How can I add for loop that prints results separately?
Here is the code:
path = 'C:/Users/Hamza/OneDrive/Desktop/talha.R/Project 5/text.files'
setwd(path)
getwd()

fileslist = list.files(pattern = ",*.txt")

datalist = lapply(fileslist, function(x) readLines(x))

datafr = do.call("rbind", datalist)

view(datalist[1])

filename <- datalist
filename <- trimws(filename)

filetext <- glue(read_file(filename))
filetext <- gsub("\\$", "", filetext)

tokens <- tibble(text = filetext) %>% unnest_tokens(word, text)
tokens %>%
  inner_join(get_sentiments("loughran")) %>%
  count(sentiment) %>%
  spread(sentiment, n, fill = 0) %>%
  mutate(sentiment = positive - negative)

This is the sample of the result:

I want this same output for 542 files. Thanks in advance.


text:
Q: Confirm event completion whilst invoking REST API in an outlook JS add-in I am building a JS add-in that simply forwards a message with the added comment 'STOP' to a defined address upon clicking a button in the ribbon. In order to forward I call the REST API with a POST request.
When adding event.completed() at the end of the function, with (event) as parameter, the getCallbackTokenAsync does not run at all.
Instead, without it, the add-in forwards the message properly but the info bar does not disapear and the script keeps running on a loop:
Info bar to signal that script is running: https://i.stack.imgur.com/zGa2K.png
Any ideas on how I should properly handle the event.completed() when calling the REST API?

// the function sendAsStops is called directly from the manifest file
function sendAsStops(event) {
  console.log("Initialising STOP command.");
  var restHost = Office.context.mailbox.restUrl;
  var itemId = getItemRestId();
  console.log(itemId);
  Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
      console.log('Sending email...');
     var accessToken = result.value;
      console.log(result);
      var getMessageUrl = restHost + '/v2.0/me/messages/' + itemId + '/forward';
        $.ajax({
          url: getMessageUrl,
          type: 'post',
          headers: { 'Authorization': 'Bearer ' + accessToken },
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify({
            'Comment': 'STOP',
            'ToRecipients': [{'EmailAddress': { 'Address': 'name@address.com' }}],
          })
         }).done(function() {
           console.log("Stop successfully forwarded.");
         }).fail(function(error) {
           console.log("Failed to send");
        });
    } else {
      console.log("Unable to proceed. Ref: " + result.status);
      return false;
    }
  });
  event.completed();
}

function getItemRestId() {
  console.log("Getting item ID...");
  if (Office.context.mailbox.diagnostics.hostName === 'OutlookIOS') {
    console.log("ID ready to use.");
    return Office.context.mailbox.item.itemId;
  } else {
    console.log('Converting ID...');
    return Office.context.mailbox.convertToRestId(
      Office.context.mailbox.item.itemId,
      Office.MailboxEnums.RestVersion.v2_0
    );
  }
}

A: event.completed() must be called at the end of the execution of your add-in. Calling event.completed() is terminating your add-in, so any asynchronous calls (such as getCallbackTokenAsync callback in this case) gets automatically terminated and cleaned up. Hence, you do not see the add-in forwarding the message.
Call event.completed() after your entire add-in execution is complete. Something like:
       $.ajax({
          url: getMessageUrl,
          type: 'post',
          headers: { 'Authorization': 'Bearer ' + accessToken },
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify({
            'Comment': 'STOP',
            'ToRecipients': [{'EmailAddress': { 'Address': 'name@address.com' }}],
          })
         }).done(function() {
           console.log("Stop successfully forwarded.");
           event.completed();
         }).fail(function(error) {
           console.log("Failed to send");
           event.completed();
        });


text:
Q: Converting finalBufferData into img url to display I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
                        "/upload/v" + version + "/" + publicID + "." + format + "/n");

it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
 public class JsonTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("resources");

            StringBuffer finalBufferData = new StringBuffer();

            for(int i=0; i<parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);

                String publicID = finalObject.getString("public_id");
                String version = finalObject.getString("version");
                String format = finalObject.getString("format");
                finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
                        "/upload/v" + version + "/" + publicID + "." + format);

            }
            return finalBufferData.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();

            }
            try {
                if (reader != null) {
                    reader.close();

                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);

        //imagesList.setText(result);
    }

}

}

A: found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {

    @Override
    protected List<upImgModels> doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("resources");

            List<upImgModels> upImgList = new ArrayList<>();

            for(int i=0; i<parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);

                upImgModels upImgModels = new upImgModels();
                upImgModels.setPublic_id(finalObject.getString("public_id"));
                upImgModels.setVersion(finalObject.getString("version"));
                upImgModels.setFormat(finalObject.getString("format"));

                upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
                        + "/upload/v" + finalObject.getString("version") + "/"
                        + finalObject.getString("public_id") + "." +
                        finalObject.getString("format"));

                upImgList.add(upImgModels);
            }
            return upImgList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();

            }
            try {
                if (reader != null) {
                    reader.close();

                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<upImgModels> result) {
        super.onPostExecute(result);
        upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
        listViewUpload.setAdapter(adapter);
        //imagesList.setText(result);
    }

}

public class upImgAdapter extends ArrayAdapter{

    public List<upImgModels> upImgModelsList;
    private int resource;
    private LayoutInflater inflater;
    public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
        super(context, resource, objects);
        upImgModelsList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = inflater.inflate(R.layout.row, null);
        }

        ImageView imageViewDisplay;
        imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);

        ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);

        return convertView;
    }
}

}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.


text:
Q: Explanation about multiple su I'm a bit confused when a multiple su happen. Lets say a situation like this happen:
Fikrie su to root :

ps -ef | grep su:

root       15524  15388  0  10:15  pts/0  00:00:00 su root

I know that the pid for that su is 15524 and the parent pid is 15388. But when a multiple su happen. eg : this situation.
Fikrie su root:
root su fikrie2:
fikrie 2 su root:

ps -ef | grep su:

root       15450  15388  0  10:15  pts/0  00:00:00 su root
fikrie2    15468  15458  0  10:15  pts/0  00:00:00 su fikrie2
root       15478  15476  0  10:15  pts/0  00:00:00 su root

I thought that when root su into fikrie2, the first pid will be the ppid for the second su. Somehow when I tried to grep the process, this confuses me. The ppid became 15458 instead of 15450 or 15388. None of the ppid are connected/related to the ppid or pid before it. I tried to google and read about process relationship in Advanced Programming in the UNIX Environment book. Can someone give me a good explanation about this or maybe a link to help me understand more on the process relationship.
I'm trying to write a code to find the user that su into that user. From all the answer I look into SO, they only help to find the original user, eg. fikrie. If the second situation happen, I wasn't able to get fikrie2 when I su to root from fikrie2. Instead I get fikrie which is the original user. My original idea was to use the parent id to get the user, but when doing it from command line. This really confuse me.
PS* I'm trying this on Unix platform. I do not know anything about Windows, but if the ppid and pid are different between Windows and Unix, please point me the direction into Unix.

A: I'm not sure, but I suspect that the parent process that you are seeing is the shell which got called.  When you su you will run the .profile which will call multiple other processes and will end with a shell being launched.  So the parent process isn't going to be the previous invocation of su, because that isn't the process which spawned this one.  The shell did that.


text:
Q: how to use the type FLOAT8 [] with NPGSQL / Postgres I have this in my schema:
f_gain_factor_notional        FLOAT8       NOT NULL,
f_profits                     FLOAT8 []    NOT NULL,
f_fees                        FLOAT8 []    NOT NULL,

How can I write to the FLOAT8 [] type using npgsql?
There doesn't seem to be a built-in type Sql.doubleArray or any equivalent. I see Sql.stringArray, Sql.intArray, etc.
How can this be handled?

Edit: these are the types available

Edit: here is some code:
            let queryInsert =
                $"
                -- insert row
                ... skipped for brevity
                ",
                [[

                    "@f_gain_factor_notional",          Sql.double (float results.FixedResults.GainFactorNotional)
                    "@f_profits",                       Sql.stringArray (results.FixedResults.Profits |> List.map string |> List.toArray)
                    "@f_fees",                          Sql.stringArray (results.FixedResults.Fees    |> List.map string |> List.toArray)
                    "@f_margin",                        Sql.stringArray (results.FixedResults.Margin  |> List.map string |> List.toArray)
                    "@f_relative_drawdown",             Sql.double (float results.FixedResults.RelativeDrawdown)
                    "@f_absolute_drawdown",             Sql.double (float results.FixedResults.AbsoluteDrawdown)
                    "@f_realized_profit",
...

This is F# code, but the issue is identical with C#:
I've to cast the dotnet types to npgsql type.
So, for a string, I can do:
Sql.string "yo"

for a string array, I can do:
Sql.stringArray [| "hello"; "world |]

for a double array, I... can't do, since Sql.doubleArray doesn't exist. Sql.intArray exists, but no double/float/decimal.

A: Npgsql maps regular .NET arrays to PostgreSQL array types, so you should be able to simply use .NET double[] to map PG float8[].


text:
Q: How to force the project to use a specific assembly, in C#? Suppose I have a class library with some conditional compilation, that eventually gets built to MyPortable.dll and MyPortable.X.dll, where the latter is the version compiled with the conditional enabled.
Then I have my "Core" project which references "MyPortable.dll". So far so good.
However, my problem lies in the third project (the "App"), which has a reference to "Core", but needs to use "MyPortable.X.dll" (which is a different build that "Core" uses), but because "Core" is linked against to "MyPortable.dll", my "App" ends using that same version as well, instead of "MyPortable.X.dll".
Is there any way to do that? The code is something like this:
MyPortable
namespace MyPortable
{
    public class Person {
        public string Name { get; set; }
    }

    public class Something {
        public List<Person> GetPersons() {
            List<Person> l = new List<Person>();
            l.Add(new Person { Name = "Name 1" });

#if PLATFORM_X
            l.Add(new Person { Name = "Name 2" });
#endif

            return l;
        }
    }
}

I first compile MyPortable without "PLATFORM_X" enabled, and then I compile again, this time with the flag turned ON. File references are below (note that I am referencing Core.csproj directly):
Core\References\MyPortable.dll
App\
    \References\Core.csproj
    \References\MyPortable.X.dll

A: If I understand you correctly then yes. You edit your project file to include conditional MSBUILD statements for the references/run times you need in which ever version.
I had a simillar answer here : Visual Studio loading the right (x86 or x64) dll!
Thought that in particular used the Build Platform/Target as the variable. I assume that you're using different Targets for setting the compilation conditions?

A: You can control assembly binding from the config file, although I'm not sure that this is exactly what you are looking for.
Essentially you can tell your application to bind to a specific assembly:
<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="myAssembly"
                              publicKeyToken="32ab4ba45e0a69a1"
                              culture="neutral" />
            <bindingRedirect oldVersion="1.0.0.0"
                             newVersion="2.0.0.0"/>
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>

I took the above example from the MSDN documentation located here:
http://msdn.microsoft.com/en-us/library/2fc472t2.aspx
Hope that helps,
Chris


text:
Q: Prove $f(x) = x^{2}\cos(1/x)$ is differentiable How would I prove that the function
$f: \Bbb R \to \Bbb R$, where $f(x) = \begin{cases} x^2\cos(1/x)   & x \neq 0 \\ 0 & x=0 \end{cases}$
is differentiable?
So far I have tried using the product rule, but gotten stuck with differentiating $\cos(1/x)$ from the definition of differentiation.

A: Only point of concern is with $x=0$:
$$\lim_{x\to 0}\dfrac{f(x)-f(0)}{x-0}=\lim_{x\to 0}\dfrac{x^2\cos{\frac{1}{x}}}{x}=\lim_{x\to 0}\left(x\cos{\dfrac{1}{x}}\right).$$
Now as $\cos{\dfrac{1}{x}}$ is bounded in a neighborhood of the origin (besides $0$) we have $x\cos{\dfrac{1}{x}} \to 0$ as $x\to 0$


text:
Q: How to pass data from component to a controller in angular I have a scenario like i have dialog which have a controller and inside the dialog i have component and component template have inputs box and select box etc on change of this inputs i want to pass data to dialog controller.
Please suggest how can i achieve that.Thanks

<md-dialog flex="30">
  <form name="newContactForm" novalidate layout="column" flex="auto">
    <md-toolbar style="min-height:48px;max-height:48px;" class="md-light md-primary">

{{ContactsDialogCtrl.title}}

        <md-divider class="vertical-divider" style="background-color: #788395;min-height: 48px;"></md-divider>
        <md-button type="submit" class="md-icon-button" ng-click="createaccountDialogCtrl.createNewContactFn(newContactForm.$valid,newContactForm)">
          <md-icon flex class="icon-custom-position material-icons">save</md-icon>
          <md-tooltip>Save Contact</md-tooltip>
        </md-button>
        <md-divider class="vertical-divider" style="background-color: #788395;min-height: 48px;"></md-divider>
        <md-button class="md-icon-button" ng-click="createaccountDialogCtrl.close()">
          <md-icon class="material-icons">close</md-icon>
        </md-button>

    </md-toolbar>
    <md-dialog-content style="padding:20px; overflow-y:auto;height:78vh;" class="overflow-h" layout="row">

      <createaccount-Componentfor-Bidding account-Details="createaccountDialogCtrl.setaccountParameter(event)"></createaccount-Componentfor-Bidding>
    </md-dialog-content>
    </form>
</md-dialog>

(function() {
    'use strict';

    angular
        .module('webapp')
        .controller('createaccountDialogController', createaccountDialogController);

    /** @ngInject */
    function createaccountDialogController($mdDialog) {
     var vm = this;
     vm.state = '';
        vm.close = close;
        vm.setaccountParameter = setaccountParameter;

     console.log('inside createaccountDialogController');
     //console.log($state.current.name);
        //getAllbidinformation();

        function close() {
            console.log('close');
            $mdDialog.hide();
        };

        function setaccountParameter(obj)
        {
            console.log(obj);
            console.log('inside setaccountParameter');
        }
    }
})();


text:
Q: Finding angles in three dimensions Suppose there is a line making an angle $\theta$ with $z$ axis in three dimensions. Then what will be the angles of that line with $x$ and $y$ axes?

A: You have not provided enough information to answer your question — unless the angle $\theta$ happens to be zero.  The set of all lines making some angle $\theta$ with the $z$ axis is a cone centered around the $z$ axis.  Different lines making up that cone have different angles with the $x$ and $y$ axes, ranging from $\pi/2 - \theta$ to $\pi/2 + \theta$ (or in degrees, from $90^\circ - \theta$ to $90^\circ + \theta$).
This is true quite generally — not just for angles relative to the axes or just for Cartesian coordinates, but for any angle with respect to any other line and in any coordinate system.  There are infinitely many different lines that could have some particular angle relative to any given line, so depending on which of those different lines happens to be your one line, there could be many different answers.


text:
Q: Time Series with a for loop I have this equity model that generates independent 225 values of S. But i want to make it such that S[i+1] is calculated from the previous S[i] value. I have made a mess of the code, please help.
St <- 10
r <- 0.15
sigma <- 0.1
z <- rnorm(225)
h <- seq(0,1,by=1/225)
t <- h[-1]

S <- numeric(225)
for (i in 1:225){
S <- St * exp( (r - 0.5 * (sigma^2)) * t + sigma * z * sqrt(t) )
S[i+1] <- S[i]* exp( (r - 0.5 * (sigma^2)) * t[i+1] + sigma * z * sqrt(t[i+1]))
}

S


text:
Q: Laravel: Get 405 Method Not Allowed while posting data using jquery ajax api to store data I am trying to save data to a database using jQuery ajax api in Laravel 4.* and receive a 405 error.
View
{{Form::open(array("","id"=>"frmProcessLevel"))}}
   <input name="{{$result->id.'_'.str_replace(' ','-',$title)}}" id="processLevel">

{{$title}} Impact rating

               Level
               Category
               Description

           @foreach($impact_rating as $key => $value)

                    {{$key}}
                    {{$impact_cat[$key]}}
                    {{$value}}

           @endforeach

   {{Form::token()}}
   {{Form::submit('Save')}}
{{Form::close()}}

Routes
Route::post('/bia/create_critical_process',array('before' => 'csrf','uses'=>'BiaController@createBiaStepThree'));

Controller
 public function createBiaStepThree(){
        $data = Input::all();
        $last_insert_bia_id = Session::get('last_insert_bia_id');
        if (Request::ajex())
        {
            Log::info(Input::all());
            $bia = new CriticalProcessStepThree();
            $bia->impact_rating_clinical = $data['selectedLevel'];
            $bia->key_process_fk = 1;
            $bia->bia_entry_fk = $last_insert_bia_id;
            $bia->save();
        }
    }

Passing token: http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/

A: In your controller you have a typo.
It should be
if(Request::ajax())

instead of
Request::ajex()

Not sure if this is your only problem, but that is one of them.
EDIT : also you should set your request type.
type    :"POST",

Also make sure your route is setup to accept post requests like.
Route::post('route/what/ever/you/want', 'Controller@function');

A: Example in AJAX.
var formData = new FormData();
            formData.append("password", password.val());
        $.ajax({
             url: 'btn',
             method: 'post',
             processData: false,
             contentType: false,
             cache: false,
             dataType: 'json',
             data: formData,
             success: function(data){
                    var vote_now = $("#vote_now");
                    if(data.btn == 'visible'){
                        vote_now.fadeIn();

                    }
                    else {

                        vote_now.fadeOut();
                    }

                    },
                error: function(){

             }
        });


text:
Q: Edit text columns I have a text file (the first two lines are character spacings):

         1         2         3         4         5         6         7         8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
ATOM      1  N1  SPINA   3      30.616  29.799  14.979  1.00 20.00      S    N
ATOM      2  N1  SPINA   3      28.146  28.381  13.950  1.00 20.00      S    N
ATOM      3  N1  SPINA   3      27.605  28.239  14.037  1.00 20.00      S    N
ATOM      4  N1  SPINA   3      30.333  29.182  15.464  1.00 20.00      S    N
ATOM      5  N1  SPINA   3      29.608  29.434  14.333  1.00 20.00      S    N
ATOM      6  N1  SPINA   3      29.303  29.830  13.317  1.00 20.00      S    N
ATOM      7  N1  SPINA   3      28.963  31.116  13.472  1.00 20.00      S    N
ATOM      8  N1  SPINA   3      28.859  28.743  13.828  1.00 20.00      S    N
ATOM      9  N1  SPINA   3      29.699  30.575  14.564  1.00 20.00      S    N
ATOM     10  N1  SPINA   3      29.518  29.194  15.301  1.00 20.00      S    N

I want to edit it and make it like:

         1         2         3         4         5         6         7         8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
ATOM      1 N001 SPINA   3      30.616  29.799  14.979  1.00 20.00      S    N
ATOM      2 N002 SPINA   3      28.146  28.381  13.950  1.00 20.00      S    N
ATOM      3 N003 SPINA   3      27.605  28.239  14.037  1.00 20.00      S    N
ATOM      4 N004 SPINA   3      30.333  29.182  15.464  1.00 20.00      S    N
ATOM      5 N005 SPINA   3      29.608  29.434  14.333  1.00 20.00      S    N
ATOM      6 N006 SPINA   3      29.303  29.830  13.317  1.00 20.00      S    N
ATOM      7 N007 SPINA   3      28.963  31.116  13.472  1.00 20.00      S    N
ATOM      8 N008 SPINA   3      28.859  28.743  13.828  1.00 20.00      S    N
ATOM      9 N009 SPINA   3      29.699  30.575  14.564  1.00 20.00      S    N
ATOM     10 N010 SPINA   3      29.518  29.194  15.301  1.00 20.00      S    N

The number of spaces between each column are important and the list of atoms needs to go up to 190 (N001-N190). Thus I would like to replace characters 13-16 (" N1 ") in file 1 with ("N001") and keep the remainder of the file in the original spacing.

A: You don't need 10 long lines of sample input to demonstrate the problem or the solution:
$ cat file
ATOM      1  N1  SPINA   3
ATOM      2  N1  SPINA   3
ATOM     10  N1  SPINA   3

$ awk '{print substr($0,1,12) sprintf("N%03d",$2) substr($0,17)}' file
ATOM      1 N001 SPINA   3
ATOM      2 N002 SPINA   3
ATOM     10 N010 SPINA   3

I'm assuming we could use $2 as the numeric part of the 3rd field. It seems to increment sequentially with your line numbers. Using NR might be an alternative. If neither of those is actually what you want, post some more representative sample input/output.
Also, note that any solution that involves assigning to a field (e.g. $3=...) WILL cause awk to recompile the line using the value of OFS as the field separator and so will change your spacing.
Oh, and if those 2 initial lines of character spacings are really present in your files, this is the tweak:
$ cat file
         1         2
12345678901234567890123456
ATOM      1  N1  SPINA   3
ATOM      2  N1  SPINA   3
ATOM     10  N1  SPINA   3

$ awk 'NR>2{$0 = substr($0,1,12) sprintf("N%03d",$2) substr($0,17)} 1' file
         1         2
12345678901234567890123456
ATOM      1 N001 SPINA   3
ATOM      2 N002 SPINA   3
ATOM     10 N010 SPINA   3

A: Try :
$ awk '{$3=substr($3,1,1) sprintf("%03d",$2)}1' OFS=\\t file

Note : OFS will be tab
If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk
--edit--
if you want to increment with line
$ awk '{$3=substr($3,1,1) sprintf("%03d",NR)}1' OFS=\\t file

A: Here is yet another way:
awk 'sub(/.$/,sprintf("%03d",NR),$3)' OFS='\t' file

Output:
$ awk 'sub(/.$/,sprintf("%03d",NR),$3)' OFS='\t' file
ATOM    1       N001    SPINA   3       30.616  29.799  14.979  1.00    20.00   S       N
ATOM    2       N002    SPINA   3       28.146  28.381  13.950  1.00    20.00   S       N
ATOM    3       N003    SPINA   3       27.605  28.239  14.037  1.00    20.00   S       N
ATOM    4       N004    SPINA   3       30.333  29.182  15.464  1.00    20.00   S       N
ATOM    5       N005    SPINA   3       29.608  29.434  14.333  1.00    20.00   S       N
ATOM    6       N006    SPINA   3       29.303  29.830  13.317  1.00    20.00   S       N
ATOM    7       N007    SPINA   3       28.963  31.116  13.472  1.00    20.00   S       N
ATOM    8       N008    SPINA   3       28.859  28.743  13.828  1.00    20.00   S       N
ATOM    9       N009    SPINA   3       29.699  30.575  14.564  1.00    20.00   S       N
ATOM    10      N010    SPINA   3       29.518  29.194  15.301  1.00    20.00   S       N

A: If you are interesting to resolve it with pure shell, here is the code:
while IFS="\n" read -r line
do
  n=${line:9:3}
  printf "%sN%03d%s\n" "${line:0:12}" $n "${line:16}"
done < file

A: awk '$3="N"sprintf("%03d",$2)' OFS='\t' infile.txt

Result

ATOM    1       N001    SPINA   3       30.616  29.799  14.979  1.00    20.00SN
ATOM    2       N002    SPINA   3       28.146  28.381  13.950  1.00    20.00SN
ATOM    3       N003    SPINA   3       27.605  28.239  14.037  1.00    20.00SN
ATOM    4       N004    SPINA   3       30.333  29.182  15.464  1.00    20.00SN
ATOM    5       N005    SPINA   3       29.608  29.434  14.333  1.00    20.00SN
ATOM    6       N006    SPINA   3       29.303  29.830  13.317  1.00    20.00SN
ATOM    7       N007    SPINA   3       28.963  31.116  13.472  1.00    20.00SN
ATOM    8       N008    SPINA   3       28.859  28.743  13.828  1.00    20.00SN
ATOM    9       N009    SPINA   3       29.699  30.575  14.564  1.00    20.00SN
ATOM    10      N010    SPINA   3       29.518  29.194  15.301  1.00    20.00SN


text:
Q: Monodb with nodejs - query with group after count result I have the following collection which represents a swipe record when a member goes to the gym.
{
    "_id" : ObjectId(""),
    "content" : {
        "Date_Key" : "",
        "TRANSACTION_EVENT_KEY" : "",
        "SITE_NAME" : "",
        "Swipe_DateTime" : "",
        "Gender" : "",
        "Post_Out_Code" : "",
        "Year_Of_Birth" : "",
        "Time_Key" : "",
        "MemberID_Hash" : "",
        "Member_Key_Hash" : "",
        "Swipes" : ""
    },
    "collection" : "observations"
}

I want to return the number of members for every number of gym swipes in a given month.
For example:
{
   {"nrOfGymSwipes": 0, "nrOfMembers": 10}, // 10 members who swiped 0 times
   {"nrOfGymSwipes": 1, "nrOfMembers": 15}, // 15 members who swiped once
   {"nrOfGymSwipes": 2, "nrOfMembers": 17},
   ...
}

I have tried the following:
collection
            .aggregate(
            [{$match: {"content.Swipe_DateTime": {$regex:"201602"}}},
            {$group: {_id: "$content.MemberID_Hash", "nrOfGymSwipes":{$sum: 1}}},
            {$sort: {"nrOfGymSwipes": 1}}],

which returns for each member the number of swipes in the given month.
.........
    { _id: '111', nrOfGymSwipes: 16 },
    { _id: '112', nrOfGymSwipes: 16 },
    { _id: '113', nrOfGymSwipes: 17 },
...............

Now I was thinking of doing a group by the number of gym swipes and count the ids, have tried this but it doesn't return what i expected
collection
            .aggregate(
            [{$match: {"content.Swipe_DateTime": {$regex:"201602"}}},
            {$group: {_id: "$content.MemberID_Hash", "nrOfGymSwipes":{$sum: 1}}},
            {$group: {_id: "nrOfGymSwipes", "nrOfMembers":{$sum: 1}}}, <---added this
            {$sort: {"nrOfGymSwipes": 1}}],

Any idea how i can solve this?
Also, is there a way to change the way i get the json output? for example instead of showing  _id: "32131" part, output nrOfMembers: "312321"

A: You were almost there with your final group, you only needed to prefix your _id key with $ to indicate the number of swipes field. The $sort pipeline is where another problem is because the field you are trying to sort on does not exist. The aggregate pipeline works on the premise that results from a stage in the pipeline are passed on to the next as modified documents (with their own structure depending on the aggregate operation) and the last group pipeline only produces two fields, "_id" and "nrOfMembers".
You can use the $project pipeline step in order for the $sort stage to work since it creates the "nrOfGymSwipes" field for you by replacing the previous _id key and you can then get the final output in the desired structure. So you final aggregate operation should be:
collection.aggregate([
    { "$match": { "content.Swipe_DateTime": { "$regex":"201602" } } },
    { "$group": { "_id": "$content.MemberID_Hash", "nrOfGymSwipes": { "$sum": 1 } } },
    { "$group": { "_id": "$nrOfGymSwipes", "nrOfMembers": { "$sum": 1 } } },
    { "$project": { "_id": 0, "nrOfGymSwipes": "$_id", "nrOfMembers": 1 } },
    { "$sort": { "nrOfGymSwipes": 1 } }
], function (err, result) { ... });


text:
Q: $X $~ $exp (0.5)$ and $Y$ ~ $exp (1)$. How can I calculate such probability? $X$ ~ $exp (0.5)$ and $Y$ ~ $exp (1)$.
X is the waiting time for the bus and Y is the waiting time for the taxi. Meaning half a bus is expected to arrive every 1 hour and 1 taxi is expected to arrive every 1 hour.
It is know that in $\frac{1}{3}$ of the days I take the taxi and in $\frac{2}{3}$ I take the bus. What is the probability that in a random day I took the bus, if it is known that I waited less than $1.2$ hours overall?
I first calculated $P(X < 1.2)$ but now I am not sure how to continue. How can I calculate the probability that.overall I waited less than $1.2$ hours? If I have that then I think I can get the solution

A: I think you are on the right track: the probability $P(X<Y|\min\{X,Y\}<1.2)$ is sought.
Set $A=\{\min\{X,Y\}<1.2\}$. By independence,
$$P(A)=P(X<1.2,Y<1.2)=P(X<1.2)P(Y<1.2).$$
Further, by the Law of Total Probability (disintegration),
$$P(\{X<Y\}\cap A)=\int_0^{1.2} P(X<y,X<1.2)dF_Y(y)=\int_0^{1.2} P(X<y)dF_Y(y),
$$
where $F_Y(y)$ is the c.d.f. of $Y$. At this point, explicit calculation of $$P(X<Y|A)=\frac{P(\{X<Y\}\cap A)}{P(A)}$$ is readily available.


text:
Q: Finding number of solutions to an equation in $\mathbb F_p$ $p=3 \pmod 4$ is a prime. Let $b\in \mathbb F_p^*$.
Show that the equation $v^2=u^4-4b$ has $p-1$ solutions $(u,v)$ with $u, v \in \mathbb F_p$.
If we write the given equation as $v+u^2=x$ and $v-u^2=-4by$ where $y$ is the inverse of $x$ in $\mathbb F_p^*$ and solve, we get $u^2=-\frac {4b+x^2} {2x}$. So, I need to check when this quantity $-\frac {4b+x^2} {2x}$ will be a perfect square in $\mathbb F_p$. Can anyone please help me with this?

A: Let us introduce a "new" variable $w=u^2$. Shiva's idea shows that there are $p-1$ pairs $(v,w)$ such that $v^2=w^2-4b$ - one for each non-zero value of $x$.
The claim follows from the fact that $\gcd(p-1,4)=2$. A consequence of this is that the set of fourth powers in $\mathbb{F}_p$ is exactly the same as the set of squares (the group is cyclic!). Furthermore, both functions $f(x)=x^2$ and $g(x)=x^4$ are 2-1. This follows either by a counting argument or from the observation that $f$ and $g$ are both endomorphisms of $\mathbb{F}_p^*$ with kernel $\{\pm1\}$. So the number of solutions of $v^2=w^2-4b$ equals the number of solutions of $v^2=u^4-4b$, and the former we know to be equal to $p-1$.

An alternative way of seeing the same thing (every square is a fourth power) is by Little Fermat. If $w$ is non-zero, then
$$
w^2=w^2\cdot1=w^2\cdot w^{p-1}=w^{p+1}=(w^{(p+1)/4})^4.
$$
Here $p\equiv 3\pmod4$ implies that $(p+1)/4$ is an integer.


text:
Q: Origin of "darkest Brooklyn" I'm wondering about the origin of the phrase "darkest Brooklyn".
I imagine it is meant to suggest unexplored wilderness and perhaps also primitive social conditions. I've found a citation from the late 19th century:
[George B. Buzelle], The Third Annual Report of the Brooklyn Bureau of Charities… presented May 1, 1884. District Conference of Wards 3 and 10, Secretary's Report, (Brooklyn: Tremlett & Co., 1884), p. 21.

The end of another year finds us returning with our reports from Darker Brooklyn; not darkest Brooklyn; that region few of us have explored.

That makes it sound as though the author is nodding to "darkest Brooklyn" as an established phrase. It certainly predates the books In Darkest Africa (1890) and In Darkest England and the Way Out (1890).
How old is this expression, actually, and what associations of Brooklyn are being referred to?

Edit, 19:30 EDT: Contrary to some of the comments, this phrase is attested well before the 1970s:

*

*Library of Congress possesses a 1958 work, "Through Darkest Brooklyn," by Gerson Lieber. http://www.loc.gov/pictures/item/2003668972/

*Truman Capote (1946): "As you see, I have changed addresses, have moved to a little lost mews in darkest Brooklyn... for various reasons...". Too Brief a Treat: The Letters of Truman Capote, ed. Gerald Clarke, (New York: Vintage International, 2004), p. 39.

*James Huneker (1920): "adjacent to all the cemeteries and frog ponds of Darkest Brooklyn", letter to Alice Wade Mulbern, Dec. 12, 1920, Letters of James Gibbons Huneker, ed. Josephine Huneker, (New York: Charles Scribner's Sons, 1920), p. 308.

*New York Times (1911): "Contrary to Eastern conceptions, he said, the only cowboys and Indians to be seen in the West nowadays are found in Eastern magazines shipped in trainloads out there; while Western gamblers make their habitat onIy on Broadway and take their money exclusively from 'citizens of Harlem and darkest Brooklyn.'" Article "WEST EXULTS OVER EAST. Gerrit Fort, Railway Man, Tells of Marvelously Superlative Attractions." June 01, 1911, p. 7.

*New York Times (1908): "Sir Oliver seems to have told the Ruskinians nothing definite about the Myers messages. Instead he discussed the relation between the psychical and the physical, and his remarks must have had all the Intellectual vigor that marks the utterances old Uncle Peleg or Little Bright Eyes at a materializing séance in Darkest Brooklyn." Article "TOPICS OF THE TIMES. More Science from Sir Oliver." February 7, 1908, p. 6.

*Brooklyn Daily Eagle (1901): "In that particular settlement the bath tub is a prime neighborhood attraction, and benighted visitors from darkest Brooklyn and Jersey City are escorted proudly to the settlement and given an opportunity to enjoy the tub as the greatest luxury of belonging to a woman's club in the city." Article "Hopeful Side of the 'East Side'." May 17, 1901, p. 4.

*Brooklyn Daily Eagle (1896): "In the center of 'Darkest' New York and 'Darkest' Brooklyn is the home in which the sun never shines." Article "Christ in the Tenements." Jan. 13, 1896, p. 9

A: The Corpus of Contemporary American English has only one entry in its database that uses the phrase "darkest Brooklyn" -- an article in the Spring 1998 issue of American Scholar by Alfred Kazin titled "The art city our fathers built."

I first walked into the Metropolitan Museum seventy-one years ago, as
a boy of eleven, led by my father, an immigrant house painter from
darkest Brooklyn who liked his firstborn to accompany him as he timidly looked into the city's public places -- the Met, the Brooklyn
Museum, the great library on Fifth Avenue, the Aquarium on the
Battery, the Staten Island ferry when it charged a nickel. [American Scholar, Spring98, Vol. 67 Issue 2, p17, 10p]

Kazin seems to be using darkest Brooklyn in the sense of Brooklyn's innermost ethnic core, where the gentry dare not tread.

A: The archives of The Brooklyn Daily Eagle are searchable online.
The string "darkest Brooklyn" can be found several times but it does not appear to be a stock phrase. Contrary to your suspicion I don't believe your writer is referring to a established place.
Later occurrences appear to be a play on "Darkest Africa" as you suggested.

A: The expression "darkest Brooklyn" does not appear to be a  very  common one.  Ngram shows usages only from the late '70s.
In a   recent book (2015) Social Imaginaries they mention the concept of "deepest, darkest Brooklyn" as related to the hippie communes  of the '60s.

*

*... the new, cool, worlds of design and worlds of entrepreneurship work, and we have a map, in a sense. That's not the mechanism of producing the map, they aren't imaginary, necessarily, it's the map. I loved in that article—somebody quoted in it introduces the notion of "Deep Brooklyn" (laughter) "Deepest, darkest Brooklyn. Well you know, we also saw this in the '60s with the rise of the communes of the hippie culture.

My impression is that the concept may have been used trough the years in a generic sense, referring to the less known and possibly most dangerous parts of Brooklyn. Darkest in this context conveys the idea of something "unknown and dangerous".

A: Does it strike anyone else as odd that the expression is

Darker Brooklyn; not darkest Brooklyn;

(emphases mine)? I'd like to suggest that "darkest Brooklyn" is, as JOSH suggests, the common use of the superlative, which the OED attests to be of long standing, for example in locutions like darkest dungeon. It's the comparative adjective that intrigues me. In 1900, Wards 3 and 10 straddled Bergen St in the northwest of Brooklyn. I have no reason to believe that the boundaries were much changed from 1890, when Brooklyn wasn't yet part of New York City. A little rummaging around on the intertubes finds that an earlier census records that Ward 3 was 40% black and Ward 10 was almost all white. The Draft Riots of 1863 (really race riots) drove most of the black population out of Manhattan. Brooklyn became a refuge for those black New Yorkers, possibly changing the racial makeup of Ward 10.
One ward to the east of Ward 3 stood an important black church, the Bridge Street African Wesleyan Methodist Episcopal Church (established 1854). One ward to the southwest of Ward 10, was Ward 12, described in the Annual Report as having "a swarming population of mixed races".
None of the designations Negro, African, or black appear in the Annual Report, and I don't plan to spend more time investigating the demographics of 1890 Brooklyn, but I'd like to suggest that the capitalized "Darker Brooklyn" is a racial reference.


text:
Q: Zend Framework - fetchAll returns fatal error when it has no rows returned? I know that when I try top use fetchAll and it returns a fatal error, the reason is because it has returned no records on the query. But my question is, how to treat it? How can I know if the query will not return any records, so i do not use toArray()?
For instance,
$table = new Application_Model_Proucts();
$products = $table->fetchAll()->toArray();

How can I do a verification of the query before I put the toArray method?

A: If there are no records returned from fetchAll() then you are passing nothing to toArray(), which is where the error is occurring.
Try wrapping the last but of your code in an if statement:
$products = $table->fetchAll();

if(count($products))
{
  $products = $products->toArray();
}

A: wrap your query in a condition and/or throw a new exception when condition isn't met


text:
Q: Creating overlayMaps by querying Carto dataset using geoJson I am trying to create an overlayMap by querying a Carto dataset using geoJson.
So far I have:
    var baseMaps = {
        "OSM B&W" : OpenStreetMap_BlackAndWhite,
        "Toner" : Stamen_Toner,
        "Relief Map": Stamen_TopOSMRelief,
        "Satellite Imagery": Esri_WorldImagery
    };

    var geojsonFeature = "http://sspradli.carto.com/api/v2/sql?      format=GeoJSON&q={SELECT * FROM mosquitosamplingsites";

    var bicycleRental = L.geoJson(bicycleRental).bindPopup('Mosquito trap site');

    var overlayMaps={
    "Mosquito Sampling Sites": bicycleRental
    };

  L.control.layers(baseMaps,overlayMaps).addTo(map);

You can view results here

A: There are at least two problems with your jsbin code.

*

*You are not including Carto.js, instead you are using regular
Leaflet

*You are not using the Carto SQL API to get geojson, which
would look something this:
var sql = new cartodb.SQL({ user: 'examples', format: 'geojson' });

// create the layer and add to the map, then will be filled with data
var countriesLayer = L.geoJson().addTo(map);
sql.execute("SELECT * FROM european_countries_e").done(function(geojson) {
    countriesLayer.addData(geojson);
});

Maybe have a look at some of the Carto docs and tutorials?


text:
Q: React native toolbar styling I'm using react native base. I want to centre align the title in iOS and android both, since text is long it hides it with "…".
I've tried different option unable to fix it. How can I fix it?
Code:
 <Header  iosStatusbar="light-content" androidStatusBarColor='#000' >
<Left>
<Button transparent onPress={() =>  this.navigateCustom("goBack")}>
 <Icon name="arrow-back" />
 </Button>
</Left>

    <Body>
     <Title>CLAP TO SUPPORT US</Title>
   </Body>

  <Right>
  <Button transparent onPress={()=> this.navigateCustom("DrawerOpen") }>
     <IconEvil  name={"menu"}  style={{ color: "rgb(255,255,255)", fontSize:30}}/>
     </Button>
  </Right>
      </Header>

EDIT:
When I apply flex:1 to left right and body it changes nothing but applying flex:4 to body shows the title but it's not centred
 <Header  iosStatusbar="light-content" androidStatusBarColor='#000' >
<Left style={{flex:1}}>
<Button transparent onPress={() =>  this.navigateCustom("goBack")}>
 <Icon name="arrow-back" />
 </Button>
</Left>

    <Body style={{flex:4}}>
     <Title>CLAP TO SUPPORT US</Title>
   </Body>

  <Right style={{flex:1}}>
  <Button transparent onPress={()=> this.navigateCustom("DrawerOpen") }>
     <IconEvil  name={"menu"}  style={{ color: "rgb(255,255,255)", fontSize:30}}/>
     </Button>
  </Right>
      </Header>

Result:

Applying center alignment:

A: This is what i have tested on my device ios simulator, and Samsung Galaxy S7Edge and emulator.
import React, { Component } from 'react';
import { Container, Header, Left, Body, Right, Button, Icon, Title } from 'native-base';
export default class App extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Left  style={{ flex: 1 }}>
            <Button transparent>
              <Icon name='arrow-back' />
            </Button>
          </Left>
          <Body  style={{ flex: 4,  justifyContent: 'center', alignItems: 'center'  }}>
            <Title>Title Center</Title>
          </Body>
          <Right  style={{ flex: 1 }}>
            <Button transparent>
              <Icon name='menu' />
            </Button>
          </Right>
        </Header>
      </Container>
    );
  }
}

This is what i have tested and result.

I recommend you to check your React-Native package version and compare.

Here my last version:

"native-base": "^2.3.6",
"react": "16.2.0",
"react-native": "0.52.0",

EDIT:
CODE:
import React, { Component } from 'react';
import { Container, Header, Left, Body, Right, Button, Icon, Title } from 'native-base';
export default class App extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Left  style={{ flex: 1 }}>
            <Button transparent>
              <Icon name='arrow-back' />
            </Button>
          </Left>
          <Body  style={{ flex: 4,  justifyContent: 'center', alignItems: 'center'  }}>
            <Title>Title Center</Title>
          </Body>
          <Right  style={{ flex: 1 }}>
            <Button transparent>
              <Icon name='menu' />
            </Button>
          </Right>
        </Header>
      </Container>
    );
  }
}

NEXUS S RESULT

A: React Native (NativeBase) follows Android and iOS guidelines,
The title is on the Left of the header for Android and Center for iOS.

If you want it to be in the center, Please apply:
flex: 1 to <Left>, <Body> and <Right>

Example:
<Left style={{ flex: 1 }}>
</Left>

<Body style={{ flex: 1,  justifyContent: 'center', alignItems: 'center' }}>
    <Title>Home</Title>
</Body>

<Right style={{ flex: 1 }}>
</Right>


text:
Q: Is a boot-loader needed to dump the flash memory to RAM? Why? When a micro-controller is booting, does it fetch the instructions directly from the flash memory? But sometimes a boot-loader is used.
If so why do we use a boot-loader to dump the flash memory data into RAM?
How can I know whether the micro controller fetches the first boot instructions directly from the flash memory or through RAM?
Edit: My question is about bootloader! This is not duplicate at all.

A: "Boot loader" has many different meanings.

*

*In some (generally slower) microcontrollers the instruction data is stored within on-chip flash memory and executed directly from there. This obviously requires that the flash can be read as fast as the MCU executes instructions. A boot loader in these chips is a chunk of code in a reserved address range which is executed before the main program and whose purpose is to rewrite the rest of the program flash when necessary. For example, AVR-based arduinos contain a bootloader that allows the chips to reprogram themselves over the UART when uploading a "sketch".

*In other (generally faster) microcontrollers the instruction data is still stored within the on-chip flash, but it is transfered to on-chip RAM prior to execution. This is because designing flash fast enough to run from directly would be impractical. In these cases the bootloader still refers to a piece of code for rewriting the flash, as the data transfer is done in hardware.

*In others still there is just enough flash(or ROM/EEPROM) for storing the bootloader, whose sole purpose is to copy instructions from external memory (usually SPI/I2C flash) into RAM prior to execution.

A: The wikipedia page for bootloader does an okay job, is focused more on pc things, but still okay.
The loader part of the word (or standalone word if you type boot loader vs bootloader, I dont know if one is right or wrong) implies that not only does it boot the system, but it also allows for loading as in a tool for bootloader or other developers to get in and change things or do experiments before the application or operating system is started, basically interfere with the boot process if desired.  Otherwise it just bootstraps the system.
Understand the bootloader itself is just a program.  The processor doesnt know a bootloader from a hole in the wall, it is just machine code to run placed in the right place when the power comes on or reset is deasserted.
They can serve many purposes and the ones like uboot that prep you for linux are almost or in some cases are operating systems themselves with the massive size of the source.  heavy on that loader side, allowing full tcp/ip stacks to reach across networks to pull down experimental binaries.  support for various file systems, etc.
the typical use case for a microcontroller is not to use a bootloader, you boot right into the application and run it from flash.  which is why the flash size to ram size ratio is so high, your program is meant to live in and run from flash.  read disturb and other flash problems cannot be present in those chips for them to be successful products.  for in circuit programming though the trend is to have an alternate boot method either from the chip vendor themselves or always something you can add yourself using a gpio pin.  strap the pins a certain way and some other code boots, a bootloader that allows you ideally to reprogram the main application in flash, in circuit.  the old days you removed the microcontroller from its DIP socket, stuck it in a programmer or eraser and ultimately reprogrammed it, or wrote your own bootloader and used a gpio pin or pressed esc or something within seconds of booting (on a uart), that kind of thing.
the bootloader is as mentioned on the wikipedia page also can be and sometimes is used to put the system in a known state for the applications that follow.  not really that interesting for a microcontroller, but definitely for something bigger, initialize dram and the network interface maybe enumerate the pci bus or usb, etc.  stuff that would be common to any operating system that follows so that the operating system can just run and not have to do those things.
Some microcontrollers the factory programmed bootloader (often in a flash you cannot change or requires different steps than the app flash to change) only runs with pins strapped a certain way.  Other solutions the bootloader flash always runs, scans the app flash and decides if there is an application there and jumps to it and/or remaps and does a soft or not complete reset.  Why on the NXP I think it is the first so many words have to have a valid checksum.  Others anything non-0xFF it will try to boot.
for booting linux for example the bootloader would be the one that copies the root file system over and kernel to ram then branches to the kernel.  For a microcontroller though, the bootloader really shouldnt be doing that your application should if any data has to move at all do the move.  the bootstrap code before you branch to main() would copy the .data section over to ram if you have .data and zero the .bss section, set the stack pointer and branch to main.
in short in a microcontroller you dont need a bootloader, if there it is usually there for in system programming/upgrades.  your application runs from flash and only variables and other read/write items live in ram.

A: However some microcontroller will not support flash to flash programming, in such case also you need to copy bootloader to RAM. Then the bootloader in RAM will be capable of erasing the writing the application in the flash area.


text:
Q: Fill Data In Expandable/Collapsable UiTableView For Show Contact I Got MutableArray Like Following
 - @"6 objects"
 - [0]=(_NSDictionary*) 4 key/Value pairs
  - [0]=@"Home":@"(555)564-8583"
  - [1]=@"Mobile":@"(415)555-3695"
  - [2]=@"First Name":@"Kate"
  - [3]=@"Last Name":@"Bell"
 - [1]=(_NSDictionary*) 5 key/Value pairs
 - [2]=(_NSDictionary*) 5 key/Value pairs
 - [3]=(_NSDictionary*) 5 key/Value pairs
 - [4]=(_NSDictionary*) 5 key/Value pairs

Now I Want To Display My TableView Like following

*

*Kate Bell

*

*(555)564-8583

*(415)555-3695

*John Appleseed

*Hank Zakroff

*David Taylor

*Daniel Higgins

In Above TableView Kate Bell Is Expanded And Other All Are Collapsed.It Mean When We Tap On Contact Name At That Time Numbers Will Display And Another Tap It Will Hide.
I am Putting Code By Which I get Mutable Array named (allcontact) Like Above.
- (void)getAllContacts {

    //[self getPermissionForContacts ];
NSString *homeno,*mobileno,*workno;

    CFErrorRef *error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);

    for(int i = 0; i < numberOfPeople; i++) {

        ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );

        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        NSLog(@"Name:%@ %@", firstName, lastName);

        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

        for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
            NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
            NSLog(@"phone:%@", phoneNumber);
            if (i==0) {
                homeno=phoneNumber;
            } else if (i==1) {
                mobileno=phoneNumber;
            }else if (i==2) {
                workno=phoneNumber;
            }
        }

         allContactDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                     firstName,@"First Name",
                                        lastName,@"Last Name",
                                        homeno,@"Home",
                                        mobileno,@"Mobile",
                                        workno,@"Work",nil];

        [allContact addObject:allContactDict];

        homeno=@"";
        mobileno=@"";
        workno=@"";
        NSLog(@"=============================================");

    }

}

I Want My TableView Like Above Image.
Thanx In Advance


text:
Q: How can I tell clang-format to indent visibility modifiers? I want my visibility modifiers (public, protected and private) to be indented by clang-format who currently leaves them at the same level as the class declaration. I've looked for indent and visibility on a dump of the default format options but couldn't find anything.

A: If you want to give the access modifiers themselves their own level of indentation, you can use IndentAccessModifiers: true.  This will give you code that looks like the following.
class my_class {
  public:
    my_class() = default;
};

With IndentAccessModifiers: false, by default you'll get the access modifiers not indented at all, and class members will be indented only one level beyond the surrounding scope.
class my_class {
public:
  my_class() = default;
};

You can then use AccessModifierOffset to adjust the alignment of the access modifiers only, without affecting the alignment of the class members.  With IndentAccessModifiers: false and AccessModifierOffset: 1, you'd get this.
class my_class {
 public:
  my_class() = default;
};

With IndentAccessModifiers: true, AccessModifierOffset is ignored.
I'm sure all reasonable programmers would agree that only one of these options is even remotely acceptable.  Though they probably wouldn't agree on which one it is.

A: From the Clang-Format Style Options documentation:

AccessModifierOffset (int)
  The extra indent or outdent of access modifiers, e.g. public:.

So, add the appropriate entry to your .clang-format. For example,
AccessModifierOffset: 2


text:
Q: JavaScript создает угрозу index.html:
<script language="JavaScript">window.location.href="http://mysite.com"</script>

Проверяю index.html через Avast, и тот начинает "нежно, чуть ли шепча" говорить, что обнаружена угроза. Почему?
A: Это на какой странице? У вас перенаправление принудительное идет. И может быть даже циклическое.
A: Avast сам по себе тупой антивирус, может глючит...
Тэг language не используется (устарел давно), рекомендуется type, хотя если там JavaScript, то его указывать не нужно, ибо по умолчанию он!
Может ругаться на то, что такой прямой редирект иногда (чаще чем хотелось бы) используется в дорвеях.
А ещё может аваст определяет ссылку как ядовитую (опасный сайт в его базе).


text:
Q: change value upon select what i'm aiming is to show the other div when it selects one of the two options
Full time and Part Time
and if possible compute a different value for each
When the user selects Part time
the value of PrcA will change to PrcB
this is the code i used
<!====================================================================================>

<!====================================================================================>

Account Type *
<select name="acct" style="background-color:white;" class="validate[custom[serv]] select-input" id="acct" value="">

                <option value="Full Time">Full-Time</option>
                <option value="Part Time">Part-Time</option>
                <option selected="selected" value=""></option>

</select>

<!====================================================================================>

<!====================================================================================>

<lable style="margin-right:91px;"># of Agent(s) * </lable>

<input style="width:25px; margin-left:5px;" type="text" class="validate[custom[agnt]] text-input" name="qtyA" id="qtyA" onchange="calculate()" />

 x 1280 =

 x 640 =

$<input style="width:80px; margin-left:5px;" type="text" readonly="readonly"  name="totalA" id="totalA" onchange="calculate()" />

is there any way for me to achieve this?

A: Check this [FIDDLE] ..
Added two classes to the div's which show the amount.. This should make like easier to access them..
    $(document).ready(function() {
    $("#acct").on('change', function() {
        var selVal = $(this).val();
        if (selVal == '1') { // Full Time
            $('.parttime').hide();
            $('.fulltime').show();
            $('.agent').show();
            $('.error').hide();
        }
        else if (selVal == '2') { // Part Time
            $('.parttime').show();
            $('.fulltime').hide();
            $('.agent').show();
            $('.error').hide();
        }
        else {
            $('.parttime').hide();
            $('.fulltime').hide();
            $('.agent').hide();
            $('.error').show();
        }
    });

    $('#qtyA').on('change', function() {
        var selVal = $("#acct").val();
        if (!isNaN($(this).val())) {
            var total = 0;
            if (selVal == '1') {
                total = parseInt($(this).val()) * 1280;
            }
            else if (selVal == '2') {
                total = parseInt($(this).val()) * 640;
            }
            $('#totalA').val(total.toFixed(2));
        }
        else {
            $(this).val('0');
             $('#totalA').val('0.00');
        }
    });
});

Also you can completely eliminate the vanilla javascript and go with jQuery that should be lot easier..

A: got the answer this is what i used

A: A jsfiddle would help tremendously here. However, it sounds like you're trying to:

*

*Show/hide content containers based on a pulldown selection, and

*Process a field value based on the pulldown selection.

These two problems could generally be addressed like so (assuming jQuery, per your snippit):
<select id="time-select">
  <option value="full">Full-Time</option>
  <option value="part">Part-Time</option>
</select>

  Full-time info.

  Part-time info.

<input type="text" id="computed-value"/>


text:
Q: Is there a way to do layer 7 filtering in Linux? The L7-filter project appears to be 15 years old, requires kernel patches with no support for kernels past version 2.6, and most of the pattern files it has appear to have been written in 2003.
Usually when there's a project that is that old, and that popular, there are new projects to replace it, but I can't find anything more recent for Linux that does layer 7 filtering.
Am I not looking in the right places? Was the idea of layer 7 filtering abandoned entirely for some reason? I would think that these days, with more powerful hardware, this would be even more practical than it used to be.

A: You must be talking of (the former) project Application Layer Packet Classifier for Linux, which was implemented as patches, for the 2.4 and the 2.6 kernels.
The major problem with this project, is that the technology which it proposed to control, quickly outpaced the usefulness and efficacy of the implementation.
The members of the project, also had no time (and money) to further invest in outpacing some advancements of the technology, as far as I remember, and then sold the rights to the implementation, which killed for good an already problematic project.
The challenges this project/technology has faced over the years are, by no particular order:

*

*adapting the patches to the 3.x/4.x kernel versions;

*scarcity of processing power - in several countries, nowadays the speed of even domestic gigabit broad will demand ASICs to do efficient layer 7 traffic-shapping;

*bittorrent started using heavy obfuscation;

*HTTPS started being used heavily to encapsulate several protocols and/or to avoid detection;

*peer-to-peer protocols stopped using fixed ports, and started trying to get their way by any open/allowed port;

*the rise of ubiquitous voIP and video in real time, that makes traffic very sensitive to even small time delays:

*the widespread use of VPN connections.

Heavy R&D was then invested heavily, into professional traffic shaping products.
The state of the art ten years ago, involved already specific ASICs and (heavy use) of heuristics, for detecting encrypted/obfuscated traffic.
At the present, besides of more than a decade of experience in advanced heuristics, with the advancement of global broadband, traffic-shapping (and firewall) vendors, are also using peer-2-peer sharing in real-time, of global data, to enhance the efficacy of their solutions.
They are combining advanced heuristics, with real time profiling / sharing data from thousands of locations in the world.
It would be very difficult, to put together a open source product, that will work as efficiently as an Allot NetEnforcer.
Using open source solutions, for the purpose of infra-structure bandwidth health, it is not so usual, anymore, trying to traffic shape by the type/nature of traffic that IP address is using at the network level.
Nowadays, for generic traffic control and protecting the bandwidth capacity of the infra-structure, the usual strategy is (besides firewalling), without using advanced traffic shaping hardware, allocating a small part of the bandwidth per IP address.

A: Netifyd is an open source deep packet inspection alternative to l7-filter.  It was developed by the last maintainer of the l7-filter project and it's available for Linux and BSD.  No kernel hacking required.
Detecting encrypted protocols and things like modern BitTorrent is tricky, but certainly solvable.  Keep in mind, deep packet inspection goes beyond just detecting protocols (which was the focus of the l7-filter project).  For example, Netify DPI can detect weak ciphers in an SSL conversation - often a sign of a device running old firmware.
As Rui F mentioned, ASICs or dedicated hardware is required for sustained multi-gigabit speeds.  However, at the edge of the network, DPI can be deployed on run-of-the-mill computer hardware - even at 1 gigabit speeds.  It does take some horsepower to run - about the same as an effective intrusion detection/prevention engine.  Generally, only the first 10-ish packets of a network conversation are processed, so it's able to run in tight spaces.


text:
Q: Imagick on heroku - is it possible? I need to do some actions on jpeg images - Heroku's PHP GD does not allow that. I've read that it is possible with Imagick, so i rewritten the code, pushed it to heroku and...

PHP Fatal error:  Class 'Imagick' not found in [...]

So am I doing something wrong(code works locally)?
$tlo = new Imagick();
$tlo->newImage(640, 480, new ImagickPixel('white'));
$tlo->setImageFormat('jpg');

Is there any way of working with jpg on heroku?

A: A simpler approach is to install ImageMagick using composer.json, as explained here: https://devcenter.heroku.com/articles/php-support#using-optional-extensions
You just need to include imagick in the require section and update composer:
{
    ...
    "require": {
         "ext-imagick": "*",
         ...
    }
}

A: ImageMagick, a command-line utility and programming library, must be installed on the system for Imagick to work.
If it's not working for you, then presumably Heroku's PHP web dynos do not have this installed by default.  You have two options: you can find some convoluted way to package ImageMagick with your application itself, for instance by adding compiled binaries to your git source tree.  Or, you can modify the Heroku PHP buildpack, which is the set of rules that sets up the web dyno before your application is deployed, to install ImageMagick along with Apache and PHP itself.  The latter approach is more likely to work.
Once you've modified the buildpack, change your application to point to your buildpack fork with the command-line Heroku tools (the --buildpack option) and redeploy.


text:
Q: Web scraping with VBA I would like to create a macro to get real time stock quote from a financial website.
Below is my code.
Private Sub Worksheet_Change(ByVal Target As Range)

Dim stock As Long, rng As Range, quote As String, ie As InternetExplorer, doc As HTMLDocument

Set rng = Range("A1")
stock = rng.Value
Set ie = CreateObject("InternetExplorer.Application")

If Target.Rows = rng.Rows And Target.Columns = rng.Columns Then

    ie.navigate "http://www.aastocks.com/en/ltp/rtquote.aspx?symbol=0" & rng.Value
    ie.Visible = True

    Do
        DoEvents
    Loop Until ie.readyState = READYSTATE_COMPLETE

    Set doc = ie.document

    quote = doc.getElementsByTagName("neg bold").innertext

    MsgBox quote

End If

End Sub

However when I run the macro, it shows error 91 (Object variable or With block variable not set)  in the line
quote = doc.getElementsByTagName("neg bold").innertext

below is the HTML code of the source (the stock price)
1.900

Thanks a lot!

A: The argument for the getElementsByTagName should be an element name - not a class name. If you are looking to target an element by its class name, you could use the getElementsByClassname method instead
Also, be aware both these methods return elements collections - so unless in this specific instance the collection returned boils down to the single element you are targetting, there may be a bit more work to be done in order to narrow it down to what you are looking for


text:
Q: How can i avoid the duplicate Field counter from two user at the same time pressing the bottom i have collection which contains the whole users products , and to avoid the casts of reading all docs to get the length of the collection ,  i increase one value  +1 to every field once it's doc being created  , ok now everything is ok
here i am using this method to chick if doc if exist or not so i can avoid the duplicate of counter in case offline mode
 removeProduct1(){
    FirebaseFirestore.instance.collection("product").doc('product1')
        .get(const GetOptions(source: Source.server)).then((value1) {
      if(value1.exists) {
        FirebaseFirestore.instance.collection("product").doc('product1').delete();
        FirebaseFirestore.instance.collection("product").doc('productCount').update({
          'productCount': FieldValue.increment(-1),
        });
      }
    }).onError((error, stackTrace) {
      ScaffoldMessenger.of(context).showSnackBar(snackBar,);
      });
  }

also everything is ok , but i noticed if two user pressed the button for this method at the same time so its gonna be two value decrease -2
maybe someone will think its rarely when two user hit the button at the same time , well this is only simple sample of what i have for real instead , i have page which contains too many users which is not be rarely for being two user hit the button
EDIT FOR MOER EXPLATION
i have collection called Friends which contains User IDs of friends together
for example user1  his id is ABC and user2 his id is DEF
so id becomes final into the Friends collection like this ABCDEF by following function
and also this following function increase counter +1 for ever one of them
makeFriends(){
  // here i make sure first if the friends Ids are not exists To avoid suspiciously increasing the counter in offline mode and its work very well

    FirebaseFirestore.instance.collection("Friends").doc(user1Id+user2Id).get().then((value) {
        if(!value.exists){
          // here to add ids to the friends collection
          FirebaseFirestore.instance.collection("Friends").doc(user1Id+user2Id).set({
            'test':''
          });
          //here to increase counter in other colection which is users for both user
          //user1
      FirebaseFirestore.instance.collection("users").doc(user1Id).update({
        'friendsCounter':FieldValue.increment(1)
      });
      //user2
      FirebaseFirestore.instance.collection("users").doc(user2Id).update({
        'friendsCounter':FieldValue.increment(1)
      });
    }
  });
}

Okay now everything going fine and they became a friends with one value increased and their Ids became unit into Friends collection .. and here image for better explanation
image 1
image
here i have function responsible for deleting friend with decrease one value from FriendsCount Field for both of them
deleteFriends(){
  // here i make sure first if the friends Ids are exists To
  // avoid suspiciously decrease the counter in offline mode and its work very well
  FirebaseFirestore.instance.collection("Friends").doc(user1Id+user2Id).get().then((value) {
    if(value.exists){
      // here to remove ids from the friends collection
      FirebaseFirestore.instance.collection("Friends").doc(user1Id+user2Id).delete();
      //here to decrease counter for both user
      //user1
      FirebaseFirestore.instance.collection("users").doc(user1Id).update({
        'friendsCounter':FieldValue.increment(-1)
      });
      //user2
      FirebaseFirestore.instance.collection("users").doc(user2Id).update({
        'friendsCounter':FieldValue.increment(-1)
      });
    }
  });
}

ok now also everything going fine .. lets say user1 deleted his friend user 2 , by the previous functionthe Friends id which is ABCDEFhas been deleted so next time if user 2 want to do the same opretion it will fail because Friends ids are not exist anymore ..
the problem IS :
lets say these two users are still friends and
these two user visited each others profiles and hit the button at the same time which is call the pervious function (deleteFriend) so they gonna get the same return value which is (yes exists) then will be double decrease value for both of them instead of one as required .
means if their friendsCount was 1 both of them when they was a friend so tee value will be -1 instead 0 because there two operation was proceed
and this happen only if these two user hit the button at the same moment , but if the user 1 hit the button before user 2 then user 2 want to do same operation so he ganna fail because friendId was deleted by user1 operation as a condition statement in previous function ..
if(value.exists) i thought it too fast to delete friendIds before it give same result to other user if they together call the function at the same time

of course i can prevent the button of calling the delete function in case one of these user is already deleted other but I didn't see this as a strong solution since i can't grantee traffic jam or any reason else like bad users behavior .. etc , also basically i can't do it because delete button must be available as long as they still a friends
Note: this also happen in addFriends buttom call too if two users hit it at the same time , double value +2 instead one ..
i need any way to avoid server to give same result if there was two user query same doc at the same time , or any good solution

A: If you need to both read and write a document to update it, you should use a transaction to prevent the race condition that you now have when multiple users perform the operation around the same time.
Here you definitely want to use a transaction, because if the delete fails for whatever reason, the decrement operation should also fail (and vice versa).
The FlutterFire documentation on transactions also has a good explanation and example code to get started.


text:
Q: Joining SELECT variable into different table columns | follow suggestion I'm trying to join the result from one specific SELECT variable into a a different colum from another table.
user_friends table:
+-------------------------------------------+
|    friend_id | friend_one | friend_two    |
+-------------------------------------------+

users table:
+------------------+
|   uiD | username |
+------------------+

The following query retrieves random friends that my followers are following and suggests them to me, currently it's only retriving their uiD(id).
I'm unsure of how to join these two tables together and get the GROUP BY possible_friend below to connect to the users table.
$sth = $this->db->prepare("
                            SELECT friend_two AS possible_friend
                            FROM user_friends
                            WHERE friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                            AND friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                            AND NOT friend_two = :uiD
                            GROUP BY possible_friend
                            ORDER BY RAND()
                            ");
$sth->execute(array(':uiD' => $uiD));

$data = $sth->fetch();
return $data;

As an example, I'm user 10.
uiD = 10 : Username : Jonathan
uiD = 20 : Username : Gabriel
uiD = 30 : Username : Lisa
uiD = 40 : Username : Emily
I'm logged in as Jonathan, that is following Gabriel, but Jonathan is not following Lisa nor Emily.
Then it should show on a div.
Follow Suggestions:
Emily or Lisa
With the query above, I'm just able to get their ID's randomly but I'm unable to join the Username from the users table with the possible_friend from the user_friends table.
I've tried the following.
    $sth = $this->db->prepare("
                                SELECT F.friend_two AS possible_friend, U.username
                                FROM user_friends F, users U
                                WHERE F.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                                AND F.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                                AND NOT F.friend_two = :uiD
                                GROUP BY possible_friend
                                ORDER BY RAND()
                                ");
    $sth->execute(array(':uiD' => $uiD));

    $data = $sth->fetch();
    return $data;

but it just returns another username, since I'm unable to connect the U.username with the possible_friend.
UPDATE VERSION - WORKING VERSION :
    SELECT F.friend_two AS possible_friend, U.username, U.uiD, U.photo
    FROM user_friends F, users U
    WHERE F.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
    AND F.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
    AND NOT F.friend_two = :uiD
    AND U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
    AND U.photo NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
    GROUP BY possible_friend
    ORDER BY RAND()

A: SELECT U.uiD, U.username
FROM users U
WHERE U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
AND U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
ORDER BY RAND()


text:
Q: Design Automation cache life cycle Our customers would like to know what happens to their data, that is being processed by the Design Automation plug-in. As I understand, the input files are downloaded from the bucket and stored on the Design Automation VM instance while the plug-in runs. But what happens with input and output files when the job is finished? When and how are these resources erased? What happens to the VM itself? Also, could other service/program/user gain access to these files?
Secondly, is there a way to perform RVT->SVF conversion without using cloud services? Does Autodesk provide any desktop tool or API to do it locally?
Thanks in advance.

A: To the 1st question, in general, the Design Automation Cloud Sandbox will be destroyed as soon as the workitem is done, all the input and output files will be destroyed, that means there should be no other service/app could access these files after the DA workitem is done.
To the 2nd question, No, Rvt-Svf should be done by Model Derivative service, there is no local tool or API to do that from Autodesk at this moment.


text:
Q: Inactive Trigger Test Code Question for potential solution I was reading this:
Are inactive triggers counted against test coverage?
And I had an idea pop into my head: Can I cover several apex triggers, using a single test function, if they all contain the same code to be tested?
Here is my reasoning: my manager has asked me to please not delete the inactive apex triggers, and to instead comment out the code. But I am still tasked with getting coverage on these.
The idea I had was to use a hidden checkbox field, and assert that it is checked for the actual test.
The idea is if every trigger has the exact same code, would that single test asserting the checkbox checked as true satisfy the test coverage for all of those triggers?
Something like:
List<ObjectType> toUpdate = new List<ObjectType>();
for(ObjectType test : Trigger.new){
    if(name == value) check the checkbox;
}

test class
Insert test account to trigger the trigger;

TestStart();
Assert Checkbox
TestStop();

Would I run into any issues testing things this way? Would it cause problems to populate the triggers with the same code after commenting out the main code blocks?

A: Honestly, implement Version Control and get rid of everything you don't use any more. You can restore it at will very simply. But, that might be a bit of a pick your battles situation, and involves an unfortunate amount of office politics.
So what to do? This situation illustrates the value of a trigger framework. Then you can just comment out the method calls and not worry about the trigger body; the lines will get hit anyway. Here is the pattern I use, and your trigger coverage would be essentially unaffected in this scenario:
Service Layer
public with sharing class LeadServices
{
    public static void methodNoLongerNeeded1(List<Lead> leads) { /* implementation */ }
    public static void methodNoLongerNeeded2(List<Lead> leads) { /* implementation */ }
}

Handler Pattern
public with sharing class LeadTriggerHandler
{
    @TestVisible static void bypassTrigger = false;

    final List<Lead> newRecords;
    final Map<Id, Lead> oldMap;
    public LeadTriggerHandler(List<Lead> newRecords, Map<Id, Lead> oldMap)
    {
        this.newRecords = newRecords;
        this.oldMap = oldMap;
    }

    public void beforeInsert()
    {
        if (bypassTrigger) return;
        methodNoLongerNeeded1(newRecords);
    }
    public void afterInsert()
    {
        if (bypassTrigger) return;
        methodNoLongerNeeded2(newRecords);
    }

    public void beforeUpdate() { /* implementation */ }
    public void afterUpdate() { /* implementation */ }

    public void beforeDelete() { /* implementation */ }
    public void afterDelete() { /* implementation */ }

    public void afterUndelete() { /* implementation */ }
}

Trigger Implementation
trigger Lead on Lead (before insert, after insert /*etc*/)
{
    LeadTriggerHandler handle = new LeadTriggerHandler(trigger.new, trigger.oldMap);
    if (trigger.isBefore)
    {
        if (trigger.isInsert) handle.beforeInsert();
        if (trigger.isUpdate) handle.beforeUpdate();
        if (trigger.isDelete) handle.beforeDelete();
    }
    if (trigger.isAfter)
    {
        if (trigger.isInsert) handle.afterInsert();
        if (trigger.isUpdate) handle.afterUpdate();
        if (trigger.isDelete) handle.afterDelete();
        if (trigger.isUndelete) handle.afterUndelete();
    }
}

Getting coverage on your trigger itself is now trivial. It's also easy to just comment out methodNoLongerNeeded1 if that is all you were doing in some trigger you want to deactivate. One Trigger Per Object.


text:
Q: android edittext textwatcher format phone number like xxx-xxx-xx-xx how to format phone number like xxx-xxx-xx-xx using textwacher
tried following code,bt its not working while i delete elements
 et_phone_num.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        et_phone_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                et_phone_num.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        MyLog.e("onkeychange","key "+keyCode);
                        if(keyCode == KeyEvent.KEYCODE_DEL) {
                            keyDel = 1;
                            MyLog.e("onkeychange","key 1");
                        }
                        return false;
                    }
                });

                if (keyDel == 0) {
                    MyLog.e("onkeychange", "if key 0");
                    int len = et_phone_num.getText().toString().length();
                    if (len == 3) {
                        et_phone_num.setText(et_phone_num.getText().toString() + "-");
                        et_phone_num.setSelection(et_phone_num.getText().toString().length());
                    } else if (len == 7) {
                        et_phone_num.setText(et_phone_num.getText().toString() + "-");
                        et_phone_num.setSelection(et_phone_num.getText().toString().length());
                    } else if (len == 10) {
                        et_phone_num.setText(et_phone_num.getText().toString() + "-");
                        et_phone_num.setSelection(et_phone_num.getText().toString().length());
                    }

                } else {
                    MyLog.e("onkeychange", "else key 0");
                    keyDel = 0;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

A: finally i did it like this :
public class PhoneNumberTextWatcher implements TextWatcher {

private static final String TAG = PhoneNumberTextWatcher.class
        .getSimpleName();
private EditText edTxt;
private boolean isDelete;

public PhoneNumberTextWatcher(EditText edTxtPhone) {
    this.edTxt = edTxtPhone;
    edTxt.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                isDelete = true;
            }
            return false;
        }
    });
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
}

public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
}

public void afterTextChanged(Editable s) {

    if (isDelete) {
        isDelete = false;
        return;
    }
    String val = s.toString();
    String a = "";
    String b = "";
    String c = "";
    if (val != null && val.length() > 0) {
        val = val.replace("-", "");
        if (val.length() >= 3) {
            a = val.substring(0, 3);
        } else if (val.length() < 3) {
            a = val.substring(0, val.length());
        }
        if (val.length() >= 6) {
            b = val.substring(3, 6);
            c = val.substring(6, val.length());
        } else if (val.length() > 3 && val.length() < 6) {
            b = val.substring(3, val.length());
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (a != null && a.length() > 0) {
            stringBuffer.append(a);
            if (a.length() == 3) {
                stringBuffer.append("-");
            }
        }
        if (b != null && b.length() > 0) {
            stringBuffer.append(b);
            if (b.length() == 3) {
                stringBuffer.append("-");
            }
        }
        if (c != null && c.length() > 0) {
            stringBuffer.append(c);
        }
        edTxt.removeTextChangedListener(this);
        edTxt.setText(stringBuffer.toString());
        edTxt.setSelection(edTxt.getText().toString().length());
        edTxt.addTextChangedListener(this);
    } else {
        edTxt.removeTextChangedListener(this);
        edTxt.setText("");
        edTxt.addTextChangedListener(this);
    }

}
 }

MainActivity.class
et_phone_num = (EditText) findViewById(R.id.et_phone_num);
 et_phone_num.addTextChangedListener(new PhoneNumberTextWatcher(et_phone_num));

activity_main.xml
 <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.6"
        android:visibility="visible"
        android:id="@+id/et_phone_num"
        android:inputType="phone"
        android:maxLength="12"
        android:digits="0123456789"
        android:background="@drawable/phone_edittext_drawable"
        android:gravity="center"
        android:hint="5XX-XXX-XXXX"
        android:imeOptions="actionDone"
        android:textColor="@color/cc" />

A: Use Masked-EditText library.
Just pass your mask like below.
<com.github.pinball83.maskededittext.MaskedEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    app:mask="xxx-xxx-xx-xx"
    app:notMaskedSymbol="x"
    app:maskIconColor="@color/colorPrimary" />

Note : If you want to remove incorrect number than place your cursor before that digit and enter your right digit this Masked-EditText library will change it.