text:
Q: Magento extension installed but not showing up in admin I've installed a magento extension and it seems to be installed correctly. I've I check it in Admin->System->Configuration->Advanced It appears Enabled. But The tab is suposed to appear in admin, doesn't appear.
My magento version is 1.7. I've tried some things but nothing works:

*

*I've cleaned the cache directory and clean the cache in admin

*I've give the hole web directory 777 permisions

*I've reinstall the extension

*I've installed it from magento connect and directly copping the directories and files from github

*I've uninstalled and installed a few times

*I've log out and log in in magento admin

But nothing fix my problem. Has anyone any more ideas?
The extension is SMTP Pro Mail. Here is the system.xml
    <config>
  <tabs>
    <aschroder module="smtppro" translate="label">
      Aschroder Extensions
      <sort_order>600</sort_order>
      <show_in_default>1</show_in_default>
      <show_in_website>0</show_in_website>
      <show_in_store>0</show_in_store>
    </aschroder>
  </tabs>
  <sections>
    <smtppro module="smtppro" translate="label">
      <class>separator-top</class>
      SMTP Pro
      <tab>aschroder</tab>
      <frontend_type>text</frontend_type>
      <sort_order>110</sort_order>
      <show_in_default>1</show_in_default>
      <show_in_website>0</show_in_website>
      <show_in_store>0</show_in_store>
      <groups>
        <general module="smtppro" translate="label comment">
          General Settings
          <frontend_type>text</frontend_type>
          <sort_order>10</sort_order>
          <show_in_default>1</show_in_default>
          <show_in_website>1</show_in_website>
          <show_in_store>0</show_in_store>
          <comment><![CDATA[
  SMTP Pro Email Extension
 Configure your SMTP connection below. If you have any questions or would like any help please visit magesmtppro.com.]]></comment>
          <fields>
            <option translate="label">
              Email Connection
              <frontend_type>select</frontend_type>
              <source_model>smtppro/system_config_source_smtp_option</source_model>
              <sort_order>10</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
            </option>

            <googleapps_email translate="label">
              Google Apps Email Address
              <frontend_type>text</frontend_type>
              <sort_order>20</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>google</option></depends>
            </googleapps_email>
            <googleapps_gpassword translate="label comment">
              Google Apps Password
              <comment><![CDATA[Input your Google Apps or Gmail username and password here. For configuration recommendations please see the guide at magesmtppro.com]]></comment>
              <frontend_type>password</frontend_type>
              <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
              <sort_order>23</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>google</option></depends>
            </googleapps_gpassword>

              <sendgrid_email translate="label">
                  SendGrid Username
                  <frontend_type>text</frontend_type>
                  <sort_order>20</sort_order>
                  <show_in_default>1</show_in_default>
                  <show_in_website>1</show_in_website>
                  <show_in_store>0</show_in_store>
                  <depends><option>sendgrid</option></depends>
              </sendgrid_email>
              <sendgrid_password translate="label comment">
                  SendGrid Password
                  <comment><![CDATA[Input your SendGrid username and password here. For more information visit SendGrid]]></comment>
                  <frontend_type>password</frontend_type>
                  <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                  <sort_order>23</sort_order>
                  <show_in_default>1</show_in_default>
                  <show_in_website>1</show_in_website>
                  <show_in_store>0</show_in_store>
                  <depends><option>sendgrid</option></depends>
              </sendgrid_password>

            <ses_access_key translate="label">
              Amazon SES Access Key
              <frontend_type>text</frontend_type>
              <sort_order>20</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>ses</option></depends>
            </ses_access_key>
            <ses_private_key translate="label comment">
              Amazon SES Secret Key
              <comment><![CDATA[Amazon SES support in SMTP Pro is limited and best suited to development and testing purposes. For a full integration with region selection, error/bounce logging and send statistics please see the premium extension: MageSend]]></comment>
              <frontend_type>password</frontend_type>
              <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
              <sort_order>23</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>ses</option></depends>
            </ses_private_key>

            <smtp_authentication translate="label">
              Authentication
              <frontend_type>select</frontend_type>
              <source_model>smtppro/system_config_source_smtp_authentication</source_model>
              <sort_order>20</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option></depends>
            </smtp_authentication>
            <smtp_username translate="label">
              Username
              <frontend_type>text</frontend_type>
              <sort_order>23</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option><smtp_authentication separator=",">login,plain,crammd5</smtp_authentication></depends>
            </smtp_username>
            <smtp_password translate="label">
              Password
              <frontend_type>password</frontend_type>
              <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
              <sort_order>26</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option><smtp_authentication separator=",">login,plain,crammd5</smtp_authentication></depends>
            </smtp_password>
            <smtp_host translate="label">
              Host
              <frontend_type>text</frontend_type>
              <sort_order>29</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option></depends>
            </smtp_host>
            <smtp_port translate="label">
              Port
              <frontend_type>text</frontend_type>
              <sort_order>32</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option></depends>
            </smtp_port>
            <smtp_ssl translate="label comment">
              SSL Security
              <comment><![CDATA[Custom SMTP servers can be configured in this section. For more information about these configuration options and troubleshooting advice please see magesmtppro.com]]></comment>
              <frontend_type>select</frontend_type>
              <source_model>smtppro/system_config_source_smtp_ssl</source_model>
              <sort_order>35</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><option>smtp</option></depends>
            </smtp_ssl>

          </fields>
        </general>

        <debug module="smtppro" translate="label comment">
          Logging and Debugging
          <frontend_type>text</frontend_type>
          <sort_order>50</sort_order>
          <show_in_default>1</show_in_default>
          <show_in_website>1</show_in_website>
          <show_in_store>0</show_in_store>
          <comment>Please only use these settings if you are a software developer or server admin.</comment>
          <fields>
            <logenabled translate="label comment">
              Log Emails
              <comment>This will log all outbound emails. View from System->Tools->SMTPPro - Email Log.</comment>
              <frontend_type>select</frontend_type>
              <source_model>adminhtml/system_config_source_yesno</source_model>
              <sort_order>40</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
            </logenabled>
            <cleanlog translate="label comment">
              Clean Email Logs
              <comment><![CDATA[If this is set to yes, old entries will be deleted from email log. Cron is required and log cleaning must be enabled in system/log/enabled for this to work.]]></comment>
              <frontend_type>select</frontend_type>
              <source_model>adminhtml/system_config_source_yesno</source_model>
              <sort_order>50</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><logenabled>1</logenabled></depends>
            </cleanlog>
            <cleanlog_after_days translate="label">
              Email Log Days Kept
              <frontend_type>text</frontend_type>
              <sort_order>60</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
              <depends><cleanlog>1</cleanlog><logenabled>1</logenabled></depends>
            </cleanlog_after_days>
            <log_debug translate="label">
              Enable Debug Logging
              <comment><![CDATA[If yes, a log file will be written with debug information.]]></comment>
              <frontend_type>select</frontend_type>
              <source_model>adminhtml/system_config_source_yesno</source_model>
              <sort_order>70</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
            </log_debug>
            <test translate="label comment">
              <comment>Save settings before running this test.</comment>
              <frontend_type>select</frontend_type>
              <frontend_model>Aschroder_SMTPPro_Block_Adminhtml_Test</frontend_model>
              <sort_order>80</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>0</show_in_website>
              <show_in_store>0</show_in_store>
            </test>
          </fields>
        </debug>
        <esp module="smtppro" translate="label">
              Compatible Email Services
              <frontend_type>text</frontend_type>
              <sort_order>70</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>1</show_in_store>
              <fields>
                  <logenabled translate="label">
                      <frontend_type>select</frontend_type>
                      <frontend_model>Aschroder_SMTPPro_Block_Adminhtml_Table</frontend_model>
                      <sort_order>40</sort_order>
                      <show_in_default>1</show_in_default>
                      <show_in_website>1</show_in_website>
                      <show_in_store>1</show_in_store>
                  </logenabled>
              </fields>
          </esp>
      </groups>
    </smtppro>
  </sections>
</config>

A: Try to flush the cache, then log out and finally log in again.


text:
Q: Is there a way to diff a line from different files? I'm currently doing some consolidation of i18n files. In some cases I have duplicate keys across multiple files, and I want to figure out if I can remove one of the duplicates.
Here's an example:
config/locales/en-primary.yml:  language_key: 'lorem ipsum'
config/locales/en-secondary.yml:  language_key: 'lorem ipsum'

Now obviously these are the same, which is easy to see in english, but things get tougher against other languages, and when the lines get longer. My current command to produce these lines is as follows:
grep language_key config/locales/en-*.yml

Is there a way to pipe those two lines into diff to compare them against each other? I can guarantee only two results for each grep'ing if that makes things easier.

A: If it's just the two files:
diff <(grep 'language_key' config/locales/en-primary.yml) <(grep 'language_key' config/locales/en-secondary.yml)

A: Variation of DopeGhoti's answer (note about support for process substitution applies here as well), this here is with a side-by-side view of differing lines:
diff -y --suppress-common-lines <(grep 'language_key' config/locales/en-primary.yml) <(grep 'language_key' config/locales/en-secondary.yml)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dataflow flex template job attempts to launch second job (for pipeline) with same job_name I am trying to launch a Dataflow flex template. As part of the build and deploy process, I am pre-building a custom SDK container image to reduce worker start-up time.
I have attempted this in these ways:

*

*When no sdk_container_image is specified and a requirements.txt file is provided, a Dataflow flex template is successfully launched and a graph is built, but the workers cannot start because they lack authority to install private packages.

*

*Errors:

*

*Dataflow job appears to be stuck; no worker activity

*Workers fail to install requirements

*When an sdk_container_image is given (with dependencies pre-installed), the Dataflow job starts, but instead of running the pipeline on the same job, it attempts to launch a Dataflow job for the pipeline using the same name, which results in an error.

*

*Errors:

*

*Duplicate Dataflow job name, DataflowJobAlreadyExistsError

*If I attempt to pass a second job_name for the pipeline, the pipeline successfully starts in a separate job, but the original flex template job eventually fails due to a polling timeout. Pipeline fails at very last step due to sdk harness disconnected because "The worker VM had to shut down one or more processes due to lack of memory."

*

*Template errors:

*

*Timeout in polling result file

*Pipeline Errors:

*

*SDK harness disconnected (Out of memory)

*When I launch the pipeline locally using DataflowRunner, the pipeline runs successfully under one job name.

Here are my Dockerfiles and gcloud commands:
Flex template Dockerfile:
FROM gcr.io/dataflow-templates-base/python39-template-launcher-base

# Create working directory
ARG WORKDIR=/flex
RUN mkdir -p ${WORKDIR}
WORKDIR ${WORKDIR}

