text:
Q: Scrolling is not working to focus on specific edittext android I have almost 20 input fields where i placed inside the scrollview. I have button at bottom. I need to validate the fields. If first field is empty, and when button is at extreme bottom, I need to move the page automatically to the first edittext.  But
I am not able to focus on specific edittext to move the scroll.
I tried many ways but still it's not working.
Here is xml structure and java code. i am using include to merge the xml "common_registration_update" inside the scrollview.
main.xml:
  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/reg_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/topLayoutId"
            layout="@layout/top_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp"
            />

        <RelativeLayout
            android:id="@+id/navigation_bar"
            android:layout_width="match_parent"
            android:layout_height="@dimen/registration_nav_bar_height"
            android:layout_below="@+id/topLayoutId"
            android:background="@color/colorGrey"
            android:orientation="horizontal"
            android:weightSum="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="@dimen/nav_bar_registration_txt_mrg_left"
                android:text="@string/registration"
                android:textColor="?attr/colorUserGroup"
                android:textSize="@dimen/gps_txt_size" />

            <TextView
                android:id="@+id/approve"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="@dimen/nav_bar_status_txt"
                android:text="@string/approval_status"
                android:textColor="@color/colorBlack"
                android:textSize="@dimen/gps_txt_size" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/info_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/navigation_bar"
            android:layout_marginTop="@dimen/info_icon_mrg_top"
            android:orientation="horizontal">

            <Space
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="1" />

            <TextView
                android:layout_width="@dimen/common_ribbon_icon_size"
                android:layout_height="@dimen/common_ribbon_icon_size"
                android:layout_marginRight="@dimen/info_icon_mrg_right"
                android:id="@+id/infoBtn"
                android:background="@drawable/ic_info_3" />
        </LinearLayout>

        <include
            android:id="@+id/retailer_form_new4"
            layout="@layout/common_registration_update"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/info_layout" />

</RelativeLayout>
</ScrollView>

You can see in the above layout where i am using include. "common_registration_update"
This common_registration_update.xml has,
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <TextView
            android:id="@+id/retail_profil"
            android:layout_width="165dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/form_mrg_left"
            android:layout_weight="0.01"
            android:text="Profile Toko"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/help_medium2text"
            android:textStyle="bold" />

        <LinearLayout
            android:id="@+id/retailer_form"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/retail_profil"
            android:orientation="horizontal"
            android:weightSum="2">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/form_mrg_left"
                android:orientation="vertical">

                <!--<TextView
                    android:layout_width="165dp"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/help_medium2text"
                    android:textColor="?attr/colorUserGroup"
                    android:text="@string/retailer_profile"
                    android:layout_weight="0.01" />-->

                <TextView
                    android:id="@+id/reg_static_nama_toko"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/retail_mrg_top"
                    android:text="@string/retailer_name1"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_nama_pic"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/tst_view_mrg_top"
                    android:text="@string/retailer_nama_pic"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_alamat_toko"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/tst_view_mrg_top"
                    android:text="@string/alamat_toco"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_tipe_toko"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="36dp"
                    android:text="@string/retailer_type1"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_trx1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/tst_view_mrg_top"
                    android:text="@string/trx1"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_trx2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/tst_view_mrg_top"
                    android:text="@string/trx2"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_trx3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/tst_view_mrg_top"
                    android:text="@string/trx3"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/reg_static_trx4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="19dp"
                    android:text="@string/trx4"
                    android:textColor="@color/colorBlack" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="205dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="@dimen/form_mrg_left"
                android:layout_marginTop="21dp"
                android:layout_weight="1.5"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/store_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/input_field_style"
                    android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789"
                    android:hint="Nama toko"
                    android:inputType="textNoSuggestions"
                    android:maxLength="30"
                    android:maxLines="1"
                    android:padding="@dimen/input_padding"
                    android:textColor="@color/colorBlack"
                    android:textSize="@dimen/help_medium1text" />

                <EditText
                    android:id="@+id/pic_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/input_mrg_top"
                    android:background="@drawable/input_field_style"
                    android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
                    android:hint="@string/pichint"
                    android:maxLength="50"
                    android:maxLines="1"
                    android:padding="@dimen/input_padding"
                    android:textColor="@color/colorBlack"
                    android:textSize="@dimen/help_medium1text" />
<//this goes like 20 fields>
</LinearLayout>
<RelativeLayout>

In code,
I use parent scrollview id to refer the specific edittext..
For eg:
mStoreName is edittext object and mScrollView is ScrollView object,
        mStoreName = (EditText) findViewById(R.id.store_name);
        mScrollview = (ScrollView) findViewById(R.id.reg_scroll_view); //parent scrollview

     if (checkKeyExists("store_name") && TextUtils.isEmpty(mStoreName.getText())) {
                showToastErrMsg("Please enter StoreName", mStoreName);
            }
    public void showToastErrMsg(String Msg, final View inputTextField) {
            final Dialog dialog = new Dialog(RetailerRegistrationActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.registration_err_modal);
            Button ok = (Button) dialog.findViewById(R.id.ok_button);
            TextView textView = (TextView) dialog.findViewById(R.id.response);
            textView.setText(Msg);
            dialog.setCancelable(false);
            dialog.show();

            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
//here redirecting to scroll to specific edittext but it's not working.
                           //mScrollview.scrollTo(0, inputTextField.getScrollY());
    //mScrollview.pageScroll(inputTextField.FOCUS_UP);
                            // mScrollview.scrollTo(0,inputTextField.getScrollY());
                           // mScrollview.smoothScrollTo(0,500);
                            mScrollview.scrollTo(0,inputTextField.getBottom());
                            dialog.dismiss();
                            inputTextField.requestFocus();
                           // scrollToView(mScrollview,inputTextField);
                        }
                    });
                }
            });
        }

I tried all commented lines to focus on edittext to move but it's not moving on specific position where cursor is located in edittext.

A: Your code seems perfectly fine to me.
sometimes android studio works weird.
Just try to clean and rebuild. if not, close studio and restart.
Many times this solution works!!
Modification-
final InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

put these lines after requestFocus() in your onClickListener()


text:
Q: separate dataset instances using datamodules in delphi I am using Delphi6 and have a data module with an ADO DataSet which is used by two forms, formA and FormB. Each form has a Dataset.Open() in OnCreate and Dataset.Close() in OnClose. If both forms are open simultaneously and formB is closed the dataset is closed in formA. How can I prevent this, essentially I need separate instances of the dataset for each form but at the same time use the datamodule.

A: Probably you need a separate instance from the datamodule for each form.
If you really want to use the same datamodule instance form both forms, then you have to open and close the dataset from the datamodule, adding some reference counting mechanism.
Tipically you do that by having a procedure for opening the dataset and one for closing it in the datamodule and an integer to count the open and close calls. The procedure which opens the dataset actually opens it only at the first call, at any subsequent call just incremets the counter. The closer procedure decrements the counter at each call, and closes the database when the counter value drops back to 0.

A: The simplest way to achieve what you want is to create an instance of the data module for each form, and pass it to the form so it can be freed when the form is closed:
var
  Data: TDataModule;
begin
  Data := T<YourDataModule>.Create(Self);
  try
    Form := T<YourForm>.Create(Self);
    Form.DataModule := Data;
    Data.Name := '';
  except
    Data.Free;
    raise;
  end;

  Form.Show;
end;

Setting the DataModule's Name to an empty string is done to ensure that the VCL's logic for hooking up data aware controls to their datasource/dataset is done using the newly created instance, instead of the first ever instance.
In the Form's OnClose handler (or its destructor) make sure to free the data module.

A: Are you trying to access the same dataset from FormA and FormB at the same time while displaying different data, if so:
Use a TClientDataSet and a TDataSetProvider to load the data from you ADO dataset.  Then clone the cursor using ClientDataSet.CloneCursor, you get a seperate cursor to the same data.  Then pass them to the forms or assign the controls of FormA to ClientDataSetA and FormB to the clone ClientDataSetB.  Reads, writes and updates from both forms change the underlying dataset which can then apply the updates to the database through the ADO dataset later via the DataSetProviders ApplyUpdates.
Look here for some help: http://www.podgoretsky.com/ftp/docs/Delphi/D5/dg/5_ds3.html
Or there is a really good book by Cary Jenson: http://www.jensendatasystems.com/cdsbook/
(free plug, but it is a good read)

A: As you said you need seperate instances, then my solution would be to have a Datamodule variable in each form declaration:
TForm1 = class(TForm)
...
private
  fDatamodule : TDatamodule1;
...
end;

procedure TForm1.FormCreate(Sender : TObject)
begin
  fDatamodule := TDatamodule1.Create(self);
  MyDatasource.Dataset := fDatamodule.MyDataset;
end;

(repeat for Form2 etc)
You have the same datamodule, instanciated twice and thus completely seperate from each other, but utilising the same business logic in each form.
Whilst on the subject, ensure your datamodule code does not make reference to either form.  This is bad practice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Want to load popup on homepage only using jQuery in wordpress I am creating a popup plugin in WordPress. In my plugin, a popup opens on every page but I just want to show it on home page.
I know how to get it in PHP but don't know hot to get the home url in jQuery.
setTimeout(function(){
    if($.cookie('SFPopup') == null){
        $('#sfp_Modal').modal('show');
    }else{
        $('#sfp_Modal').modal('hide');
    }
}, 3000);

This is how I am showing my popup using a cookie condition but I also want to show it only on home page not inner page.
This is my working code
<?php
function sf_display_popup(){
if (is_front_page() == true) {
?>
<script>
    jQuery(document).ready(function($) {
            $.cookieBar();
                setTimeout(function(){
                     //var site_url = '<?php echo home_url(); ?>';

                    if($.cookie('SFPopup') == null || $('body').hasClass('home')){
                        // alert(site_url);
                            $('#sfp_Modal').modal('show');
                        }else{
                            $('#sfp_Modal').modal('hide');
                        }
                }, 3000);

        });

</script>
<?php
    }
}
?>