# Due to a change in the Apache Beam base image in version 2.24, you must to install
# libffi-dev manually as a dependency. For more information:
#   https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4891
RUN apt-get update && apt-get install -y libffi-dev && rm -rf /var/lib/apt/lists/*

COPY ./ ./

ENV FLEX_TEMPLATE_PYTHON_PY_FILE="${WORKDIR}/launch_pipeline.py"

# Install the pipeline dependencies
RUN pip install --no-cache-dir --upgrade pip setuptools wheel
RUN pip install --no-cache-dir apache-beam[gcp]==2.41.0
RUN pip install --no-cache-dir -r requirements.txt

ENTRYPOINT [ "/opt/google/dataflow/python_template_launcher" ]

Worker Dockerfile:
# Set up image for worker.
FROM apache/beam_python3.9_sdk:2.41.0

WORKDIR /worker

COPY ./requirements.txt ./

RUN pip install --no-cache-dir --upgrade pip setuptools wheel
RUN pip install --no-cache-dir -r requirements.txt

Building template:
gcloud dataflow flex-template build $TEMPLATE_LOCATION \
    --image "$IMAGE_LOCATION" \
    --sdk-language "PYTHON" \
    --metadata-file "metadata.json"

Launching template:
gcloud dataflow flex-template run ddjanke-local-flex \
    --template-file-gcs-location=$TEMPLATE_LOCATION \
    --project=$PROJECT \
    --service-account-email=$EMAIL \
    --parameters=[OTHER_ARGS...],sdk_container_image=$WORKER_IMAGE \
    --additional-experiments=use_runner_v2

A: I actually managed to solve this yesterday. The problem was that I was passing sdk_container_image to Dataflow through the flex template and then passing that through to the PipelineOptions within my code. After I removed sdk_container_image from the options, it launched the pipeline in the same job.


text:
Q: $model->validate() returns true without any attribute assignments? I have a model with many attributes, I want to validate before saving it. So at some I would have only model initialization but no attribute assignments
$model=new patient();   $model->validate();

yet it returns true, I have many attributes set to required. I don't understand how does this happen?
Is there a way to validate a model before saving it even though no attributes are assigned to the model?

A: Your have validation rules but You may Miss the scenario's on validate .
Check the validators on your current object model by this
print_r($model->validatorList);

refer this link

A: You can validate a model at any time once it is created.
Let's look at the sequence of events :-
You have created a model class :
class User extends CActiveRecord
{
  ...
}

This creates a template for the patient class, which inherits from CActiveRecord, which means it has inherited functions available to it. So, while your class files does not the activate() function, it inherits it from the CActiveRecord class.
Now you create an instance of the class
$patient1 = new patient;

This means there is now some space in memory that exists for patient1. It has values. Some may be empty and some not (for example, they may have a default value).
So, at any time, you could
$model->validate();

This would change the model to include the error messages. To get the errors that have been raise, use
$allErrors = $model->getErrors()
print_r($all_errors); // This will show you the structure.

To print the errors in a neat way, use
echo CHtml::errorSummary($model);


text:
Q: How do you know if you can't go back VueJS I would like to write a method that links to the homepage if I can't go back.
a code a bit like that:
      if (**router.back.length == 0**){
         router.push({name:"Home"})
       }else {
         router.back();
       }
    }

the problem is i dont know how to tell if the .back () is possible or not.
I am currently on a pageNotFound, I go to the current page using the following redirect
    path: "/:catchAll(.*)",
    name: "PageNotFound",
    component: () =>
      import(/* webpackChunkName: "NotFound" */ "@/views/PageNotFound.vue")
  }

Thanks for your help!

A: Had similar case once. Try something like this (treat it like a pseudo code):
  data: () => ({
     fromRoute: null
  }),
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.fromRoute = from;
    })
  },
  methods: () {
    handleBack() {
      if (!this.fromRoute.name) {
        router.push({name:"Home"});
      } else {
        router.back();
      }
    }
  }

More info here: https://forum.vuejs.org/t/how-to-go-back-or-go-home/30242/3

A: Use this code to achieve the desired result. Make sure you are using [Named Routes][1].
export default {
  data() {
    return {
      fromRoute: null
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromRoute = from;
    });
  },
  methods: {
    goBack() {
      if (!this.fromRoute.name) {
        this.$router.push("/");
      } else {
        this.$router.back();
      }
    },
  },
};

  [1]: https://router.vuejs.org/guide/essentials/named-routes.html

A: By looking in the VueJs doc I found the solution
goBack() {
      if(this.$router.getRoutes().length==0){
        this.$router.push({name:"Home"})
      }else{
        this.$router.back();
      }
    }

https://router.vuejs.org/api/#router-onready


text:
Q: Grid header text not fitting when printing AdvancedDataGrid I want to print an AdvancedDataGrid , I am using this code
public function doPrint():void {
            myPrintJob = new FlexPrintJob();
            myPrintDataGrid = new PrintAdvancedDataGrid();
            myPrintDataGrid.source=this.dataGrid;
            StageReference.instance.addElement(myPrintDataGrid);

            if (myPrintJob.start()) {
                myPrintJob.addObject(myPrintDataGrid, FlexPrintJobScaleType.MATCH_WIDTH);
                myPrintJob.send();
                StageReference.instance.removeElement(myPrintDataGrid);
            }
            else
            {
                StageReference.instance.removeElement(myPrintDataGrid);

            }
        }

The problem is the headers text is using a lot of padding or something similar so the text is not fitting

If someone can give me any hints, I do not know what to look for(maybe try to create my own header renderer?)
I found the cause, FlexPrintJob.addObject scales the grid and I think the headers need some more frames untill are updated, there are some strange things in the scaling, I noticed in debug that the width was set to 200 even if the page width is 600, no real solution for now then avoiding scaling.

A: Flex label/text objects usually truncate the text if they think they don't have enough space.
I took a quick look at AdvancedDataGridHeaderRenderer and confirmed, that the renderer will set it's UITextField to truncate the text if the text is too wide and the grid's variableRowHeight property is false.
A snippet from AdvancedDataGridHeaderRenderer's commitProperties() method (line 462):
label.text = listData.label ? listData.label : " ";
label.multiline = grid.variableRowHeight;
// Get the headerWordWrap for a column, using the default wordWrap if none specified
if( _data is AdvancedDataGridColumn)
    label.wordWrap = grid.columnHeaderWordWrap(_data as AdvancedDataGridColumn);

The actual truncation happens in AdvancedDataGridHeaderRenderer's updateDisplayList() method (line 628).
Knowing this, you have some options:

*

*use the debugger to step through the code in commitProperties/updateDisplayList to see why the label objects in your headers think they need to be so small. In your screen shot, there appears to be plenty of space -- but for some reason the labels don't think so.

*override AdvancedDataGridHeaderRenderer's commitProperties/updateDisplayList methods to make it do exactly what you want

*set the grid/renderer's styles and properties to allow more width and/or multi-line text
To do the latter, you will want to do some combination of the following:

*

*use CSS to change font and other styles of AdvancedDataGridHeaderRenderer (default padding for this class is 2px)

*enable variableRowHeight for grid

*set the wordWrap property of the grid to true (only works w/variable row height)

*or control word wrapping at the column level with the headerWordWrap property of AdvancedDataGridColumn


text:
Q: If $f,g$ are respectively differentiable in neighborhoods of $a,f(a)$, when does $\lim\limits_{h\to0}\frac{g(f(a+h))-g(f(a))}{f(a+h)-f(a)}$ not exist?
If $f,g$ are respectively differentiable in neighborhoods of $a,f(a)$, when does $\lim\limits_{h\to0}\frac{g(f(a+h))-g(f(a))}{f(a+h)-f(a)}$ not exist?

Both $f$ and $g$ are $\Bbb R \to \Bbb R$. I'm thinking that the limit might not exist if $f(a+h)-f(a)$ somehow takes the value $0$ in some determinate way, but it seems to me that it isn't sufficient for the denominator to be $0$ only a couple of times as $h \to 0$, given we can easily imagine that as $h \to 0$, the denominator becomes $0$ a finite number of times and then never becomes $0$ again. Is there a precise statement about when the limit might not exist? Any tips or answers are welcome.

A: If $f$ is differntiable at $a$, $g$ is differentiable at $f(a)$ and if $f'(a) \ne 0,$ then
$$\frac{g(f(a+h))-g(f(a))}{f(a+h) - f(a)}=\frac{g(f(a+h))-g(f(a))}{h} \cdot \frac{h}{f(a+h) - f(a)} \to (g \circ f)'(a) \cdot \frac{1}{f'(a)}=g'(f(a))$$
as $h \to 0.$


text:
Q: Sending text from fragment to custom view where I want to use canvas.drawText I am new to Android and want to pass some text from a fragment to a custom view. Inside the custom view I want to use canvas.drawText to position the string. The reason I want to use canvas.drawText is for consistency with the position of some graphics.
What is the procedure for this?
Just to clarify, my fragment has something like this:
public class Fragment1 extends Fragment {

private TextView view;
private TextView txtBox;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, container,false);
    txtBox = (TextView) view.findViewById(R.id.TxtBox);
            String myString = "testing";
            txtBox.setText(myString);
    return view;
    }
}

I have a fragment_layout.xml file for View1 (my custom view):
<com.example.stuff.View1
    android:id="@+id/TxtBox"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

The call I am wish to make inside the custom view:
public class View1 extends TextView {

    //constructors:
    public View1(Context context, AttributeSet ats, int ds) {
        super(context, ats, ds);
        init();
    }

    public View1(Context context) {
        super(context);
        init();
    }

    public View1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
...
canvas.drawText(myString, margin1, margin2, paint);
....
}

...and what I want is to get myString from Fragment1.java to the View1.java.

A: You could create the com.example.stuff.View1 custom view dynamically, i.e. dont add it in the xml but add it using the code. And then you could pass the text in the constructor of the com.example.stuff.View1.
Other way could be to create a method in the com.example.stuff.View1 class and set the text there. For example
public class View1 extends TextView {

    //constructors:
    public View1(Context context, AttributeSet ats, int ds) {
        super(context, ats, ds);
        init();
    }

    public View1(Context context) {
        super(context);
        init();
    }

    public View1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setMyText(String string) {
        myString=string;
    }
...
canvas.drawText(myString, margin1, margin2, paint);
....
}

then in your code do something like this
View view = inflater.inflate(R.layout.fragment_layout, container,false);
    txtBox = (TextView) view.findViewById(R.id.TxtBox);
    String myString = "testing";
    txtBox.setMyText(myString);

A: I was able to solve the problem with the answers I received here (using setters/getters) and here (getting rid of the resulting NullPointer exception from mis-defined layout calls).


text:
Q: How to check if user validation (FormsAuthentication) was performed using cookies? I have a validation (authentication) problem within my ASP.NET application - I use FormsAuthentication with cookies enabled, however because of security reasons I am forced to ALSO use another, external source of authorization (which basing on username/password combination gives user "sessionID")
Application works fine when user logs in using his username/password credentials (thus, obtains sessionID). However, because of the cookies enabled, login page can be 'skipped' (user is redirected to default.aspx) and he wont obtain proper sessionID.
My question is whether there exists a possibility to check if user
a) came from login page (thus, has been redirected to default.aspx)
OR
b) formsAuthentication was performed basing on cookie data, not on username/password

A: Assuming you redirect to a default.aspx page once the user logs in (such that page load now includes the authentication cookie from the redirected client), you would know whether or not they're authenticated using global.asax.cs' Application_AuthenticateRequest event":
protected void Application_AuthenticateRequest(Object oSender, EventArgs eA)
{
    // Wire up authenticated principal with user information.

    if (this.Request.IsAuthenticated == true)
    {
         // do something with this.User.Identity.Name to map to a "sessionid"
    }
}

You ask about determining whether they just logged in and landed at the home as a redirected user, or they came to home (or any other view) directly using a browser-saved cookie, but I think it doesn't matter.  If you're storing a user's extra authentication key as part of processing the login, perhaps you should be doing it in the AuthenticateRequest event for all accesses of protected pages.  Note: that event gets fired for a lot (css files, images, whatever).  You may want to ignore every kind of request except .aspx ones.

A: Yes you can check what page a user came from using "request.UrlReferrer.ToString" and compare it to your login page URL.


text:
Q: Matrix Multiplication in Python Language I'm trying to do a Matrix multiplication using nested while loops for the given hard coded matrices...
The correct answer for this should be [[6,12], [15,30], [24,48]]
but the output of my code is [[6,12], [6,12], [6,12]]
what should I do?
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2],[1,2],[1,2]]
c=[]

cola=len(a)
rowa=len(a[0])
colb=len(b)
rowb=len(b[0])
r,s,t,u,sum = 0,0,0,0,0

c=[([0]*rowb)]*cola

print c

while s<cola:
    while u<rowb:
        while t<colb:
            d=a[s][t]*b[t][r]
            sum+=d
            t+=1

        c[s][r]=sum
        sum=0
        u+=1
        t=0
        r+=1

    r=0
    s+=1

print c

A: When you do -
c=[([0]*rowb)]*cola

You are just copying the inner list cola times, this is shallow copying, hence each inner list is a reference to the same object , hence when you change an element inside one of the inner lists, it affects all of the inner lists. Instead of that, try using list comprehension to create the c list.
Example -
c = [[0 for _ in range(rowb)] for _ in range(cola)]

Also, another small issue in your logic, you are using r to denote the elements from b , but in the while loop you are checking against - u , you should check against r . Example -
while s<cola:
    while r<rowb:

A: #!/usr/bin/env python
#-*- coding: utf-8 -*-

matrixA = [[1,2,3],[4,5,6],[7,8,9]]
matrixB = [[1,2],[1,2],[1,2]]
result = []

for row in range(len(matrixA)):
    rowResult = []
    for column in range(len(matrixB[0])):
        s = 0
        l = len(matrixA[row])
        for i in range(l):
            s += matrixA[row][i]*matrixB[i][column]
        rowResult.append(s)
    result.append(rowResult)

print result

I try this, it is correct.