A: try with checking body for class home. If body have home class it is home page.
if ($('body').hasClass('home')) { // show pop up }

A: I might be completly off, but wouldn't it be enough to check if document.location.pathname == "/" ?
That way you can check whether the adress is www.domain.com (<- would be root) or www.domain.com/something.
So if document.location.pathname == "/" you can execute your script and add the popup.


text:
Q: DateTime.Min JSON Serialisation Incorrect I am trying to figure this strange behaviour on a client machine (IE10)
When we create a new javascript Object, the ajax response from the server is \/Date(-62135596800000)\/.
I format the JSON Date in the following way:
var date  = new moment(parseInt(response.substr(6)));
On the Client machine this Date Object returns the following Date Format 0000-12-31.
When I try to validate the Date on the Server I get the response is an error saying that this is not a valid date.
My validation is Fluent Validation and the Rule is
RuleFor(x=>x.LastUpdateDate).NotEmpty();

Can anyone point me in the correct direction to help solve this issue?

A: Your timestamp value is interpreted as being an offset from a fixed UTC reference point. However, when you do something like
alert(theDate)

you'll see the default rendition of the Date instance as it would appear in the local time zone. In other words, a computer in Hong Kong will show the same UTC date differently than a computer in London.
You can use
alert(theDate.toUTCString())

to see a UTC version of the date.


text:
Q: Simple RESTful Java client in Google App Engine using java.net.URL I'm creating web app in Google App Engine which uses external RESTful services.
After a little research I've opted for using just the java.net.URL class, instead of any JAX-RS API such as Jersey, because these APIs have some compatibility problems with GAE, or they are only compatible with some versions and so on... and I don't like this issues very much.
Following this tutorial, to call the REST services I do:
URL url = new URL("rest-service-url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//process the response...

Then I process the JSON response using Google's GSON, which is also fully compatible with GAE.
First of all, in your opinion this is a good option?
And then, I'd like to centralize this code in some way, because I have many different calls to services in my app, so how could I do that? I thought of creating some class with a method like this:
public BufferedReader sendRESTRequest (URL url)
    //previous code here...
}

But I'm not sure about... this method should be static? synchronized? Should I create an HttpURLConnection object inside the method or in the class? etc...
Thanks!

A: Please take a look here if you are allowed to use Apache libs for your project. Why reinvent the wheel
Something on the lines of
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
private String poolTimeOutMillSecStr = System.getProperty("CONN_TIME_OUT_MILLSEC", "60000");

    private String maxTotalConnStr = System.getProperty("MAX_TOTAL_CONN", "400");

    private String maxConnPerRouteStr = System.getProperty("MAX_CONN_PER_ROUTE", "200");

    HttpUtility httpUtilty;

    private String baseUrl = System.getProperty("BASE_URL", "http://localhost:8888");

    private String userName;

    private String password;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        int poolTimeOutMillSec = Integer.parseInt(poolTimeOutMillSecStr);
        int maxTotalConn = Integer.parseInt(maxTotalConnStr);
        int maxConnPerRoute = Integer.parseInt(maxConnPerRouteStr);
        httpUtilty = new HttpUtility(poolTimeOutMillSec, maxTotalConn, maxConnPerRoute);
        httpUtilty.initialize(baseUrl);
        userName = "admin";
        password = "admin";

    }
}

And using it like
HttpResponse response = httpUtilty.postRequest(path, null, ins, null);
HttpEntity resEntity = response.getEntity();


text:
Q: Pdf is not previewable in Electron-Vue Desktop Application I have used electron-vue to create desktop application. I was trying to preview a pdf in my application. I have tried JsPdf, vue-pdf, iframe etc. But nothing has worked.
I am using Vue 2.5.16 version.
I can download the pdf using jspdf but can't preview it. While importing vue-pdf I got unrecognized token error.
Anyone knows any alternative solution?
Any kind of help is highly appreciable.

A: electron-vue is very outdated.
it uses electron 2.0.4, now we have electron 9.1.0.
you can read it in the dependencys here.
And from a personal project i know that the pdf bug has fixed in 9.0.
Here you find the Github Issue
So at least try to update the dependencys


text:
Q: How to get weekly data from an array Given that I have generated array of date, sales and type(customer,partner):
array(5) {
  [0]=>
  array(3) {
    ["date"]=>
    string(19) "25/03/2019 12:00 am"
    ["sales"]=>
    string(2) "95"
    ["type"]=>
    string(8) "customer"
  }
  [1]=>
  array(3) {
    ["date"]=>
    string(18) "25/03/2019 1:00 pm"
    ["sales"]=>
    string(5) "112.5"
    ["type"]=>
    string(8) "customer"
  }
  [2]=>
  array(3) {
    ["date"]=>
    string(18) "25/03/2019 1:20 pm"
    ["sales"]=>
    string(5) "132.5"
    ["type"]=>
    string(8) "customer"
  }
  [3]=>
  array(3) {
    ["date"]=>
    string(18) "25/03/2019 3:10 pm"
    ["sales"]=>
    string(2) "19"
    ["type"]=>
    string(7) "partner"
  }
  [4]=>
  array(3) {
    ["date"]=>
    string(18) "25/03/2019 4:07 pm"
    ["sales"]=>
    string(3) "7.5"
    ["type"]=>
    string(7) "partner"
  }
}

and I want to arrange it into something like this in table form:

If the date object is within the range of first week of the month it will get those date and add the sales of customer and partner. However, the column of customer and partner must be separated by column, then get the sum of customer and partner column to get the total on the 4rth column.
I found something on this post but it didn't help me out
PHP get number of week for current month only using php.


text:
Q: Prototype Equivalent JQuery's offset() I would like to know if there is any prototype equivalent to the JQuery's .offset() function?
Thanks for your help.

A: jQuery's offset (element position relative to document) maps to Element.cumulativeOffset
similarly, jQuery's position (element position relative to offset parent) maps to Element.positionedOffset

A: If you are looking for offset relative to document, go for:
Element.cumulativeOffset
If you are looking for offset relative to an element however, go for:
Element.Offset.


text:
Q: Gold nucleus vs. M87 surface gravity I tried to solve this gedanken problem, but I get a nonsense solution (may be is non resoluble).
Take a gold nucleus. Nuclear radius is about $R=7.2 \:\rm fm$. Consider it a solid rigid sphere (I take that this can be indeed the problem, since we know nuclei are not solid spheres as we imagine). Calculate the surface gravity at the nuclear radius. Calculate the distance from the center of the nucleus where the surface gravity equals the surface gravity of the M87 black hole (for simplicity, I took 6 billion solar masses and not the more exact value). Take gold mass equals to 197 u.
That is, where is the gravitational field (at what distance measured from the nuclear center) generated by the gold nucleus equals to the surface gravity on M87 black holes?
The point is that whenever I calculate the distance:

*

*If I suppose newtonian gravity proportional to $1/r^2$ (but it does not give a $r>R$ result). I get $10^{-20}$ meters (up to irrelevant numbers), which is smaller than the nuclear radius. But this can not be since inside the nucleus as solid sphere (I suppose nuclear density is not constant and that is why I cannot get a meaningless solution).

*Considering the nucleus as solid sphere with constant density, I get $10^{-5}$ meters, what is nonsense since I wanted a $r<R$ size.
What is the real solution, if any?
To summarize:

*

*Supposing $g$ proportional to $1/r^2$ in both the nucleus and M87 case, the distance where the surface gravity of the gold nucleus equals the M87 surface gravity equals about $10^{-20}$ meters.

*Supposing $g$ proportional to $r$ AND the constant density, we get $10^{-5}$ meters.
Of course, I am suspecting (2) is not correct since, after all, nucleus have no constant density and black hole interiors can not be in principle linear in density. However, taking for sure (1) conflicts the fact nuclear size has a finite high density, I believe.

A: Nuclei are quantum mechanical entities, and have to be described by quantum mechanics , i.e. built up by protons and neutrons, which in turn are composites of quarks.

where is the gravitational field (at what distance measured from the nuclear center) generated by the gold nucleus equals to the surface gravity on M87 black holes?

The mass of the nucleus is distributed within its radius in a quantum mechanical way, i.e in a probabilistic manner. There is no way to assume that the mass is concentrated in a smaller radius than the envelope of the nucleus as given by various models. The most appropriate would be the liquid drop model where a radius of the nucleus can be estimated. The nucleons will be in a probability distribution within that radius.
So the gravitational field can be estimated using classical gravity up to outside the radius of the nucleus. For smaller distances it is a probability distribution, and one cannot concentrate it to small dimensions as you are imagining.

A: The first answer, correct or not, is consistent with the fact that the gold or any other nucleus is, of course, far from being a black hole. The second answer must be incorrect.


text:
Q: Laravel homestead ignores features to be installed I want to add Minio to my Homestead VM. I've added the features option to the homestead.yml file, but running vagrant reload --provision doens't change anything and visiting http://homestead:9600/ gives me a ERR_CONNECTION_REFUSED. What am I missing here?
---
ip: "192.168.10.10"
memory: 4096
cpus: 1
provider: virtualbox
name: ausbildungsportal

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:

    - map: E:\programierung\ausbildungslink
      to: /home/vagrant/code/ausbildungslink

    - map: E:\programierung\uptimechecker
      to: /home/vagrant/code/uptimechecker

sites:

    - map: azubi.tested
      to: /home/vagrant/code/uptimechecker/public

    - map: help.tested
      to: /home/vagrant/code/ausbildungslink/public

databases:
    - homestead
    - azubiportal
    - ausbildungslink

features:
  - minio: true

A: I tried it and it didn't work for me. Fixed it by updating to the latest version of homestead

composer require laravel/homestead

A: I've just faced the same issue, leaving my solution here just in case.
For each feature, a separate script is triggered to manage the installation.
E.g. for docker it is homestead/scripts/features/docker.sh.
Inside it is checking if the feature is already installed (may look slightly different depending on the version):
if [ -f /home/$WSL_USER_NAME/.homestead-features/docker ]
then
    echo "docker already installed."
    exit 0