text:
Q: Second-Order Perturbation in electron gas I was trying to figure out the solution to exercise 1.4 on Quantum theory of many particles systems by Fetter & Walecka and I read through this question and its answer. But a point made in both the answer and the question confused me a lot.
We have this $$⟨m|H_1|Φ_0⟩ = ⟨m|
a^{\dagger}_{\vec{k'}+\vec{q'},λ'_1}
a^{\dagger}_{\vec{p'}-\vec{q'},λ'_2}
a_{\vec{p'},λ'_2}
a_{\vec{k'},λ'_1}
|Φ_0⟩$$ expression and it is said that $|\vec{k'}+\vec{q'}|$ and $|\vec{p'}-\vec{q'}|$ should be above the Fermi level otherwise $⟨m|H_1|Φ_0⟩$ will be zero. My confusion is why we need   $|\vec{k'}+\vec{q'}|$ AND $|\vec{p'}-\vec{q'}|$ to be above fermi level. I think, if we have either one of them above the Fermi level and the other below, we would still get an excited state with 1 electron excited above fermi level so I feel like it should be $|\vec{k'}+\vec{q'}|$ OR $|\vec{p'}-\vec{q'}|$ above the Fermi level.
I am sorry if this is not correct question formatting but this thing is really stuck in my mind and I really need a conclusion.

A: The ground state $|\Phi_0\rangle$ is defined as a state filled up to the Fermi level, that is
$$
a_\mathbf{k}|\Phi_0\rangle=0 \text{ if } \epsilon_\mathbf{k} > \epsilon_F,\\
a_\mathbf{k}^\dagger|\Phi_0\rangle=0 \text{ if } \epsilon_\mathbf{k} < \epsilon_F.
$$
Thus, the matrix element $\langle m|a^\dagger_{\mathbf{k}+\mathbf{q}}a^\dagger_{\mathbf{p}-\mathbf{q}}a_\mathbf{p}a_\mathbf{k}|\Phi_0\rangle$ is non-zero, only if

*

*the creation operators create electrons above the Fermi surface
OR

*when either (or both) of them fills the hole created by one of the annihilation operators on the right

The process where the created holes are filled will be the essential one when you get to Wick's theorem, and calculating matrix elements $\langle \Phi_0|a^\dagger_{\mathbf{k}+\mathbf{q}}a^\dagger_{\mathbf{p}-\mathbf{q}}a_\mathbf{p}a_\mathbf{k}|\Phi_0\rangle$ (the same ground state in the bra and in the ket).
However, in the calculation you are dealing with now, there is a phase space factor: there is huge amount of states above the Fermi level, and only few possibilities to fill the two holes. Thus, these processes could be safely neglected... in fact, they disappear exactly in thermodynamic limit, where one takes $V\rightarrow +\infty$ (check in the book, that there is a volume factor in front): integration over the states above the Fermi level cancels the volume, but the contribution with filling holes vanishes as $\sim1/V$.


text:
Q: Android/Firebase Create a folder as a subfolder of a unique folder, both are created at the same time Problem: I want to add photos to the post, it partially works, but the "images" folder is created separately, instead of in a unique folder marked in green
databaseReference = FirebaseDatabase.getInstance().reference.child("posts")

private fun SendLink(url: String) {
    val hashMap: HashMap<String, String> = HashMap()
    hashMap["link"] = url
    databaseReference!!.child("images").push().setValue(hashMap).addOnCompleteListener {
        progressDialog!!.dismiss()
        choosenImages!!.text = "Succesfully added images."
        addImagesBT.visibility = View.GONE
        ImageList.clear()
    }
}

Question: How to move / create "images" folder as a subfolder of green underlined folder?

A: In Realtime Database, there are not actually any "folders".  There are just nodes that can contain child nodes.  There are no operations to "move" data between nodes.  What you can do instead is read data from a source node, write it to a destination node, then delete the original node.
If a node that you create is showing up in the wrong location, that means you should probably just change the location where it's being written.  Right now, your code is adding new child nodes to randomly generated nodes under "images".  If you want to write to "posts" instead, simply change the name of the node where you push the data.  Pay attention to how you create the Reference object that you use when you call push() - that reference will be the root node under which the new randomly generated node name will be written.


text:
Q: jar File Becomes Corrupted After Being Sent Over Socket IF It Was Sent In Pieces I have been trying to work this problem out for a few hours now, but nothing seems to help. This is a problem out of my FOV.
So basically what i'm trying to do is send a jar file over a socket. I setup my ServerSocket, wait for connection, connect to it. After connecting I setup ObjectStreams. Then I send a request from client-side for download. Server receives that message and reacts accordingly: starts a thread which sends a file over a socket to the client. It opens the file using FileInputStream, takes the length of the file in bytes. Then it sends the file in pieces of X bytes. I tried many values here. The only time I successfully send a jar file over a socket, is when I send all the bytes at once. If I send bytes 2 times, (half the first time, seconds half after it), then my sent jar file won't work anymore, it becomes corrupted.
It becomes corrupted only with some values. With others, when I try to run it, nothing happens. So I ran in in CMD and turns out I get an error:
Exception in thread "main" java.util.zip.ZipException: invalid LOC header (bad signature)
        at java.util.zip.ZipFile.read(Native Method)
        at java.util.zip.ZipFile.access$1400(Unknown Source)
        at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source)
        at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source)
        at java.util.zip.InflaterInputStream.read(Unknown Source)
        at org.ninjacave.jarsplice.JarSpliceLauncher.extractNatives(JarSpliceLauncher.java:140)
        at org.ninjacave.jarsplice.JarSpliceLauncher.<init>(JarSpliceLauncher.java:63)
        at org.ninjacave.jarsplice.JarSpliceLauncher.main(JarSpliceLauncher.java:234)

So my question is this: do objects sent over a socket get modified in some way or what? Because all the things in my sent file are present, but it doesn't seem to launch properly or gets corrupted. + I have run out of moves.. If you want to see code I can show it.
Ok. Code for breaking into pieces.
public void run() {

        FileInputStream fileStream = null;

        try {
            fileStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        long length = file.length(), done = 0;
        byte[] buffer = new byte[step];

        try {

            int counter = 0;

            while(done + step < length) {
                fileStream.read(buffer);
                output.writeObject(new Data(buffer, counter));
                done+=step;
                counter+=1;
            }

            int last = (int)(length - done);
            byte[] lastBuffer = new byte[last];
            fileStream.read(lastBuffer);
            output.writeObject(new Data(lastBuffer, counter));

            output.writeObject(new Message(null, Message.SEND_COMPLETED));
        }catch(IOException e) {
            e.printStackTrace();
            return;
        }

        try {
            fileStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

Gluing the file back:
obj = in.readObject();
if(obj instanceof Data) {
   Data dat = (Data)obj;
   fileWriter.write(dat.buffer);
}

Data class:
package act;

import java.io.Serializable;
public class Data implements Serializable{
/**
 *
 */
private static final long serialVersionUID = 3070641500586981886L;
public byte[] buffer;
public int counter = 0;

public Data(byte[] buffer, int counter) {
    this.counter = counter;
    this.buffer = buffer;
}

}
Here is some kind of "example" program I made for myself to see if my program actually works without networking. And it does.
public static void main(String args[]) {

    File fileSource = new File("tosend.jar");
    File fileDest = new File("C:/Users/Chris/Desktop/downloader/Testing/dest/dest.jar");

    try {

        FileInputStream in = new FileInputStream(fileSource);

        FileOutputStream out = new FileOutputStream(fileDest);

        long length = fileSource.length(), done = 0;
        int step = 1000;
        byte[] buffer = new byte[step];

        while(done + step < length) {
            in.read(buffer);
            out.write(buffer);
            done+=step;
        }

        int last = (int)(length - done);
        buffer = new byte[last];
        in.read(buffer);
        out.write(buffer);

        in.close();
        out.close();

        System.out.println("Writing compleete!");
    }catch(IOException e) {
        e.printStackTrace();
    }

A: You have the usual problem. You are ignoring the result of the read() method. Try this, at both ends:
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

No need for Object streams at all. This works with any size buffer > 0.


text:
Q: Tensor flow and RandomShuffleQueue "insufficient elements (requested 64, current size 0)" I currently playing around with tensorFlow, and even thoughthe tutorials were kinda simple to complete, the true work starts when we try to input our own datas.
I used a very basic dataset composer of animals and background.
I created 3 tfrecords (train/val/test).
I then attempt to read them and to train a simple model (Alexnet here).
I tried to use the "FLAGS.num_iter" to be sure i'm not out the iteration range.
This code processing  get me a nice  RandomShuffleQueue  "insufficient elements (requested 64, current size 0)" error.
I tried to dig the web but i found no answer to my questions. Here they are: How do we fix this ? How can we check if our tfrecord contain any mistakes? Can we write any condition to ensure that we have enough elements?
If You have any further question on my code, I stay around!
Best regards,
import tensorflow as tf
import os.path
from model import Model
from alexnet import Alexnet

FLAGS = tf.app.flags.FLAGS
NUM_LABELS = 2

IMAGE_WIDTH = 64
IMAGE_HEIGHT = 64
NUMBER_OF_CHANNELS = 3
#SOURCE_DIR = './data/'
#TRAINING_IMAGES_DIR = SOURCE_DIR + 'train/'
#LIST_FILE_NAME = 'list.txt'
BATCH_SIZE = 2
#TRAINING_SET_SIZE = 81112
TRAIN_FILE = '/home/sebv/SebV/datas/tfRecording/train.tfrecords'
VAL_FILE = '/home/sebv/SebV/datas/tfRecording/val.tfrecor'

def read_and_decode(filename_queue):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        # Defaults are not specified since both keys are required.
        features={
          'image/encoded': tf.FixedLenFeature([], tf.string),
          'image/format': tf.FixedLenFeature([], tf.string),
          'image/class/label': tf.FixedLenFeature([], tf.int64),
          'image/height': tf.FixedLenFeature([], tf.int64),
          'image/width': tf.FixedLenFeature([], tf.int64),
        })

    # Convert from a scalar string tensor (whose single string has
    # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape
    # [mnist.IMAGE_PIXELS].
    image = tf.image.decode_png(features['image/encoded'], 3, tf.uint8)

    # OPTIONAL: Could reshape into a 28x28 image and apply distortions
    # here.  Since we are not applying any distortions in this
    # example, and the next step expects the image to be flattened
    # into a vector, we don't bother.

    # Convert from [0, 255] -> [-0.5, 0.5] floats.
    image = tf.cast(image, tf.float32)# * (1. / 255) - 0.5
    image = tf.reshape(image, [IMAGE_WIDTH,IMAGE_HEIGHT,NUMBER_OF_CHANNELS])
    # Convert label from a scalar uint8 tensor to an int32 scalar.
    label = tf.cast(features['image/class/label'], tf.int64)

    return image, label

def inputs(train, filen, batch_size, num_epochs):
    """Reads input data num_epochs times.
    Args:
    train: Selects between the training (True) and validation (False) data.
    batch_size: Number of examples per returned batch.
    num_epochs: Number of times to read the input data, or 0/None to
    train forever.
    Returns:
    A tuple (images, labels), where:
    * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
    in the range [-0.5, 0.5].
    * labels is an int32 tensor with shape [batch_size] with the true label,
    a number in the range [0, mnist.NUM_CLASSES).
    Note that an tf.train.QueueRunner is added to the graph, which
    must be run using e.g. tf.train.start_queue_runners().
    """
    if not num_epochs: num_epochs = None
    filename = filen
    filename_queue = tf.train.string_input_producer([filename], num_epochs=num_epochs)

    # Even when reading in multiple threads, share the filename
    # queue.
    image, label = read_and_decode(filename_queue)
    # Shuffle the examples and collect them into batch_size batches.
    # (Internally uses a RandomShuffleQueue.)
    # We run this in two threads to avoid being a bottleneck.
    images, sparse_labels = tf.train.shuffle_batch([image, label], batch_size=batch_size, num_threads=2,capacity=20000 + 3 * batch_size,min_after_dequeue=20000)
    sparse_labels = tf.reshape(sparse_labels, [batch_size])
    return images, sparse_labels

def train():
    model = Alexnet()
    with tf.Graph().as_default():

        x = tf.placeholder(tf.float32, [None, IMAGE_WIDTH,IMAGE_HEIGHT,NUMBER_OF_CHANNELS], name='x-input')
        y = tf.placeholder(tf.float32, [None], name='y-input')

        images, labels = inputs(train=True, filen=TRAIN_FILE, batch_size=FLAGS.batch_size,num_epochs=FLAGS.num_iter)

        images_val, labels_val = inputs(train=False, filen=VAL_FILE, batch_size=FLAGS.batch_size,num_epochs=1)

        keep_prob = tf.placeholder(tf.float32, name='dropout_prob')
        global_step = tf.contrib.framework.get_or_create_global_step()

        logits = model.inference(images, keep_prob=keep_prob)
        loss = model.loss(logits=logits, labels=labels)

        accuracy = model.accuracy(logits, labels)
        summary_op = tf.summary.merge_all()
        train_op = model.train(loss, global_step=global_step)

        saver = tf.train.Saver()

        with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
            writer = tf.summary.FileWriter(FLAGS.summary_dir, sess.graph)
            sess.run(tf.global_variables_initializer())
            sess.run(tf.local_variables_initializer())
            coord = tf.train.Coordinator()
            threads = tf.train.start_queue_runners(sess=sess, coord=coord)
            for i in xrange(FLAGS.num_iter):
                _, cur_loss, summary = sess.run([train_op, loss, summary_op],
                                                feed_dict={keep_prob: 0.5})
                writer.add_summary(summary, i)

                if i % 10 == 0:

                    batch_x = sess.run(images_val)
                    batch_y = sess.run(labels_val)
                    validation_accuracy = accuracy.eval(feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
                    print('Iter {} Accuracy: {}'.format(i, validation_accuracy))
                    saver.save(sess, FLAGS.checkpoint_file_path, global_step)
                if i == FLAGS.num_iter:
                    coord.request_stop()
                    coord.join(threads)

def main(argv=None):
    train()

if __name__ == '__main__':
    tf.app.flags.DEFINE_integer('batch_size', 64, 'size of training batches')
    tf.app.flags.DEFINE_integer('num_iter', 4001, 'number of training iterations') #10000
    tf.app.flags.DEFINE_string('checkpoint_file_path', 'checkpoints/model.ckpt-10000', 'path to checkpoint file')
    tf.app.flags.DEFINE_string('train_data', 'data', 'path to train and test data')
    tf.app.flags.DEFINE_string('summary_dir', 'graphs', 'path to directory for storing summaries')

    tf.app.run()

A: Using the queue runner API for I/O is deprecated. Instead, I recommend using tf.data API. Here is a detailed example of an input function for AlexNet data that can be used along with an Estimator:
def input_fn(params):
  """Passes data to the estimator as required."""

  batch_size = params["batch_size"]

  def parser(serialized_example):
    """Parses a single tf.Example into a 224x224 image and label tensors."""

    final_image = None
    final_label = None
    if FLAGS.preprocessed:
      features = tf.parse_single_example(
          serialized_example,
          features={
              "image": tf.FixedLenFeature([], tf.string),
              "label": tf.FixedLenFeature([], tf.int64),
          })
      image = tf.decode_raw(features["image"], tf.float32)
      image.set_shape([224 * 224 * 3])
      final_label = tf.cast(features["label"], tf.int32)
    else:
      features = tf.parse_single_example(
          serialized_example,
          features={
              "image/encoded": tf.FixedLenFeature([], tf.string),
              "image/class/label": tf.FixedLenFeature([], tf.int64),
          })
      image = tf.image.decode_jpeg(features["image/encoded"], channels=3)
      image = tf.image.resize_images(
          image,
          size=[224, 224])
      final_label = tf.cast(features["image/class/label"], tf.int32)

    final_image = (tf.cast(image, tf.float32) * (1. / 255)) - 0.5

    return final_image, final_label

  file_pattern = os.path.join(FLAGS.data_dir, "train-*")
  dataset = tf.data.Dataset.list_files(file_pattern)

  if FLAGS.filename_shuffle_buffer_size > 0:
    dataset = dataset.shuffle(buffer_size=FLAGS.filename_shuffle_buffer_size)
  dataset = dataset.repeat()

  def prefetch_map_fn(filename):
    dataset = tf.data.TFRecordDataset(
        filename, buffer_size=FLAGS.dataset_reader_buffer_size)
    if FLAGS.prefetch_size is None:
      dataset = dataset.prefetch(batch_size)
    else:
      if FLAGS.prefetch_size > 0:
        dataset = dataset.prefetch(FLAGS.prefetch_size)
    return dataset

  if FLAGS.use_sloppy_interleave:
    dataset = dataset.apply(
        tf.contrib.data.sloppy_interleave(
            prefetch_map_fn, cycle_length=FLAGS.cycle_length))
  else:
    dataset = dataset.interleave(
        prefetch_map_fn, cycle_length=FLAGS.cycle_length)

  if FLAGS.element_shuffle_buffer_size > 0:
    dataset = dataset.shuffle(buffer_size=FLAGS.element_shuffle_buffer_size)

  dataset = dataset.map(
      parser,
      num_parallel_calls=FLAGS.num_parallel_calls).prefetch(batch_size)

  dataset = dataset.batch(batch_size)
  dataset = dataset.prefetch(1)
  images, labels = dataset.make_one_shot_iterator().get_next()
  return (
      tf.reshape(images, [batch_size, 224, 224, 3]),
      tf.reshape(labels, [batch_size])
  )

You can learn more about the tf.data API in this programmer's guide.

A: I actually figured out why i get this error.
In fact, some of the images i was sending were not sized 64*64. therefore they couldn't be reshaped as 1 64 64 3. I don't know why there was no error here and I only get it on the shuffle image.
I've put an image resize before the reshape and it's all good now!
Also, thanks jsimsa i'll note that for later!


text:
Q: How do I log controller and action details? Using ASP.NET MVC 4 RTW, how do I log MVC controller actions and parameters to a database? I'd like to audit user actions but don't really want to duplicate a bunch of code inside every controller or, even worse, inside every action. Is there something i can implement globally?
I understand the EF / database side of things so this is really about MVC.

A: You should look at Custom Action Filters. Good MSDN article here http://msdn.microsoft.com/en-us/library/dd381609(v=vs.100).aspx
The filterContext.ActionDescriptor.ActionName would give you the name of the action to log, also the filterContext.ActionDescriptor.ControllerDescriptor.ControllerName will probably help and the parameters are held in filterContext.ActionParameters
These filters can be applied globally for all actions in the config Global.asax or in the App_Start folder under FilterConfig via.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new LoggingFilterAttribute());
}

Example Code for Attribute
public class LoggingFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
            filterContext.ActionDescriptor.ActionName);

        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Exception != null)
            filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");

        base.OnActionExecuted(filterContext);
    }
}