fi

So, if the feature is not installed, but still ignored by the Homestead script, you can just delete the needed file inside the VM (e.g. /home/vagrant/.homestead-features/docker for docker feature, similar for other features).


text:
Q: Null reference issue occurs when converting from Domain model to View model The below code throws null reference exception when there is no data to be returned from the stored procedure. Method executes successfully if data is present.
Am I doing anything wrong with the below code? Do I need to create an object from the model?
public PersonVM GetStaff()
{
    PersonDM personDM = _Repo.GetStaff();
    PersonVM personVM = PersonVM.ToViewModel(personDM);
    return personVM;
}

public class PersonDM
{
    public int RoleID { get; set; }
    public string Name { get; set; }
}

public class PersonVM
{
    public int RoleID { get; set; }
    public string Name { get; set; }

    public static PersonVM ToViewModel(PersonDM model)
    {
        return new PersonVM
        {
            RoleID = model.RoleID,
            Name = model.Name
        };
    }

    public PersonDM ToEntityModel()
    {
        return new PersonDM
        {
            RoleID=this.=RoleID,
            Name = this.Name,
        }
    }
}

When there is no data to be returned from the SP personDM becomes NULL. I need it to be filled with null values without returning NULL. Is it possible to achieve?

I did the same thing with a method which is returning a List<PersonVM> with the below code. It fills the VM with NULL values if there is no data present. How can apply the below code to a method which is returning the type PersonVM
public List<PersonVM> GetPartyByPartyRelationship(int partyRoleId, int partyRelationshipTypeId)
    {
        List<PersonDM> personDMList = _partyManagerRepo.GetPartyByPartyRelationship(partyRoleId, partyRelationshipTypeId);
        List<PersonVM> personVMList = new List<PersonVM>();
        foreach (PersonDM personDM in personDMList)
        {
            personVMList.Add(PersonVM.ToViewModel(personDM));
        }

        return personVMList;
    }

A: Assuming that _Repo.GetStaff() is returning null and therefore personDM is null, it should not be a surprise that a NullReferenceException is being thrown as you're trying to access object properties within ToViewModel() on a null reference.
Add a null check, either in GetStaff() or ToViewModel() and handle appropriately. Based on your update, you say you want to return a viewmodel with null properties, which you can do with the null check:
public static PersonVM ToViewModel(PersonDM model)
{
    if (model == null)
        return new PersonVM();

    return new PersonVM
    {
        RoleID = model.RoleID,
        Name = model.Name
    };
}

Update - Or, change your ToViewModel() method to utilise the null-progagating operator:
public static PersonVM ToViewModel(PersonDM model)
{
    return new PersonVM
    {
        RoleID = model?.RoleID,
        Name = model?.Name
    };
}


text:
Q: Change Twenty twelve theme background color I use the twenty twelve theme and I would like to change the background color manually by modifying the right files in the plugins folder. However, I can not find what to change in the style.css file. I even tried to modify the background color through the Wordpress interface to #e50000. After that, I looked for a line containing e50000 in my wordpress directory, but there seems to be none.
I can't figure out which line to change in my wordpress directory to change the background color.

A: The background is a option. You can set colors and also images. See in the Administration area, Appearance --> Background

Also you can use the Live Preview link on the theme and customize the background and other otpions.

A: Changing the theme background color can be done with the build in theme customizer.
Go to themes->customize. On the left you will see the customize options.
In the colors tab you will find the background color.
No need to code this ;)

A: When you change the background color through the dashboard (as mentioned by @bueltge), it is echo'd directly into the site head using <style> tags. You can override the background color in your style.css by setting it on the body element:
body {
    background-color: #efefef !important;
}

The !important part ensures that the color specified in style.css overrides the one set in the dashboard.

A: Easy. In the twentytwelve theme, search for this:
.site {
    padding: 0 24px;
    padding: 0 1.714285714rem;
    background-color: #888;
}

And change the background-color to what you'd like it to be.


text:
Q: nginx - phppgadmin - *1 access forbidden by rule I want to setup phppgadmin, postgresql is already - done by following this article
but I have nginx,
I did so far these configs:
ln -s /usr/share/phppgadmin /var/www

and
/etc/nginx/sites-available/phppgadmin:
server{
    listen 85;
    server_name     pgadmin.mypage.com;
    root            /var/www/phppgadmin;
    index index.html index.html index.php;

    access_log      /var/log/phppgadmin/access.log;
    error_log       /var/log/phppgadmin/error.log;

    location / {
            allow   my_page_IP;
            deny    all;
    }
    location ~ /\.ht {
            deny all;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /var/www/phppgadmin$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }
 }

and
ln -s /etc/nginx/sites-available/phppgadmin /etc/nginx/sites-enabled/

and
service nginx restart

but I am getting:
403 Forbidden

the error.log says:
2015/03/21 18:06:14 [error] 16916#0: *1 access forbidden by rule, client: 188.194.97.247, server: pgadmin.mypage.com, request: "GET / HTTP/1.1", host: "my_page_IP:85"

I did:
chmod -R 775 phppgadmin/
chown -R www-data:www-data phppgadmin/

but still the same 403 message. what am I doing wrong?

A: Access forbidden by rule mean that the access of the desired page was dropped by rule you have put in your configuration.
Just try to remove rule on each location to see which is cause problem.


text:
Q: how to disable copy for particular element in html Here, I'm having a problem with copy option when select 3 elements all the three are getting copied. But, I have a Jquery function to disable copy for the middle element. How I can disable that while selecting 3 elements. But, If I select the middle element individually it's not copying.

$('#notcp').bind('cut copy paste', function (e) {
    e.preventDefault();
});

select and copy

cannot copy

select and copy

A: Use This CSS Style to disable Selection. By this The Text will not be selected. Thus can't be copied also.
#notcp {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}

A: This feature can be done via disabling Text Selection using few CSS lines:
html, body {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}

A: There are numerous ways to achieve this.
Easiest one is to use jQuery's .hide() method
$("#notcp").hide();

To show it again, use the show() method
$("#notcp").show();

A: try add  return false;

   $('#notcp').bind('copy paste',function(e) {
    e.preventDefault(); return false;
});

A: Try with this.
$(document).on("cut copy paste","#notcp",function(e) {
    e.preventDefault();
});


text:
Q: Divisibility and factorization in rings that are not integral domains In my course notes for an undergraduate course "Algebra I", I wrote at the point when I'm introducing the notion of divisibility in rings (in a section on unique factorization):

We want to study factorization in arbitrary integral domains$^1$,...
$^1$ (footnote) The study of factorization in arbitrary commutative rings that are not integral domains, is in principle possible, but leads to rather exotic behavior and is therefore less interesting.

I have to confess that I didn't think too seriously about this sentence when I wrote it, but a student asked me whether that doesn't make it more interesting instead of less interesting.
I couldn't really give a sensible answer, hence my question:

Have there been serious attempts of a study of divisibility and/or factorization in arbitrary commutative rings with zero divisors, or is that simply something that doesn't really make sense?

Of course there are immediate problems even with the smallest examples such as $\mathbb{Z}/6$, e.g.
$$ 2 = 2 \cdot 4 = 2 \cdot 4 \cdot 4 = \dots $$
but I could imagine that there might be formal ways to overcome these obvious ambiguities when talking about uniqueness of factorization.

A: The biggest problem complicating factorization when there are zero-divisors present in my experience stems from the fact that there are several ways to define "associate" that are no longer equivalent.
For instance, the reference given by Guntram provides a good introduction to the issues:
$a$ and $b$ are associates, written $a\sim b$ iff $(a)=(b)$
$a$ and $b$ are strong associates, written $a \approx b$ iff $a=\lambda b$ for some $\lambda \in U(R)$
$a$ and $b$ are very strong associates, written $a\cong b$ iff $(a)=(b)$ and if $a=rb$ for some $r\in R$, then $r$ is a unit.
Each gives rise to a different type of irreducible along the lines of if $a=a_1 \cdots a_n$ is a factorization then $a \sim a_i$, $a \approx a_i$, or $a \cong a_i$ for some $1 \leq i \leq n$, respectively $a$ is irreducible, strongly irreducible, or very strongly irreducible.
Examples are given to show how the different types of irreducibles are no longer equivalent.
This means when looking at something like how to define a Unique Factorization Ring (instead of domain) you need to pick what type of atoms you want your factorizations to be broken into and then when rearranging up to associate, what to pick for that.
Of course, this is only part of the story.  Unique Factorization Rings are pretty nice, there are weaker properties that will fail by the existence of zero-divisors, idempotent elements and nilpotent elements.
Zero-divisors mean, you can factor zero: Say $ab=0$.  Well so does $0=ab=ababab=abxyzw$ or anything after it has already become zero.
Or nilpotents: $x^n=0$ implies $0=(x^{n-1})^{i}$ for all $i \geq 2$.
So do you allow zero to be factored? Maybe just don't allow zero to appear as a factor? Even that is not enough to deal with it completely.
Suppose $e=e^2$, well then $e=e^i$ for all $i\geq 1$, so does that mean your ring is not even a Bounded Factorization Ring?  This is what happened in your example $\mathbb{Z}/6 \mathbb{Z}$, $4$ is idempotent.
One approach that seems particularly nice was introduced by Fletcher in two papers in Proc. Cambridge Philos. Soc. in 1969 and 1970 called Unique Factorization Rings and The structure of Unique Factorization Rings.  This was U-factorization where you have essential and inessential divisors to help deal with things like nilpotents and idempotents.  M. Axtell has a couple of nice papers on it too in 2002 and 2003
U-factorizations in Commutative Rings with zero-divisors and Properties of U-factorizations.
This makes something like $\mathbb{Z}/6 \mathbb{Z}$ a U-UFR, U-HFR, U-BFR, etc, but not a UFR, HFR, or a BFR.
Interesting stuff in my opinion.
EDIT: I just wanted to add a few mathematical comments to respond to your mention of Galovich's paper.
This was something that I found very, very confusing when I first began studying factorization in rings with zero-divisors.  Nearly every author uses the term "irreducible" and "associate"; however, the problem is they mean different things in each case.  As far as I can tell D.D. Anderson and Valdez-Leon's method of 3 choices for associate, and several choices of irreducible (irreducible, strongly irreducible, m-irreducible, very strongly irreducible) is the most general and encompasses the others in the following way:
In Galovich's paper he chooses for associate the relation $\approx$.  That is $a$ and $b$ are "associate" in the Galovich sense if $a=\lambda b$ for some unit $\lambda$.  His choice for "irreducible", is what Anderson and Valdez-Leon termed "very strongly irreducible."
In Bouvier's papers we have "associate" is $\sim$ as in Anderson and Valdez-Leon $a$ and $b$ are associate if $(a)=(b)$.  However, the choice for "irreducible" is what is called m-irreducible, which comes from the fact that $a$ is m-irreducible if it is maximal among all principal ideals.  For non-zero elements, the strength of this type of irreducible falls between strong irreducible and very strong irreducible.  For zero, $0$ is m-irreducible if and only if $R$ is a field.  For zero to be irreducible, strongly irreducible, or very strongly irreducible is equivalent to $R$ being a domain.
There is yet another type of atomic referred to as i-atomic which is in terms of factorization into products of principal ideals, and I believe this is equivalent to the U-factorizations studied by Axtell, and Fletcher.
As you can see this is perhaps why most people skip the factorization with zero-divisors present.  Things get complicated rather quickly, but as the student alluded, perhaps this is what makes it more interesting in some ways.
This might be way more information than you want, but I just came across this site and it seems really exciting and useful and I saw your question was about what I study, and I may have gone a little overboard.