text:
Q: How is scheduling handled in C++17 STL parallel algorithms? Is there a standard scheduler specification for the C++17 STL parallel algorithms or is it entirely implementation dependant? The serial algorithms have complexity guarantees but the scheduler implementation is critical for performance with non uniform task loads, does the specification address this? It seems like it would be hard to guarantee cross-platform performance without a standardized scheduler.

A: As far as I can tell from the wording, such details are completely within the domain of implementation specification, as one would expect. The standard generally makes no effort to guarantee absolute performance of any kind, only complexity requirements, as you're seeing in this case.
Ultimately, though your source code can now take advantage of parallelism while being completely standard-defined, the actual practical outcome of running your program is up to your implementation, and I think that still makes sense. The goal of standardising features is not cross-platform performance, but portable code that can be proven correct in a vacuum.
I'd expect your toolchain to give further information on how this sort of thing works, and that may even influence your choice of toolchain! But it does make sense for them to have freedom in that regard, as they do in other areas. After all, there is a multitude of target platforms out there (theoretically infinite), all with their own potential and quirks.
It could be that a future standard emplaces further constraints on scheduling in order to kick implementers up the backside a little, but personally I wouldn't count on it.

A: Scheduling for C++17 STL algorithms is implementation-defined.
Moreover, C++17 doesn't guarantee parallel execution. It just allows parallelism.

The class execution::parallel_policy is an execution policy type used
  as a unique type to disambiguate parallel algorithm overloading and
  indicate that a parallel algorithm's execution may be parallelized


text:
Q: UDP Broadcast sendto failed:"network is unreachable" on linux 2.6.30 I write a program using udp broadcast.Code segment as follows:
struct sockaddr_in broadcast_addr;
socklen_t sock_len=sizeof(broadcast_addr);

bzero(&broadcast_addr,sock_len);
broadcast_addr.sin_family=AF_INET;
broadcast_addr.sin_port=12345;
broadcast_addr.sin_addr.s_addr=inet_addr("255.255.255.255");

int fd=socket(AF_INET,SOCK_DGRAM,0);
int broadcast_enable=1;
setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&broadcast_enable,sizeof(broadcast_enable));

uint8_t send_buf[100];
int ret=sendto(fd,send_buf,sizeof(send_buf),0,
       (struct sockaddr*)&broadcast_addr,sock_len);

 if(ret==-1)
    perror("sendto failed");

output:
sendto failed: Network is unreachable

But when I run "add default gateway" command like " route add default gw 10.10.10.111 ",the error disappears.When setting a new ipaddress to netdev,command as above should be ran,otherwise the error comes. Why? Thanks.

A: Not sure why 255.255.255.255 isn't working for you. However, I've never used that as a broadcast IP myself. When I send a broadcast packet I usually derive the broadcast IP from my subnet mask, i.e. if your subnet mask is 255.255.255.0 (/24) and say your IP is 192.168.0.5, then to send a UDP broadcast your destination IP should be 192.168.0.255.


text:
Q: Get ID from closest feature in different layer ArcGIS Collector (Android)
ArcGIS Online

Scenario:
Users create and update features in a point FC via Collector.
Upon creation/update, I want Collector to:

*

*Automatically get the ASSET_ID value from the closest feature in a line FC.

*Insert the value from the line FC into an ASSET_ID field in the points FC.

What would it take to configure ArcGIS Collector to automatically perform a spatial operation like this?

A: Since you can't extend or customize Collector itself:

*

*Maybe using a SOI (Server Object Interceptor) to intercept the point feature add/update event, then execute some custom code such as the Near() geoprocessing method to return the closest line feature.

*Have some sort of SQL trigger, to calculate the nearest line using the built-in spatial functions of the database.

A: Use Smart Edit Widget in ArcGIS Online Web Application builder


text:
Q: can you edit audio to play different amounts of sound through the 2 speakers of headphones using JavaScript or html5 Holophonic sound is when a sound is played through headphone with more or less sound in one ear or the other to mimic real sound you hear in real life. With this you can feel like you can actual put a place to where it sounds like its coming from. I was wondering if I could mimic this and edit how much sound comes out of the left and right speaker with different sounds using JavaScript or html 5. If their is another language I would have to learn please tell us what it is. If you can use JavaScript and/or html 5 tell me where I should look to learn it. Thank you for your answer.

A: The answer is Yes. If it can be programmed in JavaScript it will be programmed in JavaScript. Also HTML5 would probably play a role with the Audio tag. Both work together to create the interaction.
JavaScript is a very powerful language and it is the most popular open source community at the moment. What that means is there is a large variety of modules to choose from. So you need a tool.
STEP #1: Use tools like NPM or GitHub. My first step for such a question would be to search for your key words on NPM like this:
https://www.npmjs.com/search?q=binaural+holophonic+stereo

Or GitHub and Bower:
    https://github.com/search?utf8=%E2%9C%93&q=binaural+holophonic+stereo
http://bower.io/search/?q=binaural%20holophonic%20stereo
STEP #2: See what is out there...
Surprisingly GitHub and Bower did not return results, but NPM did.

It looks like there are some good things there...

    - web-audio-school
    - audiosynth
    - augiobugger
    - sink

STEP #3 Does it fit you requirements?
The next step is to hit the readme files of each to see if these libraries have the holophonic capabilities that you need.
STEP #4: But fret not if is doesn't exist.
Because of Atwoods Law - everything that can be written in JavaScript, will be written in JavaScript.
At least that is the trend we see is proving itself over the years. I personally know a group of computer music hackers in my city. And I can guarantee that if it has not been done - this is the type of thing that they are looking out for to solve.
OVERVIEW
So, if it is possible (which it sounds like it is) - then rest with some sense of inevitability, that it will turn up on NPM, eventually. And if not - it is you that has the pleasure of creating it, once you've mastered JavaScript modularization methodology. I've seen a few of these technologies surface now through NPM and the like. Web Audio is a specific area of advancement, which you can be on look out for impact with ES6. , WebWorkers might help you eventually.
TECHNICALLY:
Diving in technically - if a library does not exist. It sounds like what is required is - JS interoperability with the headphone hardware interface. Which increasingly is a capability of JS. But you may be slightly ahead of the curve here. It is possible, but the key word that would be missing if it does not exist is - interoperability. The need would be for JS to hardware interface interoperability... Which, by the way, is exactly what JS does really wel. So in concept yes this is reasonable. In implementation - I can't say. It requires a search.
SEARCHING JAVASCRIPT AUDIO API VOLUME (gives great results):
This one from CreativeJS is highly recommended. Start here (study it):
http://creativejs.com/resources/web-audio-api-getting-started/
And of course MDN is always best otherwise:
https://developer.mozilla.org/en-US/docs/Web/API/AudioChannels_API/Using_the_AudioChannels_API
This looks important (though maybe related indirectly):
http://codetheory.in/controlling-the-volume-of-an-audio-file-in-javascript/
And of course StackOverflow has a great link (maybe similar, with clues):
Correct audio volume output decibels using HTML5 / javascript, turn off pre-processing
In conclusion to your question:

*

*Yes Definitely learn JavaScript.

*But also learn the command line tools - bc they get u what u want.

*Git, NPM, Bower...

All in all, even if you don't finish your holophonic proof of concept - you are learning valuable professional skills. JavaScript is a ripe ecosystem for a hobby deep-dive into Web Audio capabilities. It is a great idea - and if nothing exists... it is up to you to become the creator that gives it to the open-source world.


text:
Q: Socket.Bind then connect on MS Loopback NIC I have created a loopback Interface card in Windows 7 x64
say the IP of my local machine is
20.200.20.30 /
255.255.255.128
and the IP of Loopback adapter is
20.200.20.65 / 255.255.255.128
I open up a listening socket on 20.200.20.30 on port 7800
On another thread/applciation i bind a socket on 20.200.20.65 and then connect 20.200.20.30
but it fails with connection time out.
It worked well on windows XP though.
Please advise

A: Binding the outbound socket to the loopback address and then trying to connect it to a non-loopback address doesn't make any sense. Just skip the bind step. There's very little reason to ever do this outside VPNs, which this is not.

A: Done.
All i had to do was to enable weakhost for both the NICs
netsh interface ipv4 set interface "MainNIC" weakhostsend=enabled
netsh interface ipv4 set interface "MainNIC" weakhostreceive=enabled
netsh interface ipv4 set interface "LoopbackNIC" weakhostsend=enabled
netsh interface ipv4 set interface "LoopbackNIC" weakhostreceive=enabled


text:
Q: regex to check title im competly new with regex. I have a string (javascript) and i want to check if that string contains at least 3 characters from a-z or A-Z, excluding all others characters.
I dont even know the function to check regex on a string....
Im trying to learn how to use it, but i need the expresion and function by today
thx everyone

A: For any 3 a-z or A-Z characters anywhere in the string, you could use the regex .*[a-zA-Z].*[a-zA-Z].*[a-zA-Z] .
var testString = '09A9j0k';
var regExp = /.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z]/g;
var matches = testString.match(regExp);
if(matches)
{
 //Do Something
}

A: Easy:
var s = "your string";
if(s.match(/(.*[A-Za-z]){3,}/))
{
   // 3 or more
}

If you want to test for more, just replace the 3 with whatever number you want.

A: Try this:
var testString = '09A9j0k';
var regExp = /[a-zA-Z]/g;
var matches = testString.match(regExp);
if(matches && (matches.length >= 3))
{
 //Do Something
}