text:
Q: Obtener la condición de un bucle Si tengo un bucle:
for(var i = 0; i < 5 ; i++) {
ended = 5 - i === 1 && OperationSymbol.trim() === "i<5" true : false;
}

Que pretendo ? Primero obtener el condicional que se realiza en el for,
en este caso la condición es i < 5 , mientras i sea menor que 5, para qué?
Luego con esto, crearé una variable ,el nombre de esta será irrelevante,
lo que hará esta función es comprobar si el for ha acabado, y cómo ? ya que la condición es i < 5, cuando i sea igual a 4, será el último ciclo, por ende 5 - i (4) seria igual a 1.
El problema de esto, es:

¿Cómo obtengo la condición de un ciclo ?

, ya sea for o while

¿La variable sería ASIGNADA dentro de un ciclo for, pero cómo podría
  saber si realmente está en un ciclo for?

, osea cómo sé donde está una variable x ?
Con esto, desde cualquier función podra hacer algo cómo:
if (cicloX.ended()) // console.log("El ciclo finalizó, los datos están listos")

A: Lo que necesitarías sería envolver el bucle dentro de una promesa, y teniendo una referencia a esa promesa en otra parte del código, usar el método then de la promesa para ejecutar otra acción.
Cambié un poco tu ejemplo para que el bucle fuera asíncrono, pero dentro de la promesa puedes meter un while o for como te acomode:

var ti,
    contador=0,
    acumulador=[];
    promesa = new Promise(function(resolve,reject) {
        ti = window.setInterval(function() {

           console.log('ciclo ',contador);

           acumulador.push(contador);
           if(acumulador.length>=5) {
            window.clearInterval(ti);
            resolve(acumulador);
           }
           contador++;

        },500);
});

promesa.then(function(resultado) {

  console.log('acumulador terminó y tiene valores', acumulador);

});

Probablemente para el caso de uso que estás pensando, te sería más util ocupar alguna especie de deferred que puedes resolver manualmente sin envolver tu bucle en un constructor de promesa.

function Deferred() {
  var resolve, reject;
  var promise = new Promise(function() {
      resolve = arguments[0];
      reject = arguments[1];
  });
  return {
      resolve: resolve,
      reject: reject,
      promise: promise
  };
}

var ti,
    contador=0,
    acumuladorListener= new Deferred();

acumuladorListener.promise.then(function(resultado) {
  console.log('acumulador terminó y tiene valores', acumulador);
});

var acumulador=[];
    ti = window.setInterval(function() {
      console.log('ciclo ',contador);
      acumulador.push(contador);
      if(acumulador.length>=5) {
        window.clearInterval(ti);
        acumuladorListener.resolve(acumulador);
      }
      contador++;
    },500);


text:
Q: removeChild by element with PHP I want to remove the whole sticker node by calling the id 100.
But nothing happens really.
Any idea ?
$xml = new DOMDocument();
$xml->load('../write.xml');

    $result = $xpath->query('/stickers/sticker[id="100"]');
    $result->childNodes->item(0)->parentNode->removeChild($result->childNodes->item(0));

$xml->save('../write.xml');

      <stickers>
          <sticker> /* Remove */
            <text>Thaishi1</text>
            <id>100</id>
          </sticker>
            <sticker>
             </position>
            <text>Thaishi2</text>
            <id>200</id>
          </sticker>
        </stickers>

A: If "nothing happens", configure your error_reporting to a sensible debugging level – you should get warnings that there is no ->childNodes property.
$result->item(0)->parentNode->removeChild($result->item(0));

This should work.


text:
Q: rpy2, R eegAnalysis & time series error Working with a relatively new R package called "eegAnalysis" through rpy2 and getting an error for a time-series object required by the FeatureEEG function.
table_query = R_DBI.dbGetQuery(DBI_Connection, "SELECT * FROM {0}".format(a_table))

where table_query is returned from a PostgreSQL database, a small portion of the data looks like
'data.frame':   52000 obs. of  68 variables:
lfg1 : num  205 200 185 183 175 ...
lfg10: num  -135.1 -124.1 -127.1 -116.1 -80.1 ...
lfg11: num  -132 -109 -101 -103 -116 ...
lfg12: num  -259 -246 -232 -196 -203 ...
soon there-after a time-series object is created using table_query from above
ts = R_ts.timeSeries(table_query, start = 1, end = table_query.nrow, frequency = 1)

several lines below used for the important line even further below
n_columns = ts.ncol
col_middle = n_columns / 2
if round(col_middle) != col_middle:
    col_middle = col_middle + 0.5
group_1 = int(col_middle)
group_2 = int(n_columns - group_1)
classification = R_base.c(R_base.rep(1, group_1), R_base.rep(2, group_2))

the important line is here
featureEEG = R_EEGA.FeatureEEG(ts, rec_Id = ts.nrow, classes_Id = classification)

FeatureEEG is a function from the R eegAnalysis package. After processing for a few moments the
following error is returned

Traceback (most recent call last):  File "D:\Projects\Kaggle\UPenn_and_Mayo_Clinic_Seizure_Detection\Scripts\py_test01.py", line 135, in  featureEEG = R_EEGA.FeatureEEG(ts, rec_Id = ts.nrow, classes_Id = classification) File "C:\Python33\lib\site-packages\rpy2-2.3.8-py3.3-win32.egg\rpy2\robjects\functions.py", line 86, in call return super(SignatureTranslatedFunction, self).call(*args, **kwargs) File "C:\Python33\lib\site-packages\rpy2-2.3.8-py3.3-win32.egg\rpy2\robjects\functions.py", line 35, in call res = super(Function, self).call(*new_args, **new_kwargs) rpy2.rinterface.RRuntimeError: Error in UseMethod("months") :  no applicable method for 'months' applied to an object of class "c('integer', 'numeric')"*

From what I can tell, the line creating featureEEG is processed, and it is in the processing where
the error occurs. Most of the message is understandable except for the part starting at the
RRuntimeError. Could someone explain what it is saying? Or where can I find out?
Thank You.

A: The RRuntimeError is reporting an error message generated by R.
Here it appears to try calling a generic months(). I am suspecting that ts in your code is not of the right type. The authors of eegAnalysis might be able to help.


text:
Q: scala-spark Array mapping I have a question about mapping Array in scala. I have the following Array:
Array[(scala.collection.immutable.Set[String], com.trends.City, com.trends.State)]

Basically, I want to map the Array such that each String in the Set will have com.trends.City and State attached to it. The result should look something like:
Array[(String, com.trends.City, com.trends.State)]

Which is like flatMap, but I want the com.trends to be in there.
I could also convert the Array into a RDD if needed and use flatMapValues, but I am concerned for the efficiency, could someone tell me what is the best way to go?

A: You can use flatMap on scala array like this:
class City
class State
val array: Array[(scala.collection.immutable.Set[String], City, State)] = Array()
array.flatMap(p => p._1.map(q => (q, p._2, p._3)))


text:
Q: Where to Add text file on an Android Studio Project to place internal comments that won't be deployed on APK I want to add a text file on Android Studio where to place internal comments, ideas, development status, pendings, etc.
The issue is that I don't want this file to be part of deployment APK's, but I want to have it inside Android Studio project for simplicity.
I found somewhere that suggest to put it at resources folder:  res/raw, but this content will be deployed on APK and I don't want it.

A: Create a notes/ directory off of the project root. Or a docs/ directory. Or whatever you want.
Everything inside of src/ for a module is a candidate for being included in an APK. Conversely, stuff in directories that Android Studio does not know about (e.g., notes/, docs/, super-sekrit-stuff/) will not be included in an APK, unless you do something specific in the Gradle build files to request that they be included.

A: Just put it top level, right into your project folder and above app. Similar files such as the README, COPYING and BUILDING are placed there. For more info just search a bit through GitHub and you will find plenty of such structural examples.