Other option is to use replace and count the length:
    var testString = '09A9j0k';
    var regExp = /[^a-zA-Z]/g;
    if(testString.replace(regExp, "").length >= 3)
    {
     //Do Something
    }


text:
Q: Can SciPy's linprog handle larger numbers? I need to solve linear programs with numbers of sizes up to 1010. But linprog from the scipy.optimize library tells me that such programs are infeasible. As an easy example, the program

minimize c + d
s.t. c + 2d > 1010

is
linprog([1, 1], [[-1, -2]], [-10**10])

This outputs
    con: array([], dtype=float64)
    fun: 645172208.8069017
message: 'The algorithm terminated successfully and determined that the problem is infeasible.'
    nit: 2
  slack: array([-9.03223975e+09])
 status: 2
success: False
      x: array([3.22584169e+08, 3.22588040e+08])

It is supposed to output x: array([0, 0.5e+10]), in the last line. Can I make it handle larger numbers?


text:
Q: C++ Why Sendmessage doesnt work? In C#, this SendMessage function raise up volume successfull:
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

SendMessage(Handle, 0x319, (int)Handle, APPCOMMAND_VOLUME_UP);

But in C++, this SendMessage function dont work, that is volume doesnt rise up:
// HWND hwnd = CreateWindow(...
SetWindowText(hwnd, "Hi"); // Worked
SendMessage(hwnd, WM_APPCOMMAND, (int)hwnd, APPCOMMAND_VOLUME_UP); // Don't work

What do I wrong? Can you help me how to fix it? Thank you!
Full code:
#include <windows.h>
HHOOK _hhook;
HWND hwnd;
HINSTANCE _hInstance;

KBDLLHOOKSTRUCT kbdStruct;

LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        if (wParam == WM_KEYDOWN)
        {
            // lParam is the pointer to the struct containing the data needed, so cast and assign it to kdbStruct.
            kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
            // a key (non-system) is pressed.
            if (kbdStruct.vkCode == VK_F1)
            {
                // F1 is pressed!
                SetWindowText(hwnd, "Hi");
                SendMessage(hwnd, WM_APPCOMMAND, (WPARAM)hwnd, APPCOMMAND_VOLUME_UP);
                //MessageBox(NULL, "F1 is pressed!", "key pressed", MB_ICONINFORMATION);
            }
        }
    }
    return CallNextHookEx(_hhook, nCode, wParam, lParam);
}

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
    WNDCLASS wc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
    wc.hCursor = LoadCursor( NULL, IDC_HAND );
    wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
    wc.hInstance = hInstance;
    wc.lpfnWndProc = WndProc;
    wc.lpszClassName = TEXT("Philip");
    wc.lpszMenuName = 0;
    wc.style = CS_HREDRAW | CS_VREDRAW;

    RegisterClass( &wc );
    hwnd = CreateWindow(
        TEXT("Philip"),
        TEXT("Hello World!"),
        WS_OVERLAPPEDWINDOW,
        10, 10,
        500, 200,
        NULL, NULL,
        hInstance, NULL );

    ShowWindow(hwnd, iCmdShow );
    UpdateWindow(hwnd);

    _hhook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0);

    MSG msg;
    while( GetMessage( &msg, NULL, 0, 0 ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(   HWND hwnd,
                            UINT message,
                            WPARAM wparam,
                            LPARAM lparam )
{

    switch( message )
    {

    case WM_DESTROY:
        PostQuitMessage( 0 ) ;
        return 0;
        break;

    }
    return DefWindowProc( hwnd, message, wparam, lparam );
}

A: You need to use MAKELPARAM macro to pass APPCOMMAND_VOLUME_UP to SendMessage MAKELPARAM(0,APPCOMMAND_VOLUME_UP)
Final version should look like
SendMessage(hwnd, WM_APPCOMMAND, (WPARAM)hwnd, MAKELPARAM(0,APPCOMMAND_VOLUME_UP));

A: After some investigation I was able to get this working. The problem stems from passing an improperly formed lParam value. The command itself resides in the upper 16 bits of the value but you are not accounting for this. The following change should get you on your way:
SendMessage(hwnd, WM_APPCOMMAND, (WPARAM)hwnd, APPCOMMAND_VOLUME_UP << 16);


text:
Q: Using pulsed power source and capacitors for driving solenoids I'm converting a reed organ to be MIDI controlled, and I'm using solenoids to pull down on the keys. There's 88 solenoids total, and I'm going to be powering it with 2x 40A 12V power supplies.
The solenoid control circuit I'm using is this:

My problem is that each solenoid draws around 1.3A @ 12V. This results in very hot solenoids after less than a minute of being held down.
There are clever solenoid driver circuits that use a capacitor to give the solenoid the full power at first, then once the capacitor is charged (therefore no longer conducting DC power), power flows through a resistor that limits the current. However, this system needs time for the capacitor to discharge before being triggered again, and the capacitor has to be of a large value which would not work in this application well (my solenoid driver board design is dense enough at the moment... I want my component count to stay as low as possible). There are more complex circuits that get around the capacitor discharge problem using transistors and even more components (how they work is besides the point here) but again, I don't want many more components since every component gets multiplied by 88 circuits.
However, I think I have an idea for a solution, but I don't know if it would work. My idea is to PWM the raw power going into (all of) the existing circuits and then adding a single capacitor in parallel with my solenoid, like this:

Thus, when the MOSFET was triggered, this capacitor would get charged to 12V before discharging into the solenoid, making it fire. Now that the solenoid is down, the PWM power (lets say its 50% duty cycle, therefore equal to 6V) can keep it held down.
Is this idea completely flawed? If it is, any ideas? Thanks.

A: The principle of PWM drive is basically sound, but not as you've drawn it.
That shunt capacitor you've shown is either not necessary, or is not sufficient. In either case, you don't want it connected to the FET drain.

simulate this circuit – Schematic created using CircuitLab
If those solenoids are laminated, ie designed for DC or AC excitation, then they can work with rapidly changing DC, and you don't need the capacitor at all, as shown in the lefthand diagram. The PWM frequency will be fairly tightly constrained. It must be a) fast enough to keep the solenoids pulled in without chattering/buzzing and b) slow enough for the solenoid laminations to not overheat. This may limit you to a 100Hz or few 100Hz PWM, which may cause an audible buzzing problem.
Your capacitor will store the rail voltage when the FET is on, and drive the solenoid at more or less full power regardless of the PWM duty cycle, so should be removed. The solenoid current will be continuous due to its own inductance. When the FET is off, inductor current will continue to flow through the shunt diode.
If the solenoids are not laminated, or buzzing as mentioned above turns out to be a problem, then they must be fed clean(ish) DC, as in the righthand diagram. The inductor and capacitor will act as a filter. The diode D2 is still required to supply the inductor current when the FET is off. This is not a SMPS, so the DC to the solenoid does not need to be clean to mV.
This allows a wider choice of PWM frequency, as the solenoid is not seeing the switching frequency directly. Something much higher, like 25kHz, would be appropriate. Being above 20kHz, you won't have to worry about audibility, and it would use much smaller filter components than 100s Hz.
As you have total control over the PWM, you could arrange for the switching across the mulitple channels to be out of phase, so reduce the peak current drawn when there are multiple keys driven.

A: Not a complete solution, I'm afraid, but these might give some food for thought.

simulate this circuit – Schematic created using CircuitLab
Figure 1. (a) Solenoid switch contact opens when pulled in to add series resistance. (b) Large capacitor provides pull-in current while resistor provides hold-on current.

*

*1.3 A solenoid current at 12 V means solenoid resistance is about 9 Ω.

*If a normally closed solenoid contact is available the circuit of Figure 1a might provide a simple solution. Full voltage is available to the solenoid initially. When it pulls in SW1 opens and a holding current is provided by R1. Assuming that about half current should hold it in then 9 or 10 Ω would reduce the current to half and the power to 1/4.

*A variation on your capacitor theme is to provide each solenoid with a pull-in capacitor as shown in Figure 1b. The problem is that your solenoid resistance is so low that a very large capacitor is required to supply the current. For a 0.1 s pulse we can work out from the RC time constant that \$ C = \frac {\tau}{R} = \frac {0.1}{10} = 10\;mF\$. When the solenoid is switched off C1 would be 95% charged in 3τ = 0.3 s. This may not be quick enough for your musical tastes. The big problem is the size of the capacitors.

*Figure 1c is a variation on b and the idea is to use a transistor to buffer the pulse timer formed by R4 and C2. R5, D1 and D2 prevent the solenoid voltage dropping below 6 V and point A could feed 'D2' on a group of notes. (I would probably be better to use a decent voltage regulator for this rather than the Zener arrangement I've sketched.) The advantage is 100 x smaller capacitor size but the trade-off is the additional components and heatsinking for the transistor. (6 V x 0.65 A = 3.9 W.) I haven't thought this through and there are a few problems such as the initial voltage drop across Q1.

simulate this circuit
Figure 2. A version to test on the simulator.
The Darlington transistor improves the amplification of the voltage follower further reducing the value and size of C2. V1 has been raised to 14 V to overcome the Darlington voltage drop.

Figure 3. Simulation time response.
You need to play around with the values to suit your requirements.


text:
Q: How to right align some elements of WPF ListItem? I have a WPF listbox and have updated the list item data template to have essentially a 3 column layout.
I would like:
|status color|name|        buttons|
These are probably CSS terms but I want to float the status color and name to the left, which I've done, then I would like the buttons to be floated to the right, and always stay to the right even as the window gets wider.
I feel like I'm so close, the list item widths grow when the window gets wider, all I feel I have to do is tell the buttons to float right but can't figure out how. I've tried stack panels, a grid with a auto|*|auto column layout (With a stretch on the last column) and I've tried a dockpanel.
Here's my XAML:
    <Controls:MetroWindow x:Class="Appsecute.Views.MainView2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        xmlns:AppsecuteControls="clr-namespace:Appsecute.Controls"
        Title="APPSECUTE" Height="630" Width="480" Icon="/Appsecute;component/Images/icon.png" WindowStartupLocation="CenterScreen">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedSingleRowTabControl.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro.Resources;component/Icons.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid Margin="0,0,12,0">
        <AppsecuteControls:NotifyIcon
            x:Name="NotifyIcon"
            Text="Appsecute"
            Icon="/Images/icon.ico" MouseDoubleClick="NotifyIconMouseDoubleClick" Grid.ColumnSpan="2">
            <AppsecuteControls:NotifyIcon.ContextMenu>
                <ContextMenu StaysOpen="False">
                </ContextMenu>
            </AppsecuteControls:NotifyIcon.ContextMenu>
        </AppsecuteControls:NotifyIcon>

        <Grid Height="auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="auto" Margin="12,0,0,24">
            <Grid.RowDefinitions>
                <RowDefinition Height="auto" />
                <RowDefinition Height="*" />
                <RowDefinition Height="auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <Label Content="APPLICATIONS" Height="auto" Name="LabelApplications" Grid.Row="0" Padding="2" Margin="0,8,0,0" VerticalAlignment="Top" />
            <ListBox Height="auto" Name="ListBoxApplications" Width="auto" Grid.Row="1" Grid.ColumnSpan="3" Focusable="False" Background="White" BorderBrush="{x:Null}" SelectionChanged="ListBoxApplicationsSelectionChanged">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
                        <Setter Property="Padding" Value="0"></Setter>
                        <Setter Property="Background" Value="#EEEEEE"></Setter>
                        <Setter Property="BorderBrush" Value="White"></Setter>
                        <Setter Property="BorderThickness" Value="0,0,0,2"></Setter>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="BorderBrush" Value="#FF4EA6EA"></Setter>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>

                            <StackPanel Grid.Column="0" Orientation="Horizontal">
                                <Rectangle Fill="{Binding StateColor}" Width="5" Height="auto" Margin="0,0,5,0"></Rectangle>
                                <StackPanel Orientation="Vertical">
                                    <StackPanel Orientation="Horizontal" Margin="0,4,0,0">
                                        <TextBlock Text="{Binding DisplayName}" FontSize="20" Padding="2" />
                                    </StackPanel>
                                    <StackPanel Orientation="Horizontal" Margin="0,4">
                                        <TextBlock Text="{Binding CloudName}" FontSize="12" Foreground="#FF666666" />
                                        <TextBlock Text=" - " FontSize="12" Foreground="#FF666666" />
                                        <TextBlock Text="{Binding Username}" FontSize="12" Foreground="#FF666666" />
                                    </StackPanel>
                                </StackPanel>
                            </StackPanel>

                            <DockPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right">
                                <Button Background="{x:Null}" BorderBrush="{x:Null}" Focusable="False" Tag="{Binding}" Name="ButtonUpload" ToolTip="Upload Application" Click="ButtonUploadClick">
                                    <StackPanel>
                                        <Image Width="24" Height="24" Source="/Appsecute;component/Images/upload.png"/>
                                    </StackPanel>
                                </Button>
                                <Button Background="{x:Null}" BorderBrush="{x:Null}" Focusable="False" Tag="{Binding}" Name="ButtonStart" Click="ButtonStartClick" ToolTip="Start Application" IsEnabled="{Binding IsStopped}">
                                    <StackPanel>
                                        <Image Width="24" Height="24" Source="/Appsecute;component/Images/play.png" />
                                    </StackPanel>
                                </Button>
                                <Button Background="{x:Null}" BorderBrush="{x:Null}" Focusable="False" Tag="{Binding}" Name="ButtonStop" ToolTip="Stop Application" Click="ButtonStopClick" IsEnabled="{Binding IsStarted}">
                                    <StackPanel>
                                        <Image Width="24" Height="24" Source="/Appsecute;component/Images/stop.png"/>
                                    </StackPanel>
                                </Button>
                                <Button Background="{x:Null}" BorderBrush="{x:Null}" Focusable="False" Click="ButtonRestartClick" Tag="{Binding}" Name="ButtonRestart" ToolTip="Restart Application">
                                    <StackPanel>
                                        <Image Width="24" Height="24" Source="/Appsecute;component/Images/restart.png"/>
                                    </StackPanel>
                                </Button>
                            </DockPanel>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
            <Label Content="SERVICE INSTANCES" Height="auto" Name="LabelServiceInstances" Grid.Row="2" Grid.ColumnSpan="3" Padding="2" Margin="0,8,0,0" VerticalAlignment="Top" />
            <ListBox Height="auto" Name="ListBoxServiceInstances" Width="auto" Grid.Row="3" Grid.RowSpan="2" Grid.ColumnSpan="3" />
        </Grid>
        <Label Height="28" HorizontalAlignment="Left" Margin="0,0,0,0" Name="LabelStatus" VerticalAlignment="Bottom" Width="auto" VerticalContentAlignment="Bottom" HorizontalContentAlignment="Stretch" FontSize="10" />
    </Grid>
</Controls:MetroWindow>

And an image of what I'm trying to achieve:

A: The problem is at the first level below DataTemplate, here:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">

By its nature a StackPanel will align items to the left, so it's not a layout that's well suited to what you want to do.  Instead try using a Grid with two columns, giving the left column Width=* and the right Width=Auto.
<ListBox HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <StackPanel Grid.Column="0" Orientation="Vertical">
                    ...
                </StackPanel>
                <DockPanel Grid.Column="1" VerticalAlignment="Center">
                    ...
                </DockPanel>
            </Grid>
        <DataTemplate>
    </ListBox.ItemTemplate>
<ListBox>

A: In your ItemContainerStyle, set the HorizontalAlignment to Stretch. I believe it is Left by default, which may be causing the Grid or StackPanel or whatever container you use to collapse.


text:
Q: Glib/Gio Asynchronous or Threaded UDP Server I have currently a synchronous UDP application receiving messages.
The code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <glib.h>
#include <gio/gio.h>

int main(argc,argv)
int argc;
char ** argv;{

char buf[256], *ptr, sep[] = "| ";
GError * error = NULL;

  GSocket * socket;
  GSocketAddress *gsockAddr, *gfromAddr;
  guint16 udp_port = 1500;
  //Creates socket udp ipv4
  socket = g_socket_new(G_SOCKET_FAMILY_IPV4,
                    G_SOCKET_TYPE_DATAGRAM,
                    G_SOCKET_PROTOCOL_UDP,
                    &error);
  g_assert(error == NULL);

  if (socket == NULL) {
    g_print("ERROR");
    exit(1);
  }
  //sockaddr struct like
  gsockAddr = G_SOCKET_ADDRESS(g_inet_socket_address_new(g_inet_address_new_any(G_SOCKET_FAMILY_IPV4), udp_port));

  if(gsockAddr == NULL){
    g_error("Error socket\n");
    exit(1);
  }
//
if (g_socket_bind (socket, gsockAddr, TRUE, NULL) == FALSE){

  g_print("Error bind\n");
  exit(1);

}

int bytes = g_socket_receive_from (socket,
                       &gfromAddr,
                       buf,
                       255,
                       NULL,
                       &error);

if (bytes == -1) {
  g_warning ("Failed to receive from socket: %s", error->message);
  g_error_free (error);
  return TRUE;
}

g_message("Server receive: %s", buf);

guint16 port = g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(gfromAddr));

g_print("...from    %s(%d)\n",g_inet_address_to_string(g_inet_socket_address_get_address(G_INET_SO    CKET_ADDRESS(gfromAddr))), (int) port);

exit(0);

}

So, I want to make the receive operation, non-blocking instead of blocking. I want to make it either ansynchronous, or/and threaded so that, meanwhile, I could do other operations related to the application I want to develop.
But I did not suceed to make it like I want. I tried to use GLib IO Channels, but I can not make it works. The processus is waiting, but only because of the Main Loop (I can not telnet the application).
The code :
#include <gio/gio.h>
#include <glib.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BLOCK_SIZE 1024

static gboolean
gio_read_socket (GIOChannel     *channel,
                 GIOCondition    condition,
                 gpointer        data)
{

    char buf[1024];
    gsize bytes_read;
    GError *error = NULL;

    if (condition & G_IO_HUP) return FALSE; /* this channel is done */

    g_io_channel_read_chars (channel, buf, sizeof (buf), &bytes_read,
            &error);
    g_assert (error == NULL);

    buf[bytes_read] = '\0';

    g_print ("%s", buf);

    return TRUE;
}

int
main (int argc, char **argv)
{

  GSocket * s_udp;
  GError *err = NULL;
  guint16 udp_port = 5556;

  s_udp = g_socket_new(G_SOCKET_FAMILY_IPV4,
                    G_SOCKET_TYPE_DATAGRAM,
                    G_SOCKET_PROTOCOL_UDP,
                    &err);
  g_assert(err == NULL);

  if (s_udp == NULL) {
    g_print("ERROR");
    exit(1);
  }

  g_socket_bind(s_udp,
               G_SOCKET_ADDRESS(g_inet_socket_address_new(g_inet_address_new_any(G_SOCKET_FAMILY_IPV4), udp_port)),
              TRUE,
              &err);

  g_assert(err == NULL);

  int fd = g_socket_get_fd(s_udp);
  GIOChannel* channel = g_io_channel_unix_new(fd);
  guint source = g_io_add_watch(channel, G_IO_IN,
                              (GIOFunc) gio_read_socket, NULL);

  g_io_channel_unref(channel);

  GMainLoop *loop = g_main_loop_new(NULL, FALSE);

  g_main_loop_run(loop);
  g_main_loop_unref(loop);

}

I am quite a beginner with GLib/Gio, and I think I am doing wrong with the IO Channels. I would like to add it to the main loop as an event, so that I could use my callback function. Maybe there is a simpler way to do that.
Besides, I have a TCP asynchronous and threaded server that is working, but I did not find how to do the same with UDP (using a GThreadedSocketService and creating a socket listener, then adding the service to the main loop. Easy as pie with TCP).
Do you have any idea how to proceed ? If you know how to do but only with the basic API socket, I still take it ! Thanks.

A: I figure it out.
I am indeed quite a beginner. Because, when I wanted to test my udp application (the second code block), I used telnet to connect to it and try to send messages. However, we can not telnet udp applications of course...
So I tried with a simple udp sender (I used Glib/Gio for it by the way) instead of telnet and it worked, perfectly non-blocking and reusable. I did make some changes but basically, it is the same. I put an idle function to show you how non-blocking it is, whether this can help someone one day.
My simple Glib/Gio UDP app, non blocking :
#include <gio/gio.h>
#include <glib.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BLOCK_SIZE 1024

static gboolean
gio_read_socket (GIOChannel     *channel,
                 GIOCondition    condition,
                 gpointer        data)
{

    char buf[1024];
    gsize bytes_read;
    GError *error = NULL;

    if (condition & G_IO_HUP) return FALSE; /* this channel is done */

    g_io_channel_read_chars (channel, buf, sizeof (buf), &bytes_read,
            &error);
    g_assert (error == NULL);

    buf[bytes_read] = '\0';

    g_print ("%s", buf);

    int *a = data;
    *a = *a + 1;

    return TRUE;
}

gboolean
idleCpt (gpointer user_data){

   int *a = user_data;
   g_print("%d\n", *a);
   sleep(1);

   return TRUE;
}
int
main (int argc, char **argv)
{

  GSocket * s_udp;
  GError *err = NULL;
  int idIdle = -1, dataI = 0;
  guint16 udp_port = 1505;
  GSocketAddress * gsockAddr = G_SOCKET_ADDRESS(g_inet_socket_address_new(g_inet_address_new_any(G_SOCKET_FAMILY_IPV4), udp_port));
  s_udp = g_socket_new(G_SOCKET_FAMILY_IPV4,
                    G_SOCKET_TYPE_DATAGRAM,
                    G_SOCKET_PROTOCOL_UDP,
                    &err);
  g_assert(err == NULL);

  if (s_udp == NULL) {
    g_print("ERREUR");
    exit(1);
  }

  if (g_socket_bind (s_udp, gsockAddr, TRUE, NULL) == FALSE){

   g_print("Erreur bind\n");
   exit(1);

  }

  g_assert(err == NULL);

  int fd = g_socket_get_fd(s_udp);

  GIOChannel* channel = g_io_channel_unix_new(fd);
  guint source = g_io_add_watch(channel, G_IO_IN,
                              (GIOFunc) gio_read_socket, &dataI);

  g_io_channel_unref(channel);

   GMainLoop *loop = g_main_loop_new(NULL, FALSE);
   idIdle = g_idle_add(idleCpt, &dataI);
   g_main_loop_run(loop);
}

The code is not perfect, there is a lot of optimisations to make, but we can do nice things from that I think. If you want to see my udp sender, just ask.


text:
Q: Are there any apps that can download lyrics for all the music files in a folder? I don't want the app to be launching any existing music player and displaying lyrics I just want the lyrics files to be downloaded.I also want the lyrics files to be of .lrc extension and currently I'm using ubuntu 14.10.
Please help.

A: The programs that work with lyrics and other music metadata can make use of a library named libglyr.
There is a program providing a command line interface to it's features, glyrc. I could not see which lyrics file formats are used in the man page, but it seems to be worth a try.
(Possibly it is somethinig like the standard minimal UI for libglyr library development - then, it may be cryptic, but very complete.)
From man glyrc:
 NAME

        glyrc - search engine for music-related metadata

 USAGE

               glyrc GETTER [options]
        where GETTER must be one of:
        · cover
        · lyrics
        · artistphoto
        · artistbio
        · similarartists
        · similarsongs
        · albumreview
        · albumlist
        · tags
        [...]

A: The best choice from the commandline is certainly glyrc. Below is an example of typical usage for downloading and writing a lyric file:
glyrc lyrics --artist "Pink Floyd" \
             --album "Dark Side of the Moon" \
             --title "Money" \
             --write "money.lrc"

As far as I know glyrc requires the individual songname or title to download in this way so some scripting will be required to download a set of lyrics...


text:
Q: Ribbon cable for Logitech ClearChat Wireless headset I'm looking for the name of this cable, which is used in a Logitech ClearChat Wireless headset.
Or a cable with the same endpoints so I can use it as a replacement.

A: Cables like that are custom designed to the application for a particular product or product family. The only likely replacement you will likely be able to find new is from the manufacturer.
You may also get lucky and find a like headset that has been thrashed for some other reason and extract the cable from that.
I would start with contacting the manufacturer. Find out the cost involved - if the cable is even available as a spare part - and then weigh that against the cost of simply replacing the whole headset itself.
BTW - What is happened to your existing cable?


text:
Q: Sorting output of a dictionary Alright so I have the following dictionary of planets, and each planet has its own dictionary containing its specs:
d={
'Mercury':{
'Distance from the sun' : 58,
'Radius' : 2439.7,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : []},
'Jupiter':{
'Distance from the sun' : 483,
'Radius' : 69911,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Io', 'Ganymede', 'Callisto', 'Europa', 'Adrastea']},
'Uranus':{
'Distance from the sun' : 3000,
'Radius' : 25559,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Miranda', 'Ariel', 'Umbriel', 'Titania', 'Oberon']},
'Mars':{
'Distance from the sun' : 207,
'Radius' : 3396.2,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : ['Phobos', 'Deimos']},
'Earth':{
'Distance from the sun' : 150,
'Radius' : 6371.0,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : ['Moon']},
'Venus':{
'Distance from the sun' : 108,
'Radius' : 6051.8,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : []},
'Saturn':{
'Distance from the sun' : 1400,
'Radius' : 60268,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Pan', 'Prometheus', 'Titan', 'Phoebe', 'Rhea']},
'Neptune':{
'Distance from the sun' : 4500,
'Radius' : 24764,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Triton', 'Nereid', 'Proteus', 'Naiad', 'Thalassa']}}`

Essentially what I want to do is print it in the order it appears in the dictionary, so I used the code:
for planets in sorted(d.keys()):
print(planets)
    for k,v in sorted(d[planets].items()):
        print(k, ":", v)

However this yields a random order of each planet and key value for each planet's description. (The planet name and then its specs are printed underneath it when I run it in python, I just didn't know how to format it to show it that way on stack)
i.e.:
Neptune
Moons : ['Triton', 'Nereid', 'Proteus', 'Naiad', 'Thalassa']
Radius : 24764
Distance from the sun : 4500
Gas planet? : True
Atmosphere? : True
Jupiter
Moons : ['Io', 'Ganymede', 'Callisto', 'Europa', 'Adrastea']
Radius : 69911
Distance from the sun : 483
Gas planet? : True
Atmosphere? : True
Earth
Moons : ['Moon']
Radius : 6371.0
Distance from the sun : 150
Gas planet? : False
Atmosphere? : True
Mercury
Moons : []
Radius : 2439.7
Distance from the sun : 58
Gas planet? : False
Atmosphere? : True
Mars
Moons : ['Phobos', 'Deimos']
Radius : 3396.2
Distance from the sun : 207
Gas planet? : False
Atmosphere? : True
Uranus
Moons : ['Miranda', 'Ariel', 'Umbriel', 'Titania', 'Oberon']
Radius : 25559
Distance from the sun : 3000
Gas planet? : True
Atmosphere? : True
Venus
Moons : []
Radius : 6051.8
    Distance from the sun : 108
    Gas planet? : False
    Atmosphere? : True
    Saturn
    Moons : ['Pan', 'Prometheus', 'Titan', 'Phoebe', 'Rhea']
    Radius : 60268
    Distance from the sun : 1400
    Gas planet? : True
    Atmosphere? : True

I've tried using sorted() but that just puts it in alphabetical order. Any suggestions?

A: This cannot be done. Python dictionaries do not make any promises about their printed order.

A: It's very simple(as a work around):
Just put any of the keys in a list, sort it, and then access it element by element using it as a key to access and print your dictionary.


text:
Q: Compute the series : $\sum_{n=1}^{\infty} \frac{4^n n!}{(2n)!}$ How would you compute the following series? I'm interested in some easy approaches that would allow me to work it out.
$$\sum_{n=1}^{\infty} \frac{4^n n!}{(2n)!}$$

A: It suffices to calculate the sum with the summation index running from 0, not from 1. Then
$$\begin{align*}
\sum_{n=0}^{\infty} \frac{4^n n!}{(2n)!}
&= \sum_{n=0}^{\infty} \frac{4^n}{(2n)!}\int_{0}^{\infty}t^n e^{-t}\;dt\\
&= \int_{0}^{\infty}\sum_{n=0}^{\infty} \frac{4^n t^n}{(2n)!} e^{-t}\;dt\\
&= \int_{0}^{\infty} \cosh(2\sqrt{t}) e^{-t}\;dt\\
&= \int_{0}^{\infty} 2u\cosh(2u) e^{-u^2}\;du\qquad(t=u^2)\\
&= \left[-\cosh(2u)e^{-u^2}\right]_{0}^{\infty} + 2\int_{0}^{\infty} \sinh(2u) e^{-u^2}\;du\\
&= 1 + 2\int_{0}^{\infty} \sinh(2u) e^{-u^2}\;du \\
&= 1 + \int_{0}^{\infty} \left(e^{2u} - e^{-2u}\right) e^{-u^2}\;du \\
&= 1 + e \int_{0}^{\infty} \left(e^{-(u-1)^2} - e^{-(u+1)^2}\right)\;du.
\end{align*}$$
Now it is clear how to express the last integrals in terms of the error function, yielding
$$ \sum_{n=1}^{\infty} \frac{4^n n!}{(2n)!} = e\sqrt{\pi} \mathrm{erf}(1).$$

A: Here is a generalization. Consider the generating function
$$f(x) = \sum_{n \ge 1} \frac{x^{2n} n!}{(2n)!}.$$
It's an easy check that $2$ is in the radius of convergence, so that we need to compute $f(2)$ to solve your problem. However, it's easy to see that
$$f''(x) = 1 + \sum_{n \ge 1} \frac{x^{2n} (n + 1)!}{(2n)!}$$
Moreover,
$$xf'(x) = 2 \sum_{n \ge 1} \frac{x^{2n} n!}{(2n)!} \cdot n$$
We get the second-order ODE
$$\frac{xf'(x)}{2} + f(x) = f''(x) - 1, f(0) = 0, f'(0) = 0.$$
And the solution
$$f(x) = \frac{1}{2} \cdot e^{x^2/4} \cdot x \sqrt{\pi} \mathrm{erf}(x/2).$$
Just plug in $x = 2$ to get your answer, $e\sqrt{\pi} \mathrm{erf}(1)$.

A: This is not an appropriate answer. We have $n!\approx C n^{n+1/2}e^{-n}$, so the terms become approximate $$4^{n}\frac{C n^{n}n^{1/2}e^{-n}}{C 2^{2n}2^{1/2}n^{2n}n^{1/2}e^{-2n}}$$
After cancelling out the terms we should have $$\frac{1}{2^{1/2}e^{-n}n^{n}}=2^{-1/2}(\frac{e}{n})^{n}$$
I do not know if there is any way to sum $$C\sum^{\infty}_{N}(\frac{e}{n})^{n}$$ where $N$ is some very large number depends on Stirling's formula. Now suppose we have $kn,0\le k\le 1$ instead of $e$. Then we should have $$\sum^{\infty}_{N}k^{n}=\frac{k^{N}}{1-k}$$
So obviously for fixed $N$ we have the top side of the derivative to be $$Nk^{N-1}(1-k)+k^{N}=Nk^{N-1}-(N-1)k^{N}$$ which equals 0 if and only if $$k=\frac{N}{N-1}$$ which is impossible by our assumption on $k$. Thus this sum increases monotone with $k$ and has a minimum at $k=0$. So assume $k=\frac{e}{N}$ we should be able to bound the original sum from above. For the exact value one probably need to run a computer program.