text:
Q: flyway migration step multiple times I have a very complicated migration to perform. It can not be done with SQL, I've got to use Java. And I have treat each row individually, bulky update is not possible. To make things more complicated: one of my customers has several billions of rows in the table, other customers only a couple of hundreds. If I tried to migrate the large database table, I'll surely run into memory problems. At some point, the transaction memory runs out.
What I need is to migrate blockwise and invoke a migration step multiple times. Ideally, my JdbcMigration implementation could return an information like "I have not finished yet, please call me once more" or "I have finished, you can proceed with the next migration step" to the flyway system. If I had this feature, I would treat for example up to 1 million entries and let flyway commit the transaction. And I would repeat this as long as there are untreated entries.
Unfortunately, the method migrate(Connection) of JdbcMigration has a void return type. Is there any way to give flyway such a response?
Kind regards,
Christian

A: There is no direct support for this at this point. You can however issue commits yourself within a JdbcMigration, just keep in mind that a rollback issued by Flyway in case of an error won't have the same effect anymore.


text:
Q: mysql query using joins I'm trying to write a query that selects the latest "board" entries posted by friends, as well as the particular user. Meaning, if I was the user viewing this section, it would show the latest 6 board items including mine if I had posted something.
The query to get the friends is:
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
JOIN friend f ON f.friend_id = u.id
WHERE f.user_id = 1
ORDER BY `time` DESC
LIMIT 0 , 6

I'm dealing with tables where the actual user name was used in some tables, the user id in others. Thus, why the joins.
the above query gets all the latest posts by friends, but I want the user's own posts included if they made one.
For example:
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
JOIN friend f ON f.friend_id = u.id
WHERE f.user_id = 1
OR b.user = 'the_users_name'
ORDER BY `time` DESC
LIMIT 0 , 6

The second query merely returns 6 duplicate rows of the user due to the joins.
How can I fix this so it shows any user posts, and any friend posts?

A: I think using UNION ALL should do the trick:
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
JOIN friend f ON f.friend_id = u.id
WHERE f.user_id = 1
UNION ALL
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
WHERE u.user_id = 1
ORDER BY time DESC
LIMIT 0,6

The first query should give you the friends posts and the second would give you the users posts.  The UNION ALL combines those results together and the order by & limit are applied to the combined results.

A: Use a UNION: http://dev.mysql.com/doc/refman/5.0/en/union.html
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
JOIN friend f ON f.friend_id = u.id
WHERE f.user_id = 1
UNION ALL
SELECT b.id, b.user, b.title, b.text, b.time
FROM board b
JOIN user u ON u.user = b.user
JOIN friend f ON f.friend_id = u.id
WHERE f.user_id = 1
OR b.user = 'the_users_name'
ORDER BY `time` DESC
LIMIT 0 , 6

Something like that?


text:
Q: Automorphism group of cyclic group is isomorphic to $(\mathbb{Z}/n\mathbb{Z})^*$ Prove that the automorphism group $\operatorname{Aut}(C_n)$ of a cyclic group of order $n$ is  isomorphic to $(\mathbb{Z}/n\mathbb{Z})^*$

I know that the automorphism group consists of all the homomorphisms  from the group to the group. And I know that somehow I need to use the fact that the group is cyclic and has a generator. But I can't quite put the puzzle together.
Let $\langle g\rangle $ be the generator, it exists $m \in \mathbb{N}$ s.t $g^m=1$ so an automorphism must do $f(1)=1=f(g^m)=f(g)...f(g)=(f(g))^m=1$ does that mean $f(g)$ is also a generator ?
In order to have an isomorphism, I need to consider a homomorphism. Let $\varphi:\operatorname{Aut}(C_n) \rightarrow \mathbb{Z_n}$ with $\varphi(f)=$ ?
That's how far I go, automorphism are new to me and the whole exercise confuses me a little bit.

A: This is one place where I think it is very helpful to first ponder the problem in slightly more generality.  Fix a generator for $C_n$ once and for all.  I'll call it $g$ to meet your notation, so $C_n = \langle g \rangle$ throughout.
First, prove that every homomorphism $f: C_n \to C_n$ is uniquely determined by the value $f(g)$.  I think you know how to do this.  You just need to prove that given homs $f,h$ we have $f=h$ if and only if $f(g)=h(g)$.  This is nothing more than the definition of cyclic group.
Next, prove that every homomorphism $f: C_n \to C_n$ can be associated to a unique integer $m$ with $0 \leq m \leq n-1$.  The association is:  given a hom $f$, we know that $f(g) \in C_n$, but $C_n$ is generated by $g$.  Thus $f(g)$ is expressible as $g^m$ for some unique power $m$ with $0 \leq m \leq n-1$.  Let's call this $m_f$ instead of $m$ to denote its dependence on $f$.  In short, $f(g)=g^{m_f}$ where $m_f$ has been chosen "correctly."
You should be able to check that the association $f \mapsto m_f$ defines a perfectly good function from the set of all homs $f: C_n \to C_n$ into $\mathbb{Z}_n$ (as sets only for the moment).
Here's the first of two crucial moves:  prove that given two homs $C_n \stackrel{f}{\rightarrow}C_n\stackrel{h}{\rightarrow} C_n$ we have $m_{h\circ f}=m_h m_f \bmod n$. That is, our association $f \mapsto m_f$ respects composition in a multiplicative way mod $n$.  This is easier than it looks.
Here's the final bit.  Prove that $f: C_n \to C_n$ is an automorphism if and only if $m_f$ has a multiplicative inverse mod $n$.  To show one direction, suppose $f$ is an automorphism.  Then as $f$ is surjective there must be an $a \in C_n$ with $f(a)=g$.  This $a$, however, is expressible as $a=g^k$ for some integer $k$, since $g$ generates $C_n$.  Then
$$
g=f(a)=f(g^k)=f(g)^k=(g^{m_f})^k = g^{m_fk}.
$$
Hence $g^{m_fk}=g^1$ so you now have that $m_fk \equiv 1 \bmod n$, which is what we wanted to show.  You can fill in the rest.
Note that the association $f \mapsto m_f$ gives your isomorphism $\operatorname{Aut}(C_n) \to \mathbb{Z}_n^*$ and it is now clear why the operation must be multiplication mod $n$ (because the operation in the automorphism group is composition).

A:
I know that the automorphism group consists of all the homomorphisms from the group to the group.

Notice that automorphisms are not arbitrary homomorphisms, they are isomorphisms (homomorphisms+ bijections).

Let $<g>$ be the generator, it exists $m \in \mathbb{N}$ s.t $g^m=1$ so an automorphism must do $f(1)=1=f(g^m)=f(g)...f(g)=(f(g))^m=1$ does that mean $f(g)$ is also a generator ?

I want you to first show that an isomorphism preserves the order of an element (infact it preserves every group theoric properties.) Then you can conclude that a generotor must be sent to a generotor.
In the next step, just try to understand when you assign a genorator to another one, actually you assign all elements to one another. Then you can explicitly obtain the rule of your map.

A: I think to prove the exercise is enough to show that

*

*$|\text{Aut}(C_n)|=|\mathbb{Z_n}^*|$

*$\text{Aut}(C_n)=<f(g)>$

For 2. We can check that for a generator $g$ of $C_n$ we can get every element $h=g^m ,m\in \mathbb{N}$ so $f(h)=f(g^m)=(f(g))^m$
and for 1. a $g^i$ generates $C_n$ if and only if $\operatorname{gcd}(i,m)=1$.
$\lvert \operatorname{Aut}(C_n)\rvert=\phi(m)$ where $\phi(m)$ is Euler's function.


text:
Q: Missing CompileAs option on vcxproj generated by cmake 3.18.1 When I generate the .vcxproj for my project with cmake 3.2.1, it generates the line <CompileAs>CompileAsCpp</CompileAs>
But when I try the cmake version 3.18.1, the generated .vcxproj file does not contain that previous line causing my tests to fail (the code compiles).
Here the cmake code which set the project properties :
add_library(${PROJECT_NAME} SHARED ${PROJECT_SRC})

if(CMAKE_BUILD_TOOL MATCHES "(msdev|devenv|nmake|MSBuild)")
    target_compile_options(${PROJECT_NAME} PRIVATE "/TP")
endif()

target_include_directories(${PROJECT_NAME} PRIVATE ${PUBLIC_INCLUDES} ${PRIVATE_INCLUDES} )
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_target_properties(${PROJECT_NAME} PROPERTIES PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

How can I ask to cmake to generate that missing line (<CompileAs>CompileAsCpp</CompileAs>)?
Thank you.

A: I tried to use CMake 3.18.0 and it worked.
The CompileAs tag was generated so I will use this version instead of the CMake 3.18.1
Thank you.


text:
Q: Laravel hasmanythrough where statement I want to get the projects by the Auth::user() and company_id. I created the following:
Database:
projects:
    - id
    - name
    - company_id
project_users:
    - id
    - project_id
    - user_id
users:
    - id
    - name
    - email
companies:
    - id
    - name

So I want to get the current user projects which belongs to company_id.
I tried the following with User Modal -> return $this->hasManyThrough('App\ProjectUsers', 'App\Project'). $user->projects->where('company_id', 1) but it returns all the data (also with company_id 2,3,4 etc).
I'm looking for a solution which can filter the projects with company_id 1 out of the query.

A: You have to create function in model of user
public function projectusers() {
        return $this->hasMany('App\Models\project_users', 'projectID')->with('companies');
    }

now create function in model projects
public function companies() {
    return $this->hasMany('App\Models\companies','id', 'company_id');
}

A: If you are trying to limit a relation based on the results of another relation, then you need to use whereHas.
Also if you want to get the projects by some condition, I find its often most helpful to start there, with the projects.
$projects = App\Project::whereHas('company', function($q) use ($company_id) {
    $q->where('id', $company_id);
})->with('users')->get();

This will grab only the projects belonging to a certain company and also eager load the users.
As you are looping, then you can get the count of the users using the relation.
foreach ($projects as $project) {
    echo 'Num User: '.$project->users->count();
}


text:
Q: How to make an action bar like the Zomato app?

Like this in the Zomato app

This is the screen which opens when I click on the action bar location

I am using Android Studio 2.2 with targetSdkVersion 23


text:
Q: ArgumentNullException was unhandled This is a part of a code that will saved image to database
Bitmap TempImage = new Bitmap(@cwd + "\\Final.jpg", true);
        pictureBox.Image = new Bitmap(TempImage);//pictureBox.Image = Image.FromFile(imgName[0]);
        TempImage.Dispose();
        string name = textBox1.Text + ".jpg";
        MemoryStream mstr = new MemoryStream();
        pictureBox.Image.Save(mstr, pictureBox.Image.RawFormat);
        byte[] arrImage = mstr.GetBuffer();

then the program halts at pictureBox.Image.Save(mstr, pictureBox.Image.RawFormat); saying ArgumentNullException was unhandled, Value cannot be null.
Parameter name: encoder
what would be wrong?

A: Going to take a WAG and say that you shouldn't dispose of things you might be messing with later on.
using( Bitmap TempImage = new Bitmap(@cwd + "\\Final.jpg", true))
{
    pictureBox.Image = TempImage // why do => new Bitmap(TempImage); here?
    string name = textBox1.Text + ".jpg";
    MemoryStream mstr = new MemoryStream();
    pictureBox.Image.Save(mstr, pictureBox.Image.RawFormat);
    byte[] arrImage = mstr.GetBuffer();
}
// after this point, you'd better not be using pictureBox either!

Also, not sure why you are creating two Bitmaps... or using a "pictureBox" in order to save the image... Quite frankly, the more I look at this code the more I boggle.  Perhaps you should ask a question such as

I am attempting to foo an image so that I may bar.  How do I do this?

and skip this bit of code altogether.

A: The implementation of Save() will call FindEncoder() on the format you pass in as the second parameter (pictureBox.Image.RawFormat), and that is returning null.

A: simply use
pictureBox1.Image =
        Bitmap.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");


text:
Q: How to track performance issue of an ASP.NET MVC application? I have an application based on ASP.NET MVC V4 / SQL SERVER 2008 / WCF. This app will connect to some databases (DAL has coded our self) and other application via WCF services. There are many entity classes & services. Now I am not sure which part causes performance bottle neck.
Can anyone provide help with tools / solutions to help improving performance?

A: My proposal would be the light-weight MiniProfiler designed by the team of stackoverflow. It's easy to define what to profile:
using StackExchange.Profiling;
...
var profiler = MiniProfiler.Current; // it's ok if this is null
using (profiler.Step("Set page title"))
{
    ViewBag.Title = "Home Page";
}
using (profiler.Step("Doing complex stuff"))
{
    using (profiler.Step("Step A"))
    { // something more interesting here
        Thread.Sleep(100);
    }
    using (profiler.Step("Step B"))
    { // and here
        Thread.Sleep(250);
    }
}

It will give you feedback like this:

There are packages for MVC, EF and WCF.

A: As i said in this question ASP.NET MVC application profiling, you can use Glimpse for ASP.NET MVC profiling and here is a a plugin to track WCF calls in Glimpse and show them on the timeline. The requests are captured via GlimpseWcfClientInspector which implements IClientMessageInspector: https://github.com/stweb/Glimpse.WCF
I have never used them both (MVC & WCF) in the same application.
You can read the following in the referred question too. (for MVC)
If you're not a database boy like me, you'll love using Glimpse.
Glimpse is the diagnostics platform of the web.
Providing real time diagnostics & insights to the fingertips of hundreds of thousands of developers daily.
So you can start by grabbing Glimpse from NuGet.
PM> Install-Package Glimpse.MVC5

PM> Install-Package Glimpse.EF6

Initial configuration is the following:

*

*In the configSections:

*

*And after that:

Sorry for that but i waste 10 minutes trying to add xml code/quote/everything.
For further configuration and others, here: http://getglimpse.com/Docs/Configuration
After that you must navigate to /glimpse.axd or what path did you specified there and enable (it's a cookie).
Here is a site that is using Glimpse so you can see what's giving to you. Render view time/wire time/sql time/ajax profiling & so on..
http://play.getglimpse.com/
It is very extensible having plugins and so on. You can search.
And here is a talk that you can watch for reviewing some features and to convince you to use glimpse: https://www.youtube.com/watch?v=IGMYogdKYyw
And if you need to see ONLY the sql queries not the whole (rendering process etc.) you can press the glimpse circle and go to the sql tab. You'll have a view like the following:

A: You can use the inbuilt performance profiler tool in Visual Studio.


text:
Q: jQuery .ajax method in IE7 & IE6 not working but working fine in Firefox This relates to my previous post:
jQuery .load Method causing page refresh AJAX
I changed my implmentation to use the .ajax method instead of .load and it works fine in Firefox but not in IE7 or IE6:
    $('ul#coverTabs > li > a').live('click', function(event) {

    // Find href of current tab
    var $tabValue = $(this).attr('href');

    $.ajax({
        type: "GET",
        cache: false,
        dataType: "html",
        url: $(this).attr('href'),
        success: function(data){

        $(data).find('.benefitWrap').each(function(){

            var $benefitWrap = $(this).html();

            $('.benefitWrap').replaceWith($('
' + $benefitWrap + '
'));

        });

       }

    });

    event.preventDefault();

});

This is killing me as it has taken ages to get this far.
Any ideas where i am going wrong?

A: I accidentally worked out what the issue was.
The link referenced in this variable:
var $tabValue = $(this).attr('href');

Had a hash value on the end like so:
https://bupacouk.bwa.local.internal.bupa.co.uk/cash-plan-quote/quoteAction.do?getBenefitLevelDetails=getBenefitLevelDetails&productPolicyId=7850#a1

This cause the AJAX to fall over in bothe versions of IE.
Using the following code:
var $withoutHash = $tabValue.substr(0,$tabValue.indexOf('#'));

Getrs rid of it and it now works :)

A: Just an quick though.  I have had some frustrating issues with jQuery in the past that silently failed with IE6/7.  In almost all cases, somewhere in my code (not necessarily in the ajax call in question) I had a extra comma after an argument like this:
$.ajax({
        type: "GET",
        cache: false,
        dataType: "html",
        url: $(this).attr('href'),
        success: function(){},
)}

I would run the script through jslint to see if there is anything funny in the syntax causing this issue before doing proper debugging.

A: event is a reserved word in some versions of IE.  Try changing the parameter you're capturing from event to something sure to avoid collision, like evt, e.g.:
$('ul#coverTabs > li > a').live('click', function(evt) {

  evt.preventDefault();

  // Find href of current tab
  var $tabValue = $(this).attr('href');

  $.ajax({
    type: "GET",
    cache: false,
    dataType: "html",
    url: $(this).attr('href'),
    success: function(data){

    $(data).find('.benefitWrap').each(function(){

        var $benefitWrap = $(this).html();

        $('.benefitWrap').replaceWith($('
' + $benefitWrap + '
'));

    });

   }

});

Update
Upon further review, I believe your problem is the find().  In this case, you should use filter().
success: function(data) {
  $(data).filter('.benefitWrap').each(function() {
    // This should accomplish the same thing a bit more cleanly.
    $('.benefitWrap').html(this.innerHTML);
  });
}

That can be further refactored down to just:
success: function(data) {
  $('.benefitWrap').html($(data).filter('.benefitWrap').html());
}

A: Hash in the url is an issue with IE 6 and 7, xhr.status eror 500.  Resolved well with:
function removeHash(url) { return url.replace(/#(.*)$/, ""); }
$.get(removeHash(this.href),...)

see: http://forum.jquery.com/topic/ticket-3808-ajax-load-fails-404-if-there-is-a-hash-in-the-url

A: Well the problem seems to be here:
success: function(data){
            alert(data);
            $(data).find('.benefitWrap').each(function(){
                alert(data);
                var $benefitWrap = $(this).html();
                $('.benefitWrap').replaceWith($('
' + $benefitWrap + '
'));
        });

The second alert never appears but the first does.  I hate IE!


text:
Q: PC magically unlocks BitLocker without USB thumbdrive On premise, we have over 50 PCs with BitLocker Drive Encryption enabled.
For some employees their PC will start (after a complete power off) without using the USB drive.
The USB-drive setting is enabled via GPO, because the machines do not have a TPM-chip onboard. (This is a global setting, applied via the domain controller)
Are there ways to troubleshoot this issue? Rebooting via cmd shutdown /r /t 0 results in a blue BitLocker screen as expected.


text:
Q: Cordova iOS InAppBrowser options for location bar The Cordova InAppBrowser plugin allows the developer to open the in application browser when a link is clicked. In the code it is initialized during the listener event:
document.addEventListener("deviceready", addInAppBrowser(), false);

where,
document.onclick = function(e) {
    (void)addInAppBrowser = () => {
        window.cordova.InAppBrowser.open(link, target: "_blank", browserOptions);
    }
};

The browserOptions can be used to modify numerous aspects of the view, e.g. closebuttoncolor and toolbar.
Unfortunately, none of these options can be used to change the color of the location bar's address.backgroundColor.
Is it possible to change the attributes of the addressLabel during or after the initialization of the InAppBrowser, without having to modify the plugin code itself.
Note: The code has been abbreviated for clarity.

A: Update to Question with some Ideas
I did not find any simple method for implementing the functionality requested above. The InAppBrowser appears to only accept the designated options, which get parsed into an object and passed along through the code. Some ideas I had to get around this were:

*

*Using an after load callback to modify the plugin.

*Using hooks.

These are rather involved, and I suspect would take too much time to implement given the problem they were suppose to solve.
The application customer wanted to increase the contrast of the URL with the view.backgroundColor. They suggested a background color that would achieve the desired contrast. Since modifying the background color is not so straightforward, but it is simple to:

*

*Fork the cordova-plugin-inappbrowser and maintain the changes that will allow for fine control of the UI. The plugin is probably pretty stable, and so probably not problematic.

But I believe the correct solution will be to build a plugin that extends the InAppBrowser.


text:
Q: Get web traffic on port using http listener I have set up a web server using http listener. It is used to show a html file. The html file creates a request which I want the application to get. Here is a screenshot of the request in fiddler:
This is the only request that needs to be captured
This is what I tried:
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
Console.Write(ctx.Response.OutputStream);

This code always returns 'System.Net.HttpResponseStream' every time a request is made on the server. I want to see what it's returning but as a string.
Here is my web server code:
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;

    public WebServer(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
    {
        if (!HttpListener.IsSupported)
        {
            throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
        }

        // URI prefixes are required eg: "http://localhost:8080/test/"
        if (prefixes == null || prefixes.Count == 0)
        {
            throw new ArgumentException("URI prefixes are required");
        }

        if (method == null)
        {
            throw new ArgumentException("responder method required");
        }

        foreach (var s in prefixes)
        {
            _listener.Prefixes.Add(s);
        }

        _responderMethod = method;
        _listener.Start();
    }

    public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
       : this(prefixes, method)
    {
    }

    public void Run()
    {
        ThreadPool.QueueUserWorkItem(o =>
        {
            Console.WriteLine("Webserver running...");
            try
            {
                while (_listener.IsListening)
                {
                    ThreadPool.QueueUserWorkItem(c =>
                    {
                        var ctx = c as HttpListenerContext;
                        try
                        {
                            if (ctx == null)
                            {
                                return;
                            }

                            var rstr = _responderMethod(ctx.Request);
                            var buf = Encoding.UTF8.GetBytes(rstr);
                            ctx.Response.ContentLength64 = buf.Length;
                            ctx.Response.OutputStream.Write(buf, 0, buf.Length);

                        }
                        catch
                        {
                            // ignored
                        }
                        finally
                        {
                            // always close the stream
                            if (ctx != null)
                            {
                                ctx.Response.OutputStream.Close();
                            }
                        }
                    }, _listener.GetContext());
                }
            }
            catch (Exception ex)
            {
                // ignored
            }
        });

    }

    public void Stop()
    {
        _listener.Stop();
        _listener.Close();
    }

}
}

A: From the code you provided it looks like you're writing rstr as a UTF8 string to the output stream, so when you read the output stream again to get what its returning you will get the same value as rstr. So doing this should print what you're sending back in the stdout/console.
Console.WriteLine(rstr);

or you can use the StreamReader class to wrap the output stream and read the data as a string.
using (var reader = new StreamReader(ctx.Response.OutputStream)
{
    // Seek to origin, to read all data in the output stream,
    ctx.Response.OutputStream.Seek(0, SeekOrigin.Begin);
    var content = reader.ReadToEnd();
    Console.WriteLine(content);

    // You might not want to close the output stream in case you want to do more work with it.
}


text:
Q: How can I apply dynamically color to each row differently to HTML table? I've created HTML table dynamically using javascripts and now I want to apply each row a different color. How can I do so?

A: This will do
 $("tr:even").css("background-color", "#eeeeee");
$("tr:odd").css("background-color", "#ffffff");

Or below
$(function(){
  $('#table1 tr:odd').addClass('A');

 // for even

 $('#table1 tr:even').addClass('B');

});

A: you can achieve this by one of the following: css OR javascript:
javascript approach (i suggest including jQuery):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

// paint rows on document ready
$(function(){
    paint_rows();
});

function paint_rows() {
    $('#table_id tr').each(function(){
        $(this).css('color', get_random_color());
    });
}
</script>

just make sure to add enough color values into the array colors (can use hex values as well).
and, you can call the function paint_rows() whenever needed of course.
alternatively you can use css approach:
<style type="text/css">
#table_id tr:nth-child(1){color:blue;}
#table_id tr:nth-child(2){color:red;}
#table_id tr:nth-child(3){color:orange;}
/* etc... */
</style>

but i always prefer javascript.
HOWEVER!
if you just want to color every second row and switch between two colors (for example: one black, one blue, one black, one blue etc.) use the following css:
#table_id tr{color:black;}
#table_id tr:nth-child(even){color:blue;}

hope that helps.

A: While you build the rows assign to them a class name.
For example if you want to achieve a zebra striping  you may have a counter that increments while adding rows. Then check if the counter has odd or even value and add a class name denoting that to the corresponding row that was just added. Then in your css you can do something like,
.odd{
/*set background color*/
}

.even{
/*set background color*/
}

A: You can do something like below:
var tbl = document.getElementsByTagName("table")[0].style.border = "1px solid red";
td1 = document.getElementsByTagName("tr")[0].style.color = "red";
td2 = document.getElementsByTagName("tr")[1].style.color = "blue";

http://jsbin.com/EXUPuha/1/


text:
Q: Sending SSH Commands to Configure Networking Devices I am writing a CLI for configuring Cisco access points through Cisco wireless controllers over SSH in Go 1.9.2. I am using the golang.org/x/crypto/ssh package to handle connecting to the wireless controllers. I am able to successfully SSH to the desired controller, but I'm running into problems when attempting to send commands to the controller. I know the problem is due to the controller's prompt and output to Stdout. When manually connecting to a controller, this is the output:
$ ssh <controller_ip>

(Cisco Controller)
User: username
Password:****************
(Cisco Controller) >

Everything I have read and all the code examples I have seen of similar problems use the bufio package to create a reader to deal with the prompts/output. I can get that to partially work, but the program hangs after printing the line (Cisco Controller) before the username prompt, like this:
$ go run main.go

(Cisco Controller)
# infinite blinking cursor

I know this is because the controller is expecting a username to be passed.
My question, then, is how do I correctly handle parsing the output and send commands to the controller? I'm new to GO and network programming in general, so any help is appreciated. Here is my full code so far:
const (
    HOST = "hostname"
)

func main() {
    hostKey, err := HostKeyCheck(HOST)
    if err != nil {
        log.Fatal(err)
    }

    key, err := ioutil.ReadFile("/Users/user/.ssh/id_rsa")
    if err != nil {
        log.Fatalf("unable to read private key: %v", err)
    }

    // Create the Signer for this private key.
    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        log.Fatalf("unable to parse private key: %v", err)
    }

    // Create client config
    config := &ssh.ClientConfig{
        User: "username",
        Auth: []ssh.AuthMethod{
            ssh.Password("password"),
            // Use the PublicKeys method for remote authentication.
            ssh.PublicKeys(signer),
        },
        HostKeyCallback: ssh.FixedHostKey(hostKey),
        Timeout: time.Second * 5,
    }

    // Connect to the remote server and perform the SSH handshake.
    client, err := ssh.Dial("tcp", HOST+":22", config)
    if err != nil {
        log.Fatalf("unable to connect: %v", err)
    }
    defer client.Close()
    // Create a session
    session, err := client.NewSession()
    if err != nil {
        log.Fatal("Failed to create session: ", err)
    }
    defer session.Close()

    // Error occurs after this point
    var b bytes.Buffer
    session.Stdout = &b
    if err := session.Run("show"); err != nil {
        log.Fatalf("%v", err)
    }
    fmt.Println(b.String())
}

func HostKeyCheck(host string) (ssh.PublicKey, error) {
    file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
    if err != nil {
        return nil, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    var hostKey ssh.PublicKey
    for scanner.Scan() {
        fields := strings.Split(scanner.Text(), " ")
        if len(fields) != 3 {
            continue
        }
        if strings.Contains(fields[0], host) {
            hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
            if err != nil {
                return nil, errors.New(fmt.Sprintf("error parsing %q: %v", fields[2], err))
            }
            break
        }
    }

    if hostKey == nil {
        return nil, errors.New(fmt.Sprintf("no hostkey for %s", host))
    }

    return hostKey, nil
}

This is the output I get when running the program:
$ go run main.go
2017/12/28 14:13:28 ssh: command show failed
exit status 1

A: Here is an example: https://github.com/Scalingo/go-ssh-examples/blob/master/client.go
Shouldn't you need to start a new session to initiate commands?
Hope it helps.
func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) {
    var pass string
    fmt.Print("Password: ")
    fmt.Scanf("%s\n", &pass)

    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{ssh.Password(pass)},
    }

    sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()

    client, err := ssh.Dial("tcp", host, sshConfig)
    if err != nil {
        return nil, nil, err
    }

    session, err := client.NewSession()
    if err != nil {
        client.Close()
        return nil, nil, err
    }

    return client, session, nil
}


text:
Q: how to solve no attribute 'routes' in fastapi? I followed https://fastapi.tiangolo.com/tutorial/bigger-applications/ resource to design my app
.....game/urls.py....

from fastapi import APIRouter
router = APIRouter()
@router.post("/", response_model=schemas.GameOut, tags=["games"])
def create_game(game: schemas.GameIn, db: Session = Depends(get_db)):
    return Crud.create(db,game,model)

...main.py...

from game import urls as game_urls
app.include_router(game_urls,prefix="/games")

imported everything properly.
When i run uvicorn main:app --reload it is showing "NO attribures 'routes' " error
I am not able to find, what is the mistake i am doing here. Could any one helps me.

A: It seems you're injecting the entire urls module in your last line;
app.include_router(game_urls, prefix="/games")
                   ^

I believe you should only inject the router object, e.g. (you might want to import just the router here instead)
app.include_router(game_urls.router, prefix="/games")

A: Also if you have issue with @router not existing make sure you define the APIRouter as router and not web_router = APIRouter()


text:
Q: Cosmos DB APIs performance comparison I started to research Azure Cosmos DB and figured out that Cassandra API is not in GA yet. Although I'm generally interested in Cassandra API, I'm also trying to figure out how Cosmos DB works so I could possibly find a way how to use existing APIs for my needs.
What I understood from the official documentation:

*

*Cosmos DB stores data in the same way regardless of used API (MongoDB, Cassandra, etc.)

*Cosmos DB automatically indexes all the properties

Does it mean that I can use any other API (e.g. MongoDB, SQL, etc.) and expect similar performance as I would have if I could use Cassandra API?

A:

Cosmos DB stores data in the same way regardless of used API (MongoDB, Cassandra, etc.)

Cosmos DB stores data in the different ways when use different APIs.

Cosmos DB automatically indexes all the properties

By default, all Azure Cosmos DB data is indexed. More information for your reference: How does Azure Cosmos DB index data

Does it mean that I can use any other API (e.g. MongoDB, SQL, etc.) and expect similar performance as I would have if I could use Cassandra API?

Every API is suitable for the specify scenarios and has better performance in its suitable scene than others.
For example:
If we used to use MongoDB in the past, we can use Mongo API.

If we need to handle our data which is like model or to model both entities and relationships naturally, we can use graph api.

If we need to store data for apps which are written for Apache Cassandra, we can use Apache Cassandra API.


text:
Q: asp.net mvc 4 vs JavaScript templates I've been struggling in deciding what direction to go with in regards to the best approach for rendering content to the browser: server side using razor or client side using JSON data and some form of templating (jsRender, loadJson, etc.)
Here's a great article on using client side templating with asp.net mvc:
jQuery Templates/View Engines in ASP.NET MVC
ASP.Net MVC 4 has some great toys (WebAPI).  I can see creating a suite of WebAPI functionality for delivering JSON data that can be used on traditional web pages and even mobile pages.  Really cool stuff.
Then I look at what options you have going with a traditional ASP.Net MVC approach.  You have layouts, can take advantage of automatic bundling/minification of JS/CSS files (more ASP.Net MVC 4 goodness), robustness of having ASP.Net MVC available at your fingertips.  Really cool stuff.
So, my question is how do you make decisions on which direction you should go architecturally?  I suppose you can have a mix bag of approaches within your site, but that becomes a maintenance issue.  Going total JavaScript Templates and consuming JSON data from a service is a super clean separation of concerns, but it seems you loose out on a lot of the goodness that ASP.Net MVC offers like routing.
What's the best approach for balancing all of the options available to us?

A: This is a bit of a general question, so a general answer is that you should stick to the approach that makes you most productive/gets the job done. Either approach works but of course has tradeoffs. However those usually don't matter that much unless you reach really big scale (e.g. Twitter recently annonced it will move back to server-side rendering for performance reasons). If you're already familiar with MVC and you're working against a deadline - stick to that. If you have more time or want to learn a new technique - go with what looks interesting.


text:
Q: Problems after changing path without reload in AngularJS: I've implemented the solution explained here
https://stackoverflow.com/a/24102139/2795097
app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
    if (reload === false) {
        var lastRoute = $route.current;
        var un = $rootScope.$on('$locationChangeSuccess', function () {
            $route.current = lastRoute;
            un();
        });
    }
    return original.apply($location, [path]);
};
}])

Changing the path with no reload is working nicely with this solution.
It's afterwards when I'm having problems with links  <a href='...'> managed with $routeProvider. They should reload the view but what actually happens is the path is changing, but my view is not updating at all. Bizarrely, some links actually refresh the view, some others don't.
That only happens after navigation by calling the new method from the solution $location.path with false.
Any idea what's happening here?

A: I had to add a small delay to unregister the $locationChangeSuccess function.
My code ended like this:
 var original = $location.path;

$location.path = function (path, reload) {
if (reload === false) {
    var lastRoute = $route.current;
    var un = $rootScope.$on('$locationChangeSuccess', function () {
        $route.current = lastRoute;

    });

    $timeout(un, 200);
}

return original.apply($location, [path]);

};


text:
Q: Magento 2 Round off layered navigation max price in the price range I want to round off the price range values in the layered navigation. Now it is showing as below
$40.00 - $49.99
$50.00 - $59.99
$60.00 - $69.99
$70.00 - $79.99
$90.00 and above

I want the following format.
$40.00 - $50
$51.00 - $60
$61 - $70
$71 - $90
$91.00 and above

How can I do it?
I am using magento 2.3.2.
I have configured the Price Navigation Step Calculation field as "Automatic (equalize price ranges)".
Please help me to resolve this

A: I have override the _renderRangeLabel function in the class
Magento\CatalogSearch\Model\Layer\Filter\Price.php.

A: You just need to set below configuration

Stores > Configuration > Catalog > Catalog > Layered navigation >
  price navigation step calculation

I hope this settings help of you.


text:
Q: Transitions with nested data D3.js I've recently begun learning D3.js and I am struggling to create a transition in a scatter plot with the following data:
var data = [
    {"year" : "2004", "x":100, "y":300, "size": 2, "type": "A"},
    {"year" : "2005", "x":200, "y":200, "size": 2, "type": "A"},
    {"year" : "2006", "x":300, "y":100, "size": 2, "type": "A"},
    {"year" : "2004", "x":150, "y":250, "size": 2.382450, "type": "B"},
    {"year" : "2005", "x":150, "y":250, "size": 3.078548, "type": "B"},
    {"year" : "2006", "x":150, "y":250, "size": 4.265410, "type": "B"}];

Where in the scatter plot there are 2 points (type A&B) and they change location (x&y) and size by year. I've created a fiddle where I try to nest the data and plot the points, but making the next step of using transition() function is confusing. More specifically, I am still declaring the whole data, but to make transitions work I only need part of the data.

A: The key to understand what you want lies here:

There are 2 points and they change location (x&y) and size by year

Therefore, this is clearly a XY problem. Your problem is not "how to transition with nested data". Your problem is "how to transition by year".
My proposed solution involves, first of all, dropping that nested array. You don't need that.
Instead, get all the years in the data...
var years = [...new Set(data.map(function(d) {
  return d.year
}))];

..., filter the data by year...
var dataStart = data.filter(function(d) {
  return d.year === years[0]
});

... and loop trough the years. Here, I'm using d3.interval():
var counter = 1;
var timer = d3.interval(transition, 1500);

function transition() {

  var newData = data.filter(function(d) {
    return d.year === years[counter]
  });

  svg.selectAll("circle").data(newData)
    .transition()
    .duration(1000)
    .attr("cx", function(d) {
      console.log(d)
      return d.x;
    })
    .attr("cy", function(d) {
      return d.y;
    })
    .attr("r", function(d) {
      return d.size * 10;
    });
  counter += 1;
  if (counter === 3) {
    timer.stop()
  }
}

Here is the demo:

var data = [{
      "year": "2004",
      "x": 100,
      "y": 100,
      "size": 2,
      "type": "A"
    }, {
      "year": "2005",
      "x": 200,
      "y": 180,
      "size": 2,
      "type": "A"
    }, {
      "year": "2006",
      "x": 300,
      "y": 50,
      "size": 2,
      "type": "A"
    }, {
      "year": "2004",
      "x": 150,
      "y": 150,
      "size": 2.382450,
      "type": "B"
    }, {
      "year": "2005",
      "x": 150,
      "y": 50,
      "size": 3.078548,
      "type": "B"
    }, {
      "year": "2006",
      "x": 150,
      "y": 100,
      "size": 4.265410,
      "type": "B"
    }];

    var width = 400,
      height = 200;

    var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height);

    var years = [...new Set(data.map(function(d) {
      return d.year
    }))];

    var dataStart = data.filter(function(d) {
      return d.year === years[0]
    });

    var cell = svg.selectAll("circle")
      .data(dataStart);

    cell.enter()
      .append("circle")
      .attr("cx", function(d) {
        return d.x;
      })
      .attr("cy", function(d) {
        return d.y;
      })
      .attr("r", function(d) {
        return d.size * 10;
      });

    var counter = 1;
    var timer = d3.interval(transition, 1500);

    function transition() {

      var newData = data.filter(function(d) {
        return d.year === years[counter]
      });

      svg.selectAll("circle").data(newData)
        .transition()
        .duration(1000)
        .attr("cx", function(d) {
          return d.x;
        })
        .attr("cy", function(d) {
          return d.y;
        })
        .attr("r", function(d) {
          return d.size * 10;
        });
      counter += 1;
      if (counter === 3) {
        timer.stop()
      }
    }
<script src="https://d3js.org/d3.v4.min.js"></script>


text:
Q: Images don't show up in ListView i'm trying to make a sort of image diary where one can create post with images. First i had the problem that every post showed the same image, but tried to fix it with File.createTempFile. But now nothing is showing and i get a lot of null pointer exceptions.
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    /**
     *Gets the images taken with the camera, depended on how many pictures were taken, they are saved in images.
     **/
    if (requestCode == CAMERA_REQUEST && resultCode == this.getActivity().RESULT_OK && counter <= 2) {
        Bitmap bmp = (Bitmap) data.getExtras().get("data");

        switch (counter) {
            case 0:
                im1.setVisibility(View.VISIBLE);
                im1.setImageBitmap(bmp);
                Log.d(this.getActivity().getPackageName(), bmp != null ? "bmp is not null!" : "bmp is null!");
                images.add(saveToInternalStorage(bmp));

                counter++;
                break;
            case 1:
                im2.setVisibility(View.VISIBLE);
                im2.setImageBitmap(bmp);
                //pathList.add(1,saveToInternalStorage(bmp));
                images.add(saveToInternalStorage(bmp));

                counter++;

                break;
            case 2:
                im3.setVisibility(View.VISIBLE);
                im3.setImageBitmap(bmp);
                images.add(saveToInternalStorage(bmp));

                counter++;
                break;
        }

...
     private String saveToInternalStorage(Bitmap bitmapImage) {
    ContextWrapper cw = new ContextWrapper(this.getActivity().getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath = null;
    try {
        mypath = File.createTempFile("image", ".jpg", directory);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream fos = null;
    try {

        fos = new FileOutputStream(mypath);

        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return directory.getAbsolutePath();
}

...Is in my Adapter
    private Bitmap loadImageFromStorage(String path) {
    Bitmap b = null;
    File f= null;

    try {
        f =  new File(path);
        b = BitmapFactory.decodeStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return b;
}

Updated my code above, but no i get this exception. I think maybe the error is with the File.createTempFile when a image is saved and the load function to get the image again, can it be something i missed there?
fixed the exception but i still don't get the images

A: Inside your loadImageFromStorage(String path, int i) method
line
String name = p.getImageNames().get(i);

is giving you error make sure you are setting arraylist on your instance variable p and, then try to get that list.