text:
Q: Color Code SharePoint 2013 Column based on Date Column I followed this post on this site about color coding a SharePoint Column based on a date column. This worked really well and I got the result I wanted.
I followed the answer from @chris-g. Below is my code:
    (function () {
    var statusFieldCtx = {};
    statusFieldCtx.Templates = {};
    statusFieldCtx.Templates.Fields = {
    //internal column name between double quotes on the next line. If your column name has a space in its internal name use "_x0020_" in place of the space.
        "Next_x0020_Review_x0020_Date": {
            "View": ColorCodeNextReviewDate
            }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(statusFieldCtx);
})();

function ColorCodeNextReviewDate(ctx) {
    //update internal column name at the end of the next line
    var MyDateVar = new Date(ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[2],ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[1]-1,ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[0]);

    var today = new Date();
    today.setHours(0,0,0,0);

    var then1 = new Date();
    //use this to set how many days you want var then to be.
    then1.setHours(0,0,0,0);
    then1.setDate(then1.getDate() + 1);

    var then30 = new Date();
    then30.setHours(0,0,0,0);
    //use this to set how many days you want var then to be.
    then30.setDate(then30.getDate() + 30);

    var then31 = new Date();
    then31.setHours(0,0,0,0);
    //use this to set how many days you want var then to be.
    then31.setDate(then31.getDate() + 31);

    // if there's no due date don't render anything. Also update the column names in the else statements below. If your column name has a space in its internal name use "_x0020_" in place of the space.
    if (MyDateVar < today) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar.getTime() == today.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar.getTime() >= then1.getTime() && MyDateVar.getTime() <= then30.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar >= then31) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
}

I was hoping to also add DIV styles to the same IF statements to colour another column.  So currently, based off the formula, the "Next_x0020_Review_x0020_Date" is coloured - I also want the "Next_x0020_Review" column (a calculated column) to be coloured.  So, I thought, I'd add the additional DIV lines to the result statements (which I think could work?) but I think my trouble area is in the initial Function statement at the top of the code where I add the column names (see below).  My expertise is not JS so I'm just trying and testing but no luck so far....  Any help would be most appreciated :-)
(function () {
    var statusFieldCtx = {};
    statusFieldCtx.Templates = {};
    statusFieldCtx.Templates.Fields = {
    //internal column name between double quotes on the next line. If your column name has a space in its internal name use "_x0020_" in place of the space.
        "Next_x0020_Review_x0020_Date": {
            "View": ColorCodeNextReviewDate
            }
        "Next_x0020_Review": {
            "View": ColorCodeNextReviewDate
            }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(statusFieldCtx);
})();

function ColorCodeNextReviewDate(ctx) {
    //update internal column name at the end of the next line
    var MyDateVar = new Date(ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[2],ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[1]-1,ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[0]);

    var today = new Date();
    today.setHours(0,0,0,0);

    var then1 = new Date();
    //use this to set how many days you want var then to be.
    then1.setHours(0,0,0,0);
    then1.setDate(then1.getDate() + 1);

    var then30 = new Date();
    then30.setHours(0,0,0,0);
    //use this to set how many days you want var then to be.
    then30.setDate(then30.getDate() + 30);

    var then31 = new Date();
    then31.setHours(0,0,0,0);
    //use this to set how many days you want var then to be.
    then31.setDate(then31.getDate() + 31);

    // if there's no due date don't render anything. Also update the column names in the else statements below. If your column name has a space in its internal name use "_x0020_" in place of the space.
    if (MyDateVar < today) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar.getTime() == today.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar.getTime() >= then1.getTime() && MyDateVar.getTime() <= then30.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar >= then31) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
}

A: You have to write separate handler functions for each column. Try using below code:
(function () {
    var statusFieldCtx = {};
    statusFieldCtx.Templates = {};
    statusFieldCtx.Templates.Fields = {
        //internal column name between double quotes on the next line. If your column name has a space in its internal name use "_x0020_" in place of the space.
        "Next_x0020_Review_x0020_Date": {
            "View": ColorCodeNextReviewDate
        },
        "Next_x0020_Review": {
            "View": ColorCodeNextReviewColumn
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(statusFieldCtx);
})();

function ColorCodeNextReviewDate(ctx) {
    //update internal column name at the end of the next line
    var MyDateVar = new Date(ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[2], ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[1] - 1, ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[0]);

    var today = new Date();
    today.setHours(0, 0, 0, 0);

    var then1 = new Date();
    //use this to set how many days you want var then to be.
    then1.setHours(0, 0, 0, 0);
    then1.setDate(then1.getDate() + 1);

    var then30 = new Date();
    then30.setHours(0, 0, 0, 0);
    //use this to set how many days you want var then to be.
    then30.setDate(then30.getDate() + 30);

    var then31 = new Date();
    then31.setHours(0, 0, 0, 0);
    //use this to set how many days you want var then to be.
    then31.setDate(then31.getDate() + 31);

    // if there's no due date don't render anything. Also update the column names in the else statements below. If your column name has a space in its internal name use "_x0020_" in place of the space.
    if (MyDateVar < today) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar.getTime() == today.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar.getTime() >= then1.getTime() && MyDateVar.getTime() <= then30.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
    else if (MyDateVar >= then31) {
        return "
" + ctx.CurrentItem.Next_x0020_Review_x0020_Date + "
";
    }
}

function ColorCodeNextReviewColumn(ctx) {
    //update internal column name at the end of the next line
    var MyDateVar = new Date(ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[2], ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[1] - 1, ctx.CurrentItem.Next_x0020_Review_x0020_Date.split('/')[0]);

    var today = new Date();
    today.setHours(0, 0, 0, 0);

    var then1 = new Date();
    //use this to set how many days you want var then to be.
    then1.setHours(0, 0, 0, 0);
    then1.setDate(then1.getDate() + 1);

    var then30 = new Date();
    then30.setHours(0, 0, 0, 0);
    //use this to set how many days you want var then to be.
    then30.setDate(then30.getDate() + 30);

    var then31 = new Date();
    then31.setHours(0, 0, 0, 0);
    //use this to set how many days you want var then to be.
    then31.setDate(then31.getDate() + 31);

    // if there's no due date don't render anything. Also update the column names in the else statements below. If your column name has a space in its internal name use "_x0020_" in place of the space.
    if (MyDateVar < today) {
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar.getTime() == today.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar.getTime() >= then1.getTime() && MyDateVar.getTime() <= then30.getTime()) {
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
    else if (MyDateVar >= then31) {
        return "
" + ctx.CurrentItem.Next_x0020_Review + "
";
    }
}


text:
Q: Is it appropriate to omit "to" after "ought"? Is it appropriate to omit to after ought?

I ought to be disciplined for my insolence.

Vs.

I ought be disciplined for my insolence.

Is it okay to omit the to?

A: It's not typical.
The American Heritage Dictionary entry for ought has the following usage note:

Unlike other auxiliary verbs, ought usually takes to with its accompanying verb: We ought to go. Sometimes the accompanying verb is dropped if the meaning is clear: Should we begin soon? Yes, we ought to. In questions and negative sentences, especially those with contractions, to is also sometimes omitted: Oughtn't we be going soon? This omission of to, however, is not common in written English.

A: The omission of to is more frequent in American English. Quirk & al. (A Grammar of Contemporary English) say:

Ought regularly has the to-infinitive, but AmE occasionally has the bare infinitive in negative sentences and in questions (although should is commoner in both cases):
  - You oughtn't smoke so much.
  - Ought you smoke so much?

A: British English requires the to-infinitive. (I didn't know until reading the above comments that American English allowed its omission.)

A: The use of ought w/out the "to' is a lovely locution when the underlying intention is imperative.  "My name ought be included" = "Include my name."  I vote for its acceptance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Singleton pattern with gtk3 and gtkmm I'm working on a gui app with cpp and gtkmm3.
In this app, some widgets require the singleton pattern to implement such as window (because i want just one window in all over the app)
this is my header file:
class MyWindow : public Gtk::ApplicationWindow {

public:
    MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> builder);
    ~MyWindow();
    MyWindow(MyWindow const&) = delete;
    void operator=(MyWindow const&) = delete;
    static MyWindow* getInstance();

private:
    MyWindow();

};

and source file is :

MyWindow::MyWindow(){}

MyWindow::MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> refBuilder)
        : Gtk::ApplicationWindow(pWindow),
          builder(refBuilder) {

}

MyWindow::~MyWindow() {}

MyWindow *MyWindow::getInstance() {
    static MyWindow *window;
    return window;
}

my question is:
Is there a more appropriate and reasonable pattern instead singleton pattern ?
Is using this pattern suitable for the interface widgets and gui app ?

A: The major problem with the Singleton design pattern is that it gives you:

*

*a single instance AND

*global access.

The single instance aspect of the singleton is what people usually are looking for (like in your case), but not global access.
The usual "alternative" to this is to declare a MyWindow instance and then inject it to anyone who needs it. This is known as dependency injection. So you have something like:
void DoSomeThingOnWindow(MyWindow& p_window)
{
    p_window.DoSomething();
}

// At the beginning:
MyWindow window;

// Everywhere else:
DoSomeThingWithTheWindow(window);

instead of:
void DoSomeThingOnWindow()
{
    // Global access:
    MyWindow* window = MyWindow::getInstance();
    window->DoSomething();
}

// Everywhere:
DoSomeThingWithTheWindow();

The "bad" side of dependency injection over a singleton is that it will not enforce the single instance. However, if you use it everywhere and carefully, you can pass a single instance all around and not have global access, which will have so much more benefits.


text:
Q: How to add a click method in sensor I have successfully, with a fellow programmers help to create the following code:
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class SensorTestActivity extends Activity implements SensorEventListener {
    private SensorManager sensorManager;
    private boolean color = false;
    private View view;
    private long lastUpdate;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);
        view = findViewById(R.id.label);
        view.setBackgroundColor(Color.GREEN);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        lastUpdate = System.currentTimeMillis();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            getAccelerometer(event);
        }

    }

    private void getAccelerometer(SensorEvent event) {
        float[] values = event.values;
        // Movement
        float x = values[0];
        float y = values[1];
        float z = values[2];

        float accelationSquareRoot = (x * x + y * y + z * z)
                / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
        long actualTime = System.currentTimeMillis();
        if (accelationSquareRoot >= 2) //
        {
            if (actualTime - lastUpdate < 200) {
                return;
            }
            lastUpdate = actualTime;
            Toast.makeText(this, "Device has shaken", Toast.LENGTH_SHORT)
                    .show();
            if (color) {
                view.setBackgroundColor(Color.GREEN);

            } else {
                view.setBackgroundColor(Color.RED);
            }
            color = !color;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        // register this class as a listener for the orientation and
        // accelerometer sensors
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        // unregister listener
        super.onPause();
        sensorManager.unregisterListener(this);
    }
}

Right now i am trying to add something like..
Switch.setOnClickListener(new View.OnClickListener() {
    @Override
      public void onClick(View v) {
          if (sensorIsOn) {
              //deactivate it
           } else {
              //activate it
          }
    }

});

I want to click on a button and deseable sensor and on clicking again enabling it!

A: You should just register or unregister the listener. Just as you should in onPause and onResume (I think).
mSensorManager.registerListener(this, jAccelerometer,
            SensorManager.SENSOR_DELAY_NORMAL);

mSensorManager.unregisterListener(this);

A: in onCreate() method , after you register the sensor's listener, set the Tag of your Switch button to true :
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);
        view = findViewById(R.id.label);
        view.setBackgroundColor(Color.GREEN);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        lastUpdate = System.currentTimeMillis();

        Button Switch = (Button) findViewById(R.id.switch_button);
        Switch.setTag(true);
        //set the listener for your Switch button here
    }

And in the onClick() method : try this code  :
Switch.setOnClickListener(new View.OnClickListener() {
    @Override
      public void onClick(View v) {
          boolean isSensorActivated = (boolean) v.getTag();
          if(isSensorActivated) {
              mSensorManager.registerListener(this, jAccelerometer,
            SensorManager.SENSOR_DELAY_NORMAL);
          }
          else {
              mSensorManager.unregisterListener(this);
          }
          v.setTag(!isSensorActivated);
     }

});


text:
Q: Passing Element Data to a Bootdtrap Modal Having a frustrating time, made even worse that the examples I see everywhere are not working in this instance. My assumption is because I am not understanding what elements are being loaded in which order.
The question is common enough, I have a button that I want to pass data from into the modal it opens. Let's say I want to pass in the id. My first idea was something like this which is the typical answer on Stack Overflow:
HTML:
<button class="btn btn-primary btn-block" data-toggle="modal" data-target="#myModal" id="product-button">Product Name</button>

JavaScript:
$(function() {
    $('#product-button').click(function() {
        var productId = $(this).attr('name');
        $(".modal-body #testContainer").val(productId);
    });
});

This is seen here:
Passing data to a bootstrap modal
However, this appears not to work for me. The kicker for my scenario is that the buttons are generated dynamically and I am wondering if because I've wrapped everything in a helper function and it ties itself to the page before the dynamic buttons are created and therefore doesn't know they exist and to listen for a .click event (they are created through a search, the buttons are the results of the search)
Anybody have any ideas on how I can go about passing data to a modal with this limitation?

A: If the buttons are generated dynamically, you have to use event-delegation to make it work:
$(function() {
    $(document).on('click','#product-button',function() {
        var productId = $(this).attr('name');
        $(".modal-body #testContainer").val(productId);
    });
});

Event Delegation:

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.


text:
Q: Combotree in javascript (jquery) I'm looking for a component which enable display tree in combo (select).
Something like that: http://www.jeasyui.com/demo/index.php
But this component doesn't allow import JSON directly, only from file.
It works in that way:
$('#cc').combotree({
        url:'tree_data.json'
    });

I need (pseudocode):
$('#cc').combotree({
        data:'[{"id":1,"text":"City","children":[{"id":11,"text":"Wyoming","children":[{"id":111,"text":"Albin"}]}]}]'
    });

Or (pseudocode):
$('#cc').combotree({
        data:'<?php $json_string; ?>'
    });

Is it possible? Or maybe do you know any components which enable to do that?
Regards,
Chris

A: <?php

$obj = json_encode('['.json_encode($objects).']');
$jquery_obj = str_replace(",\\\"name\\\":", ",\\\"text\\\":", $obj);
print $jquery_obj;

?>

<script>
$(document).ready(function(){
var jq_data = $.parseJSON(<? print $jquery_obj; ?>);

$('#cc').combotree({

    animate:true,
    data:jq_data
});

});

</script>
<select id="cc" class="easyui-combotree"></select>

A: Did you try the data parameter? The documentation says it should work. (Give the data as an array, not a string.) You can also give the data as an ul list. Check the documentation for tree.


text:
Q: Как во Vue.js сохранить данные из input в localstorage и вывести их оборатно в инпут Как во Vue.js сохранить данные из input в localstorage и вывести их оборатно в инпут.
Пробовал делать по примеру с оффсайта vue.js , но мне нужно использовать framewwork7, а там  v-model не поддерживается.
А так постоянно в инпуте выводит [object InputEvent]. Если перезагрузить страницу или убрать курсор синпута тоже самое, всегда [object InputEvent].
В консоли при попытке ввода выдаёт. ---> [Vue warn]: Error in v-on handler: "ReferenceError: $event is not defined" found in --->       at src/pages/login.vue    at src/app.vue  vue.esm.js:629:7
  <f7-list form>
    <f7-list-input
      label="Username"
      name="username"
      placeholder="Username"
      type="text"
      v-bind:value="name"
      required validate
      pattern="[3-9a-zA-Zа-яА-ЯёЁ]+"
      @input="persist"
    />
  </f7-list>

<script>
export default {
data() {
    return{
        name: '',
        }
    },
mounted() {
  if (localStorage.name) {
    this.name = localStorage.getItem('name')
  }
},

 methods: {
             persist(){
                localStorage.setItem('name', $event.target.value)
        }
    }
    };
    </script>
[![Вот что выводи

т в инпуте]1]1


text:
Q: What is the relationship between momentum method for gradient descent defined in machine learning and the momentum defined in physics The momentum method for gradient descent in machine learning is defined as
$$
\begin{array}{l}
\mathbf{v}_{t} \leftarrow \beta \mathbf{v}_{t-1}+\mathbf{g}_{t-1} \\
\mathbf{x}_{t} \leftarrow \mathbf{x}_{t-1}-\eta_{t} \mathbf{v}_{t}
\end{array}
$$
where $\mathbf{g}$ is the gradient.
While the momentum in physics is defined as:
$$
p=mv
$$
where $m$ is the mass and $v$ is the velocity.
I don't see how the above two equations are mathematically connected. Does the term momentum have a totally different meaning in machine learning from it does in physics?

A: The physics concept which optimization "momentum" maps best to is drag. For example, if $\beta = 1$, then there is no damping, and you get something very close to the classic laws of motion ($x_t = x_{t-1} + v\cdot dt, v_t = v_{t-1} + \frac{F}{m} \cdot dt$). On the other hand, if $\beta = 0$, it's as if there's a drag force $F'$ acting in the opposite direction of $v_t$, just strong enough to "cancel out" the previous velocity, so that $v_t = (v_{t-1} - \frac{F'}{m} dt)
 + \frac{F}{m} dt = \frac{F}{m} dt $. Since $F' \propto v_{t-1}$, it seems appropriate to call this drag, since drag does scale linearly with velocity in many cases.


text:
Q: User Defined Print area in Excel I'm trying to make a Pretty way for a Customized Print area in Excel.
I Have a big Excel list where many Users work with.
What i want is, that every User can make a Custom Print out quick and easy.
I don't have andy Problem with the Code to define a print area in excel.
Where I'm Struggling is a Pretty Solution for that.
I thought about  Something Like in the Image below with Checkboxes. But that does not convince me really.
Does anyone of you know any better Solution for that Problem? Any Hints are Welcome.


text:
Q: How to send email Symfony 2 + AWS SES + Swiftmailer? I have moved an application to amazon builded in symfony2 and using swiftmailer for sending emails, I am not able to send emails from the application.
So searching around the solution for sending emails. Please let me know if any solutions for sending email SES or configuring SMTP for symfony2.

A: I got mine to work with the following details:
transport: "%mailer_transport%"
host:      "%mailer_host%"
username:  "%mailer_user%"
password:  "%mailer_password%"
auth_mode:  login
encryption: tls
port:  587
logging:  "%kernel.debug%"

And lastly, make sure the send FROM email address is verified.

A: I never played with AWS SES but you can use mailjet to send email. You just need to configure Swiftmailer Transport to use their SMTP and you're done.
They also ensure that your email are well sending (ie: not in spam) by providing several technique. You will have to setup some of them.
They do not provide example for Swiftmailer, but here a good one for Zend (you will see how easy it is):
$config = array(
  'ssl'      => 'ssl',
  'port'     => 465,
  'auth'     => 'login',
  'username' => 'your_Mailjet_API_Key',
  'password' => 'your_Mailjet_Secret_Key');

$transport = new Zend_Mail_Transport_Smtp('in-v3.mailjet.com', $config);

$mail = new Zend_Mail();

$mail->setFrom('your_sender@address.com', 'You');
$mail->addTo('recipient@example.com', 'Anybody');
$mail->setSubject('My first email by Mailjet');
$mail->setBodyText('Hello from Mailjet & Zend Framework !');

$mail->send($transport);

A: Amazon SES has an excellent Php API from the official AWS Php SDK:
http://docs.aws.amazon.com/aws-sdk-php/guide/latest/service-ses.html
As you can see, SES is not used as a SMTP gateway (like Mailjet does) but as a HTTP API (via Guzzle, a Php library for HTTP queries). It's always an important decision to rely or not on Amazon services such as S3/SeS/SNS etc... maybe you don't want to depend on no Amazon technology?

A: You can try to use AWS SES Monitor Bundle to manage the sending of emails through SwiftMailer with Symfony.
The problem is that when you start with AWS SES you are in the sandbox and to go live you need to file an issue to Amazon to ask to put you out of the sendbox.
The requirement is that you can manage bounces and complaints.
To get notifications about those, you need to connect to Simple Notification Service (the other option is to get notifications via e-mail).
To automate all this stuff, you can use AWS SES Monitor Bundle that do all of this for you.
It also registers a plugin for SwiftMailer that can intercept messages and avoids the sending of messages to address to which you should not send e-mails.


text:
Q: Django Pass through Table field data to Serializer I have the following models:
class Disease(models.Model):
    name = CICharField("Disease Name", max_length=200, unique=True)
    symptoms = models.ManyToManyField(Symptom, through='DiseaseSymptom', related_name='diseases')

class Symptom(models.Model):
    name = CICharField("Symptom Name", max_length=200, unique=True)

PRIORITY = (
    (0, 'Normal'),
    (1, 'Low'),
    (2, 'Medium'),
    (3, 'High'),
    (4, 'Key'),
)

class DiseaseSymptom(models.Model):
    disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name='disease_to_symptom')
    symptom = models.ForeignKey(Symptom, on_delete=models.CASCADE, related_name='symptom_to_disease')
    priority = models.PositiveSmallIntegerField('Priority', choices=PRIORITY, default=0)

On the front-end, I have multiple select boxes where users can select multiple Symptoms to find disease and that will pass to Disease model as symptoms_selected params.
I have the following get_queryset on Disease > views.py

def get_queryset(self):
        params = self.request.query_params
        query_symptoms = self.request.GET.getlist('symptoms_selected')
        if query_symptoms:
            queryset = Pattern.objects.filter(
                symptoms__id__in=query_symptoms
            ).annotate(
                matches=Count('symptoms')
            ).order_by('-matches')
        else:
            queryset = Disease.objects.all()
    return queryset
serializer_class = DiseaseSerializer

I am using Django REST API to pass the result data.

class DiseaseSerializer(serializers.ModelSerializer):
    symptoms_matches = serializers.SerializerMethodField()

    class Meta:
        model = Disease
        fields = ('id', 'name','symptoms_matches')

    def get_symptoms_matches(self, obj):
        return getattr(obj, 'matches', None)

For eg: Disease Data:
Disease A:
Got Symptoms: A (priority=4), B (priority=2), C (priority=3), D (priority=2)
Disease B:
Got Symptoms:  A (priority=1), D (priority=2), P (priority=4), Q (priority=2)
If Users select 2 symptoms: A, D. I want queryset will return the count of key symptoms ( i.e. symptom with priority 4 ) matched on each Disease and the sum of the symptoms priority in each Disease.
For Eg. if Users select 2 symptoms: A, D. I want to achieve The serializer will return data like:
[
{
name: "Disease A"
key_symptoms_matched: 1
matched_symptoms_priority_sum: 6
}

{
name: "Disease B"
key_symptoms_matched: 0
matched_symptoms_priority_sum: 3
}

]

Can anyone tell me how can I achieve this?

A: I found a way to calculate the total sum of symptoms priorities in each disease
queryset = Disease.objects.filter(
                symptoms__id__in=query_symptoms
            ).annotate(
                matches=Count('symptoms')
            ).annotate(
                matched_symptoms_priority_sum =Sum('disease_to_symptom__priority')
            ).order_by('-matches','-matched_symptoms_priority_sum')

But I still need the number of key symptoms matched in each disease?


text:
Q: Utilização do virtualenv python Estou começando a usar o virtualenv para projetos e no processo me surgiu uma duvida, depois de ativar o ambiente, toda vez que eu entrar ou sair da pasta ele ativa e desativa automaticamente, ou eu preciso dar activate para usa-lo e deactivate para voltar para configuração global?

A: De forma simplificada, o scritp activate modificará as variáveis de ambiente durante a sessão do terminal.
[...]

VIRTUAL_ENV="/home/user/python/venv"
export VIRTUAL_ENV

_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH

[...]

Trecho de código retirado do arquivo venv/bin/activate
Ou seja, quando você ativa o ambiente virtual uma variável de ambiente VIRTUAL_ENV é criada com o caminho para onde foi gerado o ambiente; logo após ele modifica o valor da variável PATH adicionando a variável recém criada como primeiro caminho na busca em PATH.
Desta forma, quando você executar algum comando com o ambiente virtual ativado, o primeiro diretório a ser analisado em busca do executável deste comando será o diretório venv/bin (no Windows será venv/Scripts).
Ao executar a função deactivate as variáveis voltarão ao valor inicial, isto é, a variável VIRTUAL_ENV será excluída e a PATH voltará ao valor _OLD_VIRTUAL_PATH, criada durante o activate com o valor original de PATH.
Ao encerrar a sessão do seu terminal, essas variáveis de ambiente serão removidas, então não existe a obrigação de você sempre chamar o deactivate. Necessita executá-lo apenas quando necessita sair do ambiente virtual mantendo a mesma sessão do terminal - comum quando está, por exemplo, conectado via SSH no servidor.
Navegar entre pastas durante a mesma sessão do terminal não fará com que o seu ambiente virtual seja desativado.

A: Ola .
Sobre sua pergunta, sim terá que ativar e desativar.
Mas pode delegar essa função ao sistema operacional em uso caso tenha apenas um ambiente no entanto se estiver  usando ambientes com versões diferentes tera que ser manualmente.
utilizando da seguinte sintaxe :
ATIVAR - (Gnu/Linux)
workon DEV38  (Uso python 3.8+)
workon DEV27 ( Uso python 2.7+)
DESATIVAR - (Gnu/Linux)
deactivate DEV38
deactivate DEV27

A: Sim, quando for trabalhar no seu projeto será necessário ativar o virtualenv, e quando terminar precisar desativa-la.
Para Windows, é necessário instalar o módulo virtualenv
  > pip install virtualenv

Depois é necessário criar uma pasta de Venv na raiz do projeto
> python -m venv "venv_name"

Para ativar a Venv:
> venv_name\Scripts\activate.bat

Para sair do Venv, digitar:
> deactivate


text:
Q: How to set priority when aggregating rows of a data frame? I need to aggregate rows of a data frame with MANY rows in this manner:
Lets say I have two rows that I want to merge (as they have the same first element):
  x1=c(ID1,1,3,2,1,NA);
  x2=c(ID1,2,2,3,NA,NA);

I want to merge their values so, that the result will in the case of clash (clash=both rows have a non-NA value in the element) prefer the value in a row with higher value in 2nd element (that is x2).
So in the example the result of the aggregation of these particular two rows will be:
x12=c(ID1,2,2,3,1,NA)

Can anyone please help?
I tried aggregate(), but it offers just summary statistics like mean, max etc.

A: You can use max as a function for the aggregate function.
Data:
x1=c('ID1',1,2,1,NA)
x2=c('ID1',3,3,NA,NA)

data <- data.frame(rbind(x1, x2), stringsAsFactors = FALSE)

Aggregating:
aggregate(data[,2:5], by = list(name = data$X1), FUN = max, na.rm = TRUE)

Result:
  name X2 X3 X4   X5
1  ID1  3  3  1 <NA>

A: You can use SQL via the package sqldf.
Using sql you can group by ID and select the max of the values you mentioned.
require(data.table)
require(sqldf)
x1 <- c(1,1,2,1,NA)
x2 <- c(1,3,3,NA,NA)
x  <- data.table(rbind(x1,x2))
colnames(x) <- c("ID", "x1", "x2", "x3", "x4")

sqldf("select ID, max(x1) as x1, max(x2) as x2, max(x3) as x3, max(x4) as x4 from x group by ID")

  ID x1 x2 x3 x4
1  1  3  3  1 NA


text:
Q: Symfony2: No route found for "GET /genus/octopus/" Doing my first app from http://knpuniversity.com/screencast/symfony/
It's standart error, but I don't know how to debug it, cause in debug:error route /genus/{genusName} is exists
(genus/{genusName}/notes is working well)
routing.yml
app:
    resource: '@AppBundle/Controller/'
    type: annotation

src/AppBundle/Controller/GenusController.php
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class GenusController extends Controller
{
    /**
     * @Route("/genus/{genusName}")
     */
    public function showAction($genusName)
    {
        return $this->render('genus/show.html.twig', array(
            'name' => $genusName,
        ));
    }
    /**
     * @Route("/genus/{genusName}/notes", name="genus_show_notes")
     * @Method("GET")
     */
    public function getNotesAction($genusName)
    {
        $notes = [
            ['id' => 1, 'username' => 'AquaPelham', 'avatarUri' => '/images/leanna.jpeg', 'note' => 'Octopus asked me a riddle, outsmarted me', 'date' => 'Dec. 10, 2015'],
            ['id' => 2, 'username' => 'AquaWeaver', 'avatarUri' => '/images/ryan.jpeg', 'note' => 'I counted 8 legs... as they wrapped around me', 'date' => 'Dec. 1, 2015'],
            ['id' => 3, 'username' => 'AquaPelham', 'avatarUri' => '/images/leanna.jpeg', 'note' => 'Inked!', 'date' => 'Aug. 20, 2015'],
        ];
        $data = [
            'notes' => $notes
        ];
        return new JsonResponse($data);
    }
}

app/Resources/views/genus/show.html.twig
{% extends 'base.html.twig' %}
{% block title %}Genus {{ name }}{% endblock %}
{% block body %}

{{ name }}

    Json Notes

Subfamily:

Octopodinae

Known Species:

289

Fun Fact:

Octopuses can change the color of their body in just three-tenths of a second!

Notes

{% endblock %}

debug:route http://joxi.ru/Dr8j6YniOx3E26 (sorry, I can paste only url cause of reputation)

A: The path in your route configuration does not contain a trailing slash. In order to make your example work you will either need to remove the trailing slash when trying to access your controller (i.e. /genus/octopus instead of /genus/octopus/) or add the slash to your route config.


text:
Q: Backbone button click event not firing Having trouble getting a button click event registered with a backbone view.  The view itself displays just fine, with the correct data substituted into the template, but when I click the generated button, nothing happens.  Any ideas?
My view is defined as:
var IndividualNoteView = Backbone.View.extend({

    template:$("#indivNoteTemplate").html(),

    events: {
        'click .removeItem': "buttonClickHandler",
    },

    initialize : function (options) {
        console.log("Creating new indiv note view");

        this.options = options || {};
        this.gridster = this.options.gridster;
        this.noteModel = this.options.noteModel;
        this.row = this.options.row;
        this.col = this.options.col;
        this.el = $("#"+this.noteModel.get("noteId"));
        console.log("my domain- "+this.el.selector);
        this.noteModel.on('remove', this.destroy_view);
    },

    render: function(){
        var tmpl = _.template(this.template);
        this.el = tmpl(this.noteModel.toJSON());
        this.gridster.add_widget(tmpl(this.noteModel.toJSON()));
    },

    buttonClickHandler : function(event){
        alert( $(event.currentTarget).text());

        return false;
    }
});

and my template (in my index.html) is defined as:

A: You need to set an el property backbone binds events to the views el.
for example:
el: '#container'
Or you could:
id: function()
{
    return this.noteModel.get('noteId');
}

and then use this.$el instead of doing this.el = $("#"+this.noteModel.get("noteId")); in the initialize function.
You would then not need to do id="<%= noteId%>" in the template since backbone will handle it for you.

A: At the time initialize is called your template has not been rendered so this.el = $("#"+this.noteModel.get("noteId")); is probably selecting nothing.
Furthermore, the Backbone.View creates the element for you, so you should not need to do this.
As per the Backbone docs your render function should probably look more like this
render: function(){
    var tmpl = _.template(this.template);
    this.$el.html(tmpl(this.noteModel.toJSON()));
    this.gridster.add_widget(this.$el);
}

If you ever want to set the .el property manually you must call setElement to properly set up the Backbone View. You can see how this is used internally here.


text:
Q: jQuery collection gets broken inside each loop (remove elem, restore innerHTML) I expected the following code to iterate through a select options and remove options having a certain value, otherwise restore the select html
var initialHTML = $('#myselect').html();

$('#myselect option').each(function(){
    if($(this).val() === 'b'){
        $(this).remove();
        console.log('matching. removed.');
        return false;
    }else{
        $('#myselect').html(initialHTML);
        console.log('not matching. html restored.');
    }
});

Expected select would be:
<select id="myselect">
    <option value="a">a</option>
    <option value="c">c</option>
</select>

but it actually is
<select id="myselect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

What I'm doing wrong? FIDDLE
Update e.g. as someone suggested:

The $('#myselect option') constructs a list of options, and
  $(this).remove() removes option b, but the list of options is no
  longer linked to the HTML, because the HTML had been already changed
  by $('#myselect').html(initialHTML) which was executed for option
  a

so, I've realised that the actual problem is not even related to what I asked initially in my question. Sorry for that and I'll try to put it in the right section.
p.s. a working solution:
var initialHTML = $('#myselect').html();

function doIt(){
    $('#myselect').html(initialHTML);

    $('#myselect option').each(function(){
        if($(this).val() === 'b'){
            $(this).remove();
        }
    });
}

Thank you so much for help.

A: The main issue is this line:
$('#myselect').html(initialHTML);

It is executed for option a and then option b can no longer be removed because the HTML has changed even though it is actually identical. So remove that line and your code will work.
$('#myselect option') constructs a list of options, and $(this).remove() removes option b from the list, but the list is no longer associated with the HTML, because the HTML had been already changed by $('#myselect').html(initialHTML) which was executed for option a.

var initialHTML = $('#myselect').html();

$('#myselect option').each(function() {
  if (this.value === 'b') {
    $(this).remove();
    console.log('matching. removed.');
    return false;
  } else {
    //$('#myselect').html(initialHTML);
    console.log('not matching. html restored.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>

I changed $(this).val() to this.value. Both will work, but the second one is a bit more efficient because there is no point in converting the JavaScript object to a jQuery object just to get the value.
However, remember that the line:
return false;

will cause the each() loop to exit once a match is found. That's OK if there will only be one match. If there can be more that one match, remove that line so the loop can go through all options.

A: Here is an alternative way:
Other answers already point out the reason, as because you refresh the option list the during the first iteration, $(this).remove() no longer works because it lose contact of the original item. Thus, a simple fix here would be re-select the target based on it's value. And you can keep your original code of $('#myselect').html(initialHTML); in the loop.

var initialHTML = $('#myselect').html();
$('#myselect option').each(function(){
    if($(this).val() === 'b'){
        $("option[value='" + $(this).val() + "']").remove();
        console.log('matching. removed.');
        return false;
    } else {
        $('#myselect').html(initialHTML);
        console.log('not matching. html restored.');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
    <option value='a'>a</option>
    <option value='b'>b</option>
    <option value='c'>c</option>
</select>

A: What is happening here is that you have something that only needs to be false once to restore the entire select. So it does remove 'b' when it finds it, but then restores the whole select once it sees that 'c' !== 'b'.
You can achive your expected behavior by removing:
else{
    $('#myselect').html(initialHTML);
    console.log('not matching. html restored.');
}

Depending on what your ultimate goal is, there may be better ways of approaching this, though.
Hope that helps.

A: Try this:
you don't need else part as it is already present and put your jquery inside document.ready so that it will ensure DOM is ready and you can run the jquery script.
var initialHTML = $('#myselect').html();
   $(document).ready(function(){
     $('#myselect option').each(function(){
        if($(this).text() == 'b'){
            $(this).remove();
            console.log('matching. removed.');
            return false;
        }
    });
   });

JSFiddle


text:
Q: Google App Engine instances stop responding This started happening about 2 weeks ago. I have 2 websites hosted on App Engine. All of a sudden both started showing blank screens on every request. Both had instances running and there were no errors in the logs.
After some trial an error I found that running the deployment (appcfg update) fixes this problem, but only for an hour or so. My colleague also found out that shutting down running instances also gets rid of the blank screen and also for a limited time.
The period during which site remains functional varies from 10 mins to 2 hours. The the blank screen. The logs either show no errors or keep loading forever showing nothing at all.
At the moment I have 2 tasks in scheduled to run every 10 minutes that start deployment scripts for every site. Again, this started happening on 2 sites at the same time and both sites haven't been updated in a while, nor have I changed any app engine related settings for them.

A: Which scaling method you are using for your application ? If you are not sure, then go through the link [1] to understand how to configure scaling in your application . I have a suspicion that ue to scaling issue the instance is unable to response.
[1] https://cloud.google.com/appengine/docs/python/modules/#Python_Instance_scaling_and_class


text:
Q: Add unified shell header in master detail application (SAPUI5) I want to add a  unified shell header to my master detail app, but I don't know where I can write the code.
I want the header become like this picture:

How can I do that?

A: You can find an example of such a usage here on my GitHub. My code there has a little more than just a Master-Detail app, so I will try and sum it up here.
Basically, if you have used the standard Master-Detail template, you have an App view which contains just a split app. This is the root control of you application (i.e. all the master and detail views are children of this control). You can simply surround with a unified shell component (as suggested in the comments).
<mvc:View controllerName="something.App" xmlns:mvc="sap.ui.core.mvc"
    xmlns="sap.m" xmlns:u="sap.ui.unified">
    <u:Shell>
        <SplitApp id="idAppControl"/>
    </u:Shell>
</mvc:View>

Keep in mind though that this only really makes sense if you plan to use the app as a standalone UI5 application. If you are registering it to the Fiori launchpad, then the shell is added automatically by the launchpad itself.
If you want to be able to have the shell both when running the app standalone and when running it from the launchpad, you can move the shell instantiation inside the index.html of your app (basically wrapping the ComponentContainer instance with the unified shell).


text:
Q: Can not read property "document" of undefined - ApexCharts I'm attempting to import apexcharts into my nuxt project. I've used both the vanilla lib and vue wrapper.
Simply importing the library causes the following error

Like I said, i've attempted importing both
import ApexCharts from "apexcharts"
and
import VueApexCharts from "vue-apexcharts"
Both return the same error.
Is this something I have to configure in the nuxt.config.js file?

A: This is because you are using Nuxt.js which does SSR for you. Since document does not exist on the server-side it will break.
To work around it there a couple of approaches:
First you can create a plugin/apex.js which is responsible for registering your components
import Vue from 'vue';
import ApexChart from 'vue-apexcharts';

Vue.component('ApexChart', ApexChart);

and in your nuxt.config.js make sure to load the plugin file on the client-side:
module.exports = {
  // ...
  plugins: [
    // ...
    { src: '~/plugins/charts', ssr: false }
  ],
  // ....
};

Now you can reference the ApexChart component anywhere in your app, also make sure to wrap it with ClientOnly component to prevent Nuxt from attempting to render it on the server-side:
<ClientOnly>
  <ApexChart type="donut" :options="chartData.options" :series="chartData.series" />
</ClientOnly>

The other approach is you can import Apex charts as async components, which do not get rendered on the server-side, but it has been a hit and miss with this approach, feel free to experiment.
Generally when using Nuxt or any SSR solution, be careful of the libraries you use as they might have an implicit dependency on the execution environment, like requiring browser-specific APIs in order to work like window or document.


text:
Q: Specific application of Fourier Transform Let's say I have two frequencies sounding at the same time.
There's a harmonic series above each, right.
I need to know the frequency of the coincidental partial in order to apply a band pass filter around that frequency in real time.
Can this be done?

A: if you have two frequencies, then you have two sinus in superposition.
you have two option to extract one of the frequencies:

*

*do a fft, then in the output you will get the two frequencies represented as two bins, then    select the bin that represent the frequency you are interested in, (this is time consuming if you are doing the fft especially for this reason).

*you can also implement an iir (or fir, iir is usually more efficient) band pass filter around the relevant frequency  (if you have only two frequencies a low pass or high pass will be sufficient).


text:
Q: При загрузке данных из JSON файла, файл неправильно декодируется я делаю discord бота используя discord.py, но у меня возникает неправильное декодирование. Вот мой код:
async def shop(ctx):
    with open('saves.json', 'r+') as f:
        saves = json.load(f)
        emb = discord.Embed(title=f'Магазин {ctx.guild.name}', colour=discord.Color.purple())
        for i in range(len(saves["shop_items"])):
            item = saves["shop_items"][i]
            emb.add_field(name=item["name"], value=f'{item["description"]}.\n Стоимость: **{item["price"]} '
                                                   f'<:tyantherium:1049409159789031454>**.')
        await ctx.reply(embed=emb)

saves.json:
{
    "shop_items": [
        {
            "name": "Ядерная боеголовка",
            "price": 0,
            "description": "УСТРОЙТЕ БОМБЁЖКУ",
            "answer": "Кое где вырос большой ядерный гриб!",
            "role": null
        }
    ]
}

Вот что я получаю в ответ в discord:

Помогите, пожалуйста, ломаю голову над этой ошибкой уже 3 день.


text:
Q: How to solve the improper integral $\int_{-\infty}^{\infty} \frac{x^2}{x^6+9}dx$ (possible trig substitution) $$\int_{-\infty}^{\infty} \frac{x^2}{x^6+9}dx$$ I'm a bit puzzled as how to go about solving this integral. I can see that it isn't undefined on -infinity to infinity. But I just need maybe a hint on how to go about solving the problem.

A: Hint: put $\;u = x^3$, so $\,du \;=\; 3x^2\, dx \;\implies\; x^2\, dx \;= \;\frac 13\, du$
This gives you $$\frac 13 \int_{-\infty}^\infty \frac {du}{u^2 + (3)^2} $$
Look familiar?:
Using one more substitution, let $\quad u =3\tan(\theta),\quad du =3\sec^2(\theta)\,d\theta, \quad \theta=\arctan\left(\frac{u}{3}\right)$
And determine the corresponding bounds for integrating.

A: It is natural to let $u=x^3$. But note that the substitution $x^3=3u$ is more efficient.

A: With complex analysis: define the complex function
$$f(z)=\frac{z^2}{z^6+9}\;\;,\;\;\text{with simple poles at}\,\,\,z_k:=\sqrt[6] 9\,\,e^{\frac{\pi i}{6}(1+2k)}\;\;,\;k=0,1,2,3,4,5$$
Note that the only poles on the upper half plane are the first three ones $\,z_0,\,z_1,\,z_2\,$ , with residues
$$Res_{z=z_0}(f)=Res_{z=z_2}(f)=-\frac{i}{18}\;\;,\;\;\;Res_{z=z_1}(f)=\frac{i}{18}$$
Choosing the contour
$$C_R:=[-R,R]\cup\gamma_R:=\{z\in\Bbb C\;;\;|z|=R\,,\,\Im (z)\ge 0\}$$
we get, by Cauchy's Integral Theorem, that
$$(**)\;\;\;\;\;\;\;2\pi i\left(\sum_{k=0}^2 Res_{z=z_k}(f)\right)=\frac{\pi}{9}=\oint_{C_R}f(z)\,dz=\int\limits_{-R}^Rf(x)\,dx+\int\limits_{\gamma_R} f(z)\,dz$$
But
$$\left|\int\limits_{\gamma_R} f(z)\,dz\right|\le\max_{z\in \gamma_R}\frac{|z|^2}{|z^6+9|}\pi R\le\frac{\pi R^3}{R^6-9}\xrightarrow[R\to\infty]{}0$$
Thus passing to the limit in (**) above we get
$$\int\limits_{-\infty}^\infty\frac{x^2}{x^6+9}dx=\frac{\pi}{9}$$


text:
Q: Query to get the information of Databases used by Stored Procedure in SQL server 2005 Is there any query in SQL server 2005 that returns the list of Stored procedures in the particular database along with the name of databases whose objects are getting used in the stored procedure.

A: This is not a simple thing to do reliably in SQL Server 2005. You might want to look at commercial products such as ApexSQL Clean or SQL Dependency Tracker.
In SQL Server 2008 you could try using the sys.sql_expression_dependencies dynamic management view. For example,
select
    quotename(s.name) + N'.' + quotename(o.name) as ProcedureName,
    ed.referenced_server_name,
    ed.referenced_database_name,
    ed.referenced_schema_name,
    ed.referenced_entity_name
from sys.sql_expression_dependencies  ed
    inner join sys.objects o on o.object_id = ed.referencing_id
    inner join sys.schemas s on s.schema_id = o.schema_id
where
    o.type = 'P'

Hope this helps,
Rhys

A: That is how to get all procedure names:
select *
  from DatabaseName.information_schema.routines
 where routine_type = 'PROCEDURE'

I will check now, if there is any way to check their code for table names.

A: you can use this query
it will show all dependencies even to the columns
SELECT
--SP, View, or Function
ReferencingName = o.name,
ReferencingType = o.type_desc,

--Referenced Field
ref.referenced_database_name, --will be null if the DB is not explicitly called out
ref.referenced_schema_name, --will be null or blank if the DB is not explicitly called out
ref.referenced_entity_name,
ref.referenced_minor_name

FROM sys.objects AS o
cross apply sys.dm_sql_referenced_entities('dbo.' + o.name, 'Object') ref
where o.type = 'p'
-- for other database object types use below line
-- o.type in ('FN','IF','V','P','TF')

A: works for single database
select *
 from information_schema.routines
 where routine_type = 'PROCEDURE'


text:
Q: How to find the bounds of a TypeMirror & turn them into a JavaPoet TypeSpec? I have an annotation processor that takes an annotated class and attempts to create a subclass of it:
package test;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;

import java.io.IOException;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;

@SupportedAnnotationTypes("java.lang.SuppressWarnings")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class BSProcessor extends AbstractProcessor {
    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
        for (TypeElement baseClassAnnotation : annotations) {
            for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(baseClassAnnotation)) {
                handleAnnotatedTypeElement((TypeElement) annotatedElement);
            }
        }
        return true;
    }

    private void handleAnnotatedTypeElement(TypeElement annotatedTypeElement) {
        try {
            javaFile(annotatedTypeElement).writeTo(System.out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private JavaFile javaFile(TypeElement annotatedTypeElement) {
        return JavaFile.builder(packageName(annotatedTypeElement), typeSpec(annotatedTypeElement))
                .build();
    }

    private TypeSpec typeSpec(TypeElement annotatedTypeElement) {
        return TypeSpec.classBuilder(className(annotatedTypeElement))
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .build();
    }

    private ClassName className(TypeElement annotatedTypeElement) {
        return ClassName.get(packageName(annotatedTypeElement), String.format("AutoGenerated_%s",
                annotatedTypeElement.getSimpleName()));
    }

    private String packageName(TypeElement annotatedTypeElement) {
        return annotatedTypeElement.getEnclosingElement().toString();
    }
}

This works with classes without type parameters, but I'm not sure how to do so with them. Performing toString on the type variables will only give the variable name, not the bounds too. Any ideas on how to do this?

A: Type parameters of TypeElement can be retrieved by calling getTypeParameters() and their bounds can be obtained by calling getBounds() on obtained TypeParameterElements. I am assuming, that you are troubled over the following step — which concrete types should be passed to those type parameters to satisfy those bounds.
Unfortunately, this is a problem, that can not be easily solved for arbitrary type (which is what you seems to be after). For example, look at this type:
public abstract class Recursive<UU extends Callable<UU>> {
}

You may intuitively conclude, that it can be implemented by a class like this:
public class Solution extends Recursive<Solution> implements Callable<Solution> {
  @Override
  public Solution call() throws Exception {
    return new Solution();
  }
}

but that's not trivial to automate, and you (probably) do not want to include required machinery in your code.
Instead of trying to solve that problem yourself, I recommend you to take advantage of type erasure and let compiler solve the problem for you:
// returns something like "Map<K, V>", this is NOT what you want!
DeclaredType classType = (DeclaredType) typeElement.asType();

Types types = processingEnvironment.getTypeUtils();
Elements elements = processingEnvironment.getElementUtils();

// this obtains raw type (plain "Map"), with all methods type-erased,
// the compiler is much better at solving type riddles than you!
DeclaredType rawType = types.getDeclaredType(typeElement);

final Collection<? extends ExecutableElement> methods =
    ElementFilter.methodsIn(elements.getAllMembers(typeElement));

// To create a MethodSpec, suitable for the raw type, you should
// call 3-parameter MethodSpec#overriding with type-erased raw class type
// as second parameter and javax.lang.model.util.Types instance as third
MethodSpec newMethod = MethodSpec.overriding(methods.get(0), rawType, types);

As such, the answer to your specific question is "don't pass any type parameters to JavaPoet, use raw types".


text:
Q: Could you give a definition of what is a superior highly composite number using only words? I know very well what is a superior highly composite number, but I would like to see how could we (roughly) define what is a superior highly composite number using only words (using no equations and no inequalities).
The only such definition I've seen is this one found on Wikipedia:

A superior highly composite number is a natural number which has more divisors than any other number scaled relative to the number itself.

A: Natural numbers were involved in countable number of competitions.
The score in an individual competition was calculated as the ratio of the number of divisors of the competing number to the ...

*

*in the $1^{st}$  competition:   ... to the competing number itself

*in the $2^{nd}$ competition:   ... to the square of the competing number

*in the $3^{rd}$  competition:  ... to the cube of the competing number

*    ... and so on ...

The absolute winners of the individual competitions obtained the title Superior highly composite number.


text:
Q: How to set up VirtualBox Bridged Network on Windows 7 Host? I have virtualbox running on a Windows 2008 server, with a guest running ubuntu 10.04. The ubuntu guest is given a static IP of 192.168.1.4, which also has openssh installed. The guest has bridged network setup, I can ping 192.168.1.4 from any machine in the LAN, the ubuntu guest can also access the LAN. However, when I try to PuTTY into the ubuntu machine, I always get "connection refused". Below are some setup details:
ubuntu IP: 192.168.1.4
hosts.allow
sshd : 192.168.1.38

hosts.deny
ALL : ALL

when I the following command, I can see that sshd is listening on port 22:
lsof -i tcp:22

Any idea?
EDIT:
It turned out to be a wrong VirtualBox Bridged Network setup. I give the Ubuntu guest a static IP of 192.168.1.4 (assigned to eth0). Then in the Windows 7 host, in the Network and Sharing Center, there is a new connection named "VirtualBox Host-Only Network" after the bridge is setup, that connection is again given the same static IP of 192.168.1.4. Once I change the "VirtualBox Host-Only Network" to automatically obtain an IP address, it's getting a different IP address of 169.254.249.70(Tentative). And now I can SSH into 192.168.1.4 with no problem, even without touching hosts.allow and hosts.deny.
I've also noticed that in the properties windows (see screenshot below) of the "VirtualBox Host-Only Network", the second checkbox, "VirtualBox Bridged Networking Driver" is unchecked. While the same checkbox of the physical NIC (that is bridged to) is checked. So my further question is: is this how VBox bridged networking supposed to be setup? Any rationale behind this? I'd appreciate if someone could provide some explaination on VBox bridged networking setup on Windows host and I'll accept it as an answer.

A: Here's a similar situation and what I did to resolve.  I had my network settings set to NAT, which resulted in my guest not using the hosts network adapter. The ip was set and then I found out later:
Search for:
I've installed BigBlueButton using the VM, but I can't access it from a browser

On this page:
http://code.google.com/p/bigbluebutton/wiki/FAQ
Even though I switched I needed to refresh my guest network adapter to pick up a new ip address, use the commmand ifconfig in the guest to find out what IP its using and set bbb-conf setip to that ip address result from ifconfig.  The guest will use the host's adapter to get out to the web/network.
For a Putty connection, run this command on your guest:
sudo apt-get install openssh-server
Run Putty with the ip from above (ifconfig result) with port 22.
Here is a good read on host-only networking:
http://christophermaier.name/blog/2010/09/01/host-only-networking-with-virtualbox


text:
Q: How to make this complex layout in JSF? i am trying to make my general layout in primefaces, with 5 different regions (top, left, center, right, bottom).

I already had try a full layout page but in the center container i need a tabview with scroll bar only in the child element and not at center container. If my implement this image layout with full layout page, the scoll bar will be present on the center container. How i can do this?
I dont want to do this with divs. I only want use primefaces components.
thanks for all your help!


text:
Q: Apache  setting affecting  After studying the documentation I wouldn't expect directives in a <Directory> container affect non-filesystem URLs like /server-status in the following (full) config:
DefaultRuntimeDir /var/run/apache2
PidFile /var/run/apache2/apache2.pid
User www-data
Group www-data
ErrorLog /var/log/apache2/error.log
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined
DocumentRoot /var/www/html

Listen 80

LoadModule mpm_worker_module /usr/lib/apache2/modules/mod_mpm_worker.so
LoadModule authz_core_module /usr/lib/apache2/modules/mod_authz_core.so
LoadModule     status_module /usr/lib/apache2/modules/mod_status.so

<Location /server-status>
    SetHandler server-status
</Location>

<Directory />
    Require all denied
</Directory>

Still, if I run Apache/2.4.25 on Debian stretch with this config like
# apache2 -f demo.conf -X

I get
$ curl --head http://localhost/server-status
HTTP/1.1 403 Forbidden

while if I replace denied in the above config with granted, I get
curl --head http://localhost/server-status
HTTP/1.1 200 OK

In other words, the Require directive in the <Directory /> block does affect the reachability of this URL. Which part of the documentation explains this?

A: You only set a single access control:
<Directory />
    Require all denied
</Directory>

The section on directive merging explains that Directory sections get applied first, before directives in Location sections, regardless of how they are ordered in your httpd.conf.
The behaviour you then see is explained in the AuthMerging Directive:

When authorization is enabled, it is normally inherited by each subsequent configuration section, unless a different set of authorization directives is specified. This is the default action...

You don't set any additional access controls in  the <Location /server-status> configuration section that would override the only access control you did set, the Require all denied and that is the access control that gets inherited by the mod-status module in the /server-status webspace.

A: As @ezra-s emphasized on IRC, even for purely virtual URIs (like /server-status in the example config in the question) Apache tries to match the leading part (/ in this case) with the filesystem. For absolute URIs the leading / will always match the DocumentRoot, but further path components may match as well, if they happen to exist under DocumentRoot. We can replace the <Location /server-status> and <Directory /> sections of the config in the question by the following to demonstrate this:
<Location /foo/server-status>
    SetHandler server-status
</Location>

<Location /bar/server-status>
    SetHandler server-status
</Location>

<Directory />
    Require all denied
</Directory>

# The /var/www/html/foo directory exists, this makes /foo/server-status accessible:
<Directory /var/www/html/foo>
    Require all granted
</Directory>

# The /var/www/html/bar directory does not exist, this does not make /bar/server-status accessible:
<Directory /var/www/html/bar>
    Require all granted
</Directory>

# But this helps regardless (through another means):
<Location /bar>
    Require all granted
</Location>

So this is how virtual locations get affected by <Directory> blocks.


text:
Q: Strange Behaviour of a @Html.ActionLink I am crafting a menu with Bootstrap in a razor Layout, but I am in a trouble with a simple @Html.ActionLink,

Editorial

Posts

    @*
@Html.ActionLink("Posts", "Index", "Posts",htmlAttributes: new { role = "menuitem", tabIndex = "-1" })
*@

@Html.ActionLink("Tags", "Index", "Tags", htmlAttributes: new { role = "menuitem", tabIndex = "-1" })

Dropdowns

Example

Aligninment options

Headers

Disabled menu items

The following statement doesn't work like I want
@Html.ActionLink("Tags", "Index", "Tags", htmlAttributes: new { role = "menuitem", tabIndex = "-1" })

This is the rendering which I have:

Editorial

Posts

Tags

Dropdowns

Example

Aligninment options

Headers

Disabled menu items

Why @Html.ActionLink("Tags", "Index", "Tags", htmlAttributes: new { role = "menuitem", tabIndex = "-1" }) are rendered in Tags ?

A: This may solve the issue.
@Html.ActionLink("Tags", "Index", "Tags", null, htmlAttributes: new { role = "menuitem", tabIndex = "-1" })


text:
Q: Apply failed: Couldn't copy file "C:\Program Files\IDA Pro 8.0\python\3\PyQt5\python_3.9\sip.pyd When I run idapyswitch.exe, I encounter this information
Checking installs from "Python Software Foundation"
Checking "Python 3.10 (64-bit)" (3.10)
Found: "C:\Program Files\Python310\" (version: 3.10.5 ('3.10.5150.1013'))
Checking "Python 3.9 (64-bit)" (3.9)
Found: "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\" (version: 3.9.7 ('3.9.7150.1013'))
Checking "Python 3.10" (3.10)
Found: "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0" (version: 3.10.10 ('3.10.10150.1013'))
Ignoring unusable AppStore Python "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\python3.dll"
IDA previously used: "C:\Program Files\Python310\python310.dll" (guessed version: 3.10.5 ('3.10.5150.1013')). Making this the preferred version.
The following Python installations were found:
    #0: 3.10.5 ('3.10.5150.1013') (C:\Program Files\Python310\python3.dll)
    #1: 3.9.7 ('3.9.7150.1013') (C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\python3.dll)
Please pick a number between 0 and 1 (default: 0)
1
Applying version 3.9.7 ('3.9.7150.1013')`

and it said permission denied
Apply failed: Couldn't copy file "C:\Program Files\IDA Pro 8.0\python\3\PyQt5\python_3.9\sip.pyd" to "C:\Program Files\IDA Pro 8.0\python\3\PyQt5\sip.pyd": Permission denied

I'm using IDA 8.0 and Python 3.10.10
I have pick number 0 and it still prompt the same error. How can i fix this


text:
Q: How to conduct a meta-analysis using raw data? I think meta-analyses are a great way of exploring a hypothesis when available evidence is heterogeneous. Usually however when conducting a meta-analysis one puts aggregated data in a model, possibly losing information.
Therefore I am considering gathering data from published research from the authors in order to be able to conduct analysis on 'raw data' rather then aggregated data (my field is neuroscience/psychology/psychiatry).
Questions

*

*Where can I learn more about conducting such analyses?

*Are researchers typically willing to share their data?

*Would ethical guidelines preclude such data sharing?

A: Yes.  It can be a problem especially in scenarios where pharmaceutical clinical trials are involved and due to competition companies may not want to share their data.  Nevertheless such studies have been carried out in recent years in such settings.  Combining raw data when the studies involve the same endpoints and the populations are similar is probably better than using summary data.  But I do think there are situations where summary statistics or even just sample size information along with p-values can be used.  This very much depends on the studies and the goals of the meta-analysis.  In my experience the hardest part of meta analysis studies is deciding which studies should be included and which must be left out.

A: As @Alexander already mentioned, you are looking for an approach that is called "individual participant/person/patient data meta-analysis" (IPD meta-analysis). He also refered to an article by Richard Riley, who has published a lot in this field. Please find below a collection of articles that I used for our advanced meta-analysis class:

*

*Cooper, H., & Patall, E. A. (2009). The relative benefits of
meta-analysis conducted with individual participant data versus
aggregated data. Psychological methods, 14(2), 165–176.
doi:10.1037/a0015565

*Curran, P. J., & Hussong, A. M. (2009). Integrative data analysis:
the simultaneous analysis of multiple data sets. Psychological
methods, 14(2), 81–100. doi:10.1037/a0015914

*Lyman, G. H., & Kuderer, N. M. (2005). The strengths and limitations
of meta-analyses based on aggregate data. BMC Medical Research
Methodology, 5(1), 14.

*(already mentioned) Riley, R. D., Lambert, P. C., & Abo-Zaid, G.
(2010). Meta-analysis of individual participant data: rationale,
conduct, and reporting. BMJ, 340(feb05 1), c221-c221.
doi:10.1136/bmj.c221

*Riley, R. D., Lambert, P. C., Staessen, J. A., Wang, J., Gueyffier,
F., Thijs, L., & Boutitie, F. (2007). Meta-analysis of continuous
outcomes combining individual patient data and aggregate data.
Statistics in Medicine. doi:10.1002/sim.3165

*Simmonds, M. C., Higgins, J. P., Stewart, L. A., Tierney, J. F.,
Clarke, M. J., & Thompson, S. G. (2005). Meta-analysis of individual
patient data from randomized trials: a review of methods used in
practice. Clinical Trials, 2(3), 209–217.

*Stewart, L. A., & Tierney, J. F. (2002). To IPD or not to IPD?
Advantages and disadvantages of systematic reviews using individual
patient data. Evaluation and The Health Professions, 25(1), 76-97.


text:
Q: Finding duplicated data using Python I have a data files which contains "name,time,data" column, I'd like to find out duplicated data (name, time must exactly similar, and data (if any binary data "1" match regardless the position). For example, data below:
Is there any available function can do this?
For example:
name,time,data
tg,0x34,1111
ab,0x54,1011
k,0x34,0100
c,0x34,0001
e,0x34,0000
d, 0x34,1111

duplicated result:
tg,0x34,1111
k,0x34,0100
c,0x34,0001
d, 0x34,1111

A: This seems to be a sorting, grouping, comparing problem.  Not really sure why but I opted for a class that has methods needed for sorting, grouping and comparing. ... Python 2.7 code:
Setup;
import io, collections, operator, csv

s = '''name,time,data
tg,0x34,1111
ab,0x54,1011
k,0x34,0100
c,0x34,0001
e,0x34,0000
d,0x34,1111'''

# for file emulation
f = io.BytesIO(s)

Class to hold the info and work with Python tools
class Thing(object):
    def __init__(self, name = None, time = None, data = None):
        self. name = name
        self.time = time
        self.data = data
    def __eq__(self, other):
        'For comparison'
        equal = self.time == other.time
        # equal if there is a one in both things at the same bit position
        equal = equal and bool(int(self.data, base = 2) &
                               int(other.data, base = 2))
        return equal
    def __lt__(self, other):
        'For sorting'
        return self.time < other.time
    def __str__(self):
        return '({}, {}, {})'.format(self.name, self.time, self.data)
    def __repr__(self):
        return '({}, {}, {})'.format(self.name, self.time, self.data)

Use the csv module to make a list of Thing's and sort them (by time):
reader = csv.DictReader(f)
things = [Thing(**row) for row in reader]
things.sort()

Use itertools.groupby and itertools.combination to compare thing's with the same time.  Put things that are equal in a set.
results = set()
for key, group in itertools.groupby(things, key = operator.attrgetter('time')):
    print key
    for a, b in itertools.combinations(group, 2):
        if a == b:
            print '\t{} is duplicate of {}'.format(a, b)
            results.add(a)
            results.add(b)

This results in
>>>
0x34
    (tg, 0x34, 1111) is duplicate of (k, 0x34, 0100)
    (tg, 0x34, 1111) is duplicate of (c, 0x34, 0001)
    (tg, 0x34, 1111) is duplicate of (d, 0x34, 1111)
    (k, 0x34, 0100) is duplicate of (d, 0x34, 1111)
    (c, 0x34, 0001) is duplicate of (d, 0x34, 1111)
0x54
>>> results
set([(tg, 0x34, 1111), (c, 0x34, 0001), (d, 0x34, 1111), (k, 0x34, 0100)])
>>>

Not sure if I understood the specs - the following dataset produces zero duplicates:
s = '''name,time,data
tg,0x34,0010
ab,0x54,1011
k,0x34,0100
c,0x34,0001
e,0x34,0000
d,0x34,1000'''

You probably want to keep duplicates for different times separate so keep them in a dictionary using the time as the key.
results = collections.defaultdict(set)
for key, group in itertools.groupby(things, key = operator.attrgetter('time')):
    print key
    for a, b in itertools.combinations(group, 2):
        if a == b:
            print '\t{} is duplicate of {}'.format(a, b)
            results[key].update((a,b))


text:
Q: bash: cat + grep to produce several replicas merging two filles Using Linux bash command line, I need to merge two filles integrating several copies of the file1 inside the specified part of the file 2. The file 1 looks like:
ATOM      1  N   SER A   1      -2.390   4.343 -17.003  1.00 27.76           N1+
ATOM      2  CA  SER A   1      -2.066   5.647 -16.370  1.00 27.12           C
ATOM      3  C   SER A   1      -2.394   5.608 -14.874  1.00 26.29           C
ATOM      4  O   SER A   1      -3.014   4.627 -14.405  1.00 22.93           O
ATOM      5  CB  SER A   1      -2.771   6.798 -17.057  1.00 28.10           C
ATOM      6  OG  SER A   1      -2.538   8.023 -16.373  1.00 32.02           O
ATOM      7  N   GLY A   2      -1.982   6.655 -14.162  1.00 25.31           N
ATOM      8  CA  GLY A   2      -2.172   6.779 -12.716  1.00 24.93           C
ATOM      9  C   GLY A   2      -0.888   6.336 -12.067  1.00 23.66           C
ATOM     10  O   GLY A   2      -0.168   5.459 -12.608  1.00 27.42           O
ATOM     11  N   PHE A   3      -0.636   6.866 -10.900  1.00 22.07           N
ATOM     12  CA  PHE A   3       0.622   6.595 -10.191  1.00 21.70           C
ATOM     13  C   PHE A   3       0.279   6.570  -8.716  1.00 20.39           C
ATOM     14  O   PHE A   3      -0.265   7.544  -8.167  1.00 23.83           O

the file 2 is a multi-block, where separate parts are defined by model1,model 2, model N and separated by ENDMDL:
MODEL 1
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ENDMDL
MODEL 2
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ENDMDL
MODEL 3
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ENDMDL

I need to copy several times all the containt of the file 1 into the file 2 just before the separator ENDMDL (in the second file), thus  integrating several coppies of the file 1 into the file 2. Here is the example of expected output:
MODEL 1
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ATOM      1  N   SER A   1      -2.390   4.343 -17.003  1.00 27.76           N1+
ATOM      2  CA  SER A   1      -2.066   5.647 -16.370  1.00 27.12           C
ATOM      3  C   SER A   1      -2.394   5.608 -14.874  1.00 26.29           C
ATOM      4  O   SER A   1      -3.014   4.627 -14.405  1.00 22.93           O
ATOM      5  CB  SER A   1      -2.771   6.798 -17.057  1.00 28.10           C
ATOM      6  OG  SER A   1      -2.538   8.023 -16.373  1.00 32.02           O
ATOM      7  N   GLY A   2      -1.982   6.655 -14.162  1.00 25.31           N
ATOM      8  CA  GLY A   2      -2.172   6.779 -12.716  1.00 24.93           C
ATOM      9  C   GLY A   2      -0.888   6.336 -12.067  1.00 23.66           C
ATOM     10  O   GLY A   2      -0.168   5.459 -12.608  1.00 27.42           O
ATOM     11  N   PHE A   3      -0.636   6.866 -10.900  1.00 22.07           N
ATOM     12  CA  PHE A   3       0.622   6.595 -10.191  1.00 21.70           C
ATOM     13  C   PHE A   3       0.279   6.570  -8.716  1.00 20.39           C
ATOM     14  O   PHE A   3      -0.265   7.544  -8.167  1.00 23.83           O
ENDMDL
MODEL 2
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ATOM      1  N   SER A   1      -2.390   4.343 -17.003  1.00 27.76           N1+
ATOM      2  CA  SER A   1      -2.066   5.647 -16.370  1.00 27.12           C
ATOM      3  C   SER A   1      -2.394   5.608 -14.874  1.00 26.29           C
ATOM      4  O   SER A   1      -3.014   4.627 -14.405  1.00 22.93           O
ATOM      5  CB  SER A   1      -2.771   6.798 -17.057  1.00 28.10           C
ATOM      6  OG  SER A   1      -2.538   8.023 -16.373  1.00 32.02           O
ATOM      7  N   GLY A   2      -1.982   6.655 -14.162  1.00 25.31           N
ATOM      8  CA  GLY A   2      -2.172   6.779 -12.716  1.00 24.93           C
ATOM      9  C   GLY A   2      -0.888   6.336 -12.067  1.00 23.66           C
ATOM     10  O   GLY A   2      -0.168   5.459 -12.608  1.00 27.42           O
ATOM     11  N   PHE A   3      -0.636   6.866 -10.900  1.00 22.07           N
ATOM     12  CA  PHE A   3       0.622   6.595 -10.191  1.00 21.70           C
ATOM     13  C   PHE A   3       0.279   6.570  -8.716  1.00 20.39           C
ATOM     14  O   PHE A   3      -0.265   7.544  -8.167  1.00 23.83           O
ENDMDL
MODEL 3
REMARK VINA RESULT:    -7.828      0.000      0.000
REMARK INTER + INTRA:         -13.769
REMARK INTER:                 -10.110
REMARK INTRA:                  -3.659
REMARK UNBOUND:                -3.196
ATOM      1  N   SER A   1      -2.390   4.343 -17.003  1.00 27.76           N1+
ATOM      2  CA  SER A   1      -2.066   5.647 -16.370  1.00 27.12           C
ATOM      3  C   SER A   1      -2.394   5.608 -14.874  1.00 26.29           C
ATOM      4  O   SER A   1      -3.014   4.627 -14.405  1.00 22.93           O
ATOM      5  CB  SER A   1      -2.771   6.798 -17.057  1.00 28.10           C
ATOM      6  OG  SER A   1      -2.538   8.023 -16.373  1.00 32.02           O
ATOM      7  N   GLY A   2      -1.982   6.655 -14.162  1.00 25.31           N
ATOM      8  CA  GLY A   2      -2.172   6.779 -12.716  1.00 24.93           C
ATOM      9  C   GLY A   2      -0.888   6.336 -12.067  1.00 23.66           C
ATOM     10  O   GLY A   2      -0.168   5.459 -12.608  1.00 27.42           O
ATOM     11  N   PHE A   3      -0.636   6.866 -10.900  1.00 22.07           N
ATOM     12  CA  PHE A   3       0.622   6.595 -10.191  1.00 21.70           C
ATOM     13  C   PHE A   3       0.279   6.570  -8.716  1.00 20.39           C
ATOM     14  O   PHE A   3      -0.265   7.544  -8.167  1.00 23.83           O
ENDMDL

I have tried to use cat BUT it just fused the both files together without the required replication of the first file:
cat file1.pdb file2.pdb > together.pdb

Need I pipe this to some expression of grep in order to replicate the file1  in the positions before the  ENDMDL of the file 2 ?

A: Use awk.
awk '/^ENDMDL$/ {system("cat file1.pdb");}; {print}' file2.pdb

Each line from file2 is written to standard output, but when the line matches ENDMDL, the entire contents of file1 are output first.
Some alternatives:

*

*Replace /^ENDMDL$/ with $0 == "ENDMDL"

*Replace {print} with 1. (With no explicit pattern, the action is performed. With no explicit action, the current line is printed.)

A: Here is an awk solution that doesn't call unsafe system or getline:
awk 'NR==FNR {s = s $0 ORS; next} $0 == "ENDMDL" {$0 = s $0} 1' file1 file2

If you want to pass shell variable names then use:
awk 'NR==FNR {s = s $0 ORS; next}
$0 == "ENDMDL" {$0 = s $0} 1' "$file1" "$file2"

A: Here's a straight-forward awk solution:
awk '
    BEGIN {
        FS = RS = "\a"
        getline contents < ARGV[2]
        close(ARGV[2])
        ARGV[2] = ""
        RS = "\n"
    }
    /^ENDMDL$/ { printf "%s", contents }
    { print }
' file1 file2

The script slurps the file content (the one to be inserted) into a variable then prints it each time ENDMDL appears. I'm using the BELL character as FS and RS because you won't encounter it in a PDB file.


text:
Q: Adding a checkbox column to the infragistics ultrawingrid that is bind to a datasource I am trying to add a new checkbox column to the ultrawingrid that is binding to a dataset, when ever I add a new column it says key not found, any ideas on how to fix it, Thank you...
Below is the code
private void grdPayVis_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{

    var gridBand = grdPayVis.DisplayLayout.Bands[0];

    gridBand.Columns["Select"].Header.Caption = "Select";
    gridBand.Columns["Select"].Header.Appearance.TextHAlign = HAlign.Center;
    gridBand.Columns["Select"].Header.VisiblePosition = 0;
    gridBand.Columns["Select"].Hidden = false;
    gridBand.Columns["Select"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
    gridBand.Columns["Select"].AutoSizeMode = ColumnAutoSizeMode.AllRowsInBand;
    gridBand.Columns["Select"].CellActivation = Activation.AllowEdit;
    gridBand.Columns["Select"].CellAppearance.TextHAlign = HAlign.Center;
    gridBand.Columns["Select"].CellClickAction = CellClickAction.Edit;

}

Swetha

A: Steve's answer above is good, but it can be simplified and made better in a couple of ways.
First, a lot of that code isn't really necessary. For example, the default Hidden state of a column is false, so there's no need to set that. Same for AutoSizeMode and CellClickAction.
Also, if you add an unbound column, it's default DataType is string, which doesn't make a lot of sense for a CheckBox column. By setting the DataType to bool, you can avoid the need to set the Style and also clear up the problem of every cell being indeterminate by default.
    private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
    {
        UltraGridLayout layout = e.Layout;
        UltraGridBand rootBand = layout.Bands[0];

        if (false == rootBand.Columns.Exists("Select"))
        {
            UltraGridColumn checkBoxColumn = rootBand.Columns.Add("Select");
            checkBoxColumn.Header.VisiblePosition = 0;
            checkBoxColumn.DataType = typeof(bool);
        }
    }

As for determining the value of the cell and keeping track of the 'selected' rows, you have to understand a little bit about how the grid cell editors work. To really understand it, imagine a cell that contains DateTime info. The user enters the cell and intends to type in a date, like '1/19/2015'. When the user begins typing, he starts by typing a '1'. If you check the cell's value at this point, the grid cannot possibly convert the current text in the cell ("1") into a date. So because of this, the grid doesn't attempt to update the underlying data source with the value until something else happens, like if the user leaves the cell or loses focus on the grid.
Of course, if the cell has a checkbox, then this problem doesn't exist, since the user is incapable of entering an invalid value, but the grid still works the same way and doesn't update the value until the user leaves the cell.
So... when you are dealing with any cell that is NOT in edit mode (not currently active) then you can use the Value property of the cell reliably. When the cell is in edit mode (is active) then you can't rely on the Value, which reads from the data source, you have to use the cell's Text.
Therefore, given any cell in a boolean (checkbox) column, to get an accurate reflection of the current state of the checkbox on the screen, you would do something like this:
    private bool GetCheckBoxCellCurrentValue(UltraGridCell cell)
    {
        if (cell.IsInEditMode)
            return bool.Parse(cell.Text);
        else
            return (bool)cell.Value;
    }

Finally, the grid doesn't keep any kind of list of the 'checked' cells. But you could do this yourself without too much difficulty. What you would have to do is build the initial list right after you bind the grid. Then trap events such as CellChange, AfterRowAdded, BeforeRowDeleted, and perhaps some others to continuously keep your list up to date.

A: When the grid has its datasource set to a datatable or other binding source, it automatically creates the columns present in the datatable or in the properties of the datasource. If you want to have another column you need to ADD it before trying to reference it from the Band columns
private void grdPayVis_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
    var gridBand = grdPayVis.DisplayLayout.Bands[0];

    // Check if the column exists, if not, add it
    if(!gridBand.Columns.Exists("Select"))
        gridBand.Columns.Add("Select", "Select");

    // Not needed, the ADD adds the Key and the Caption
    // gridBand.Columns["Select"].Header.Caption = "Select";

    // Now you can reference the column with the Key = "Select"
    gridBand.Columns["Select"].Header.VisiblePosition = 0;
    gridBand.Columns["Select"].Hidden = false;
    gridBand.Columns["Select"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
    gridBand.Columns["Select"].AutoSizeMode = ColumnAutoSizeMode.AllRowsInBand;
    gridBand.Columns["Select"].CellClickAction = CellClickAction.Edit;
}


text:
Q: LDAPException size limit exceeded I am using unboundid ldap sdk for executing ldap query. I am facing a strange problem while running ldap search query. I am getting a Exception when i run query against a group which contains 50k entries. My Exception :
LDAPException(resultCode=4 (size limit exceeded), errorMessage='size limit exceeded')
at com.unboundid.ldap.sdk.migrate.ldapjdk.LDAPSearchResults.nextElement(LDAPSearchResults.java:254)
at com.unboundid.ldap.sdk.migrate.ldapjdk.LDAPSearchResults.next(LDAPSearchResults.java:279)

Now the strange thing is i already have set the maxResultSize to 100k in search constrains than why i am getting this error ?
My code is
     ld = new LDAPConnection();
    ld.connect(ldapServer, 389);

    LDAPSearchConstraints ldsc = new LDAPSearchConstraints();
    ldsc.setMaxResults(100000);
    ld.setSearchConstraints(ldsc);

Anybody have any idea ?

A: Sorry for necroposting, but your topic with no answer is still the first in google.
Using unboundid you actually can get unlimited number of records in  paging mode.
public static void main(String[] args) {

try {
    int count = 0;
    LDAPConnection connection = new LDAPConnection("hostname", 389, "user@domain", "password");

    final String path = "OU=Users,DC=org,DC=com";
    String[] attributes = {"SamAccountName","name"};

    SearchRequest searchRequest = new SearchRequest(path, SearchScope.SUB, Filter.createEqualityFilter("objectClass", "person"), attributes);

    ASN1OctetString resumeCookie = null;
    while (true)
    {
        searchRequest.setControls(
                new SimplePagedResultsControl(100, resumeCookie));
        SearchResult searchResult = connection.search(searchRequest);
        for (SearchResultEntry e : searchResult.getSearchEntries())
        {
            if (e.hasAttribute("SamAccountName"))
                System.out.print(count++ + ": " + e.getAttributeValue("SamAccountName"));

            if (e.hasAttribute("name"))
                System.out.println("->" + e.getAttributeValue("name"));
        }

        LDAPTestUtils.assertHasControl(searchResult,
                SimplePagedResultsControl.PAGED_RESULTS_OID);
        SimplePagedResultsControl responseControl =
                SimplePagedResultsControl.get(searchResult);
        if (responseControl.moreResultsToReturn())
        {
            resumeCookie = responseControl.getCookie();
        }
        else
        {
            break;
        }
    }

}
catch (Exception e)
{
    System.out.println(e.toString());
}

}

A: Check the server-side size limit setting.  It prevails over the client-side setting which is what you're doing in your code.


text:
Q: Http post request with body parameters not working Recently I started developing a small application in Flutter. I have an issue with making a network request. I have tried the call in postman and there it work. But in Flutter I never managed to make it work, I have spent like 3 hours trying to understand what I am doing wrong.
Any help will be greatly appreciated.
 @override
  Future<String> login(common.LoginParameters loginParameters) async {
    try {

      final String loginURL = "https://test.example.eu/api/login";

      LoginModel loginResult;

      Map bodyParams = { "inlognaam" : loginParameters.username , "wachtwoord" : loginParameters.password, "code" : loginParameters.smsCode};

      //await API call
      http.Response httpResponse = await http.put( loginURL, body: json.encode(bodyParams));

      if (httpResponse.statusCode == 200) {
        // If server returns an OK response, parse the JSON
        loginResult=  LoginModel.fromJson(json.decode(httpResponse.body));
      } else {
        // If that response was not OK, throw an error.
        throw Exception('Failed to load post');
      }

      // if logged in get token, Otherwise return error
      if (loginResult.ingelogd) {
        // read the token

        saveToken(loginResult.response);
        return "Ingelogd";
      } else {
        return loginResult.error;
      }
    }
    on Exception catch(error) {
      print("Todor " + error.toString());
      return "Controleer uw internet verbinding en probeer opnieuw";
    }
  }

In Postman if I select Post request with body parameters
inlognaam : someUsername
wachtwoord : somePassword
code : someCode
Then I get a success response

A: I pass the parameters in the following way, maybe it can work for you:
var response = await http.post(
url,
headers:{ "Accept": "application/json" } ,
body: { "state": 1}, //key value
encoding: Encoding.getByName("utf-8")
);

Another thing, you say that in postman you make a post request, but in your code you have a put request, verify what is the correct method


text:
Q: How To Delay Invoke-WebRequest Until Task is Complete or Make Invoke-WebRequest Actively Update I'm trying to write a Web-Request to speedtest.net to run an internet speed test and return the results, but since the speed test takes time and I'm not getting the results in .content, I suspect that the speed test process is not updating the request after it's completed. It could also be that
I'm not understanding how to pull the data. I just learned about invoke-webrequest yesterday so it's likely that I just don't understand how to use it yet. Also, the speedtest.exe is blocked through our network, otherwise I would have used that.
My script is as follows:
$URL = "www.speedtest.net/"
$site = Invoke-WebRequest $URL -UseBasicParsing
$Testpath = ($site.Links | Where-Object onclick -icontains "window.ookla.globals.shouldstartonload = true;").href
$site = Invoke-WebRequest "$url$testpath" -SessionVariable TestSession -UseBasicParsing

As far as pulling the data, I'm trying to use this which pulls nothing. I got the class name from speedtest.net with Chrome inspect element. I've also tried using $site.split() and using select-string
$site.content | where-object class -icontains "result-data-large number result-data-value download-speed"

A: Did you ever figure out how to do this?
I was able to complete with the cli, but I don't want to use an exe either.
######### Absolute monitoring values ##########
$maxpacketloss = 2 #how much % packetloss until we alert.
$MinimumDownloadSpeed = 100 #What is the minimum expected download speed in Mbit/ps
$MinimumUploadSpeed = 2 #What is the minimum expected upload speed in Mbit/ps
######### End absolute monitoring values ######

# Replace the Download URL to where you've uploaded the ZIP file yourself. We will only download this file once.
# Latest version can be found at: https://www.speedtest.net/apps/cli
$DownloadURL = "https://install.speedtest.net/app/cli/ookla-speedtest-1.2.0-win64.zip"
$DownloadLocation = "$($Env:ProgramData)\SpeedtestCLI"
try {
$TestDownloadLocation = Test-Path $DownloadLocation
    if (!$TestDownloadLocation) {
        New-Item $DownloadLocation -ItemType Directory -force
        Invoke-WebRequest -Uri $DownloadURL -OutFile "$($DownloadLocation)\speedtest.zip"
        Expand-Archive "$($DownloadLocation)\speedtest.zip" -DestinationPath $DownloadLocation -Force
    }
}
catch {
    Write-Output -InputObject "The download and extraction of SpeedtestCLI failed. Error: $($\_.Exception.Message)"
exit 1
}
$PreviousResults = if (test-path "$($DownloadLocation)\LastResults.txt") { get-content "$($DownloadLocation)\LastResults.txt" | ConvertFrom-Json }
$SpeedtestResults = & "$($DownloadLocation)\speedtest.exe" --format=json --accept-license --accept-gdpr
$SpeedtestResults | Out-File "$($DownloadLocation)\LastResults.txt" -Force
$SpeedtestResults = $SpeedtestResults | ConvertFrom-Json

# Creating object
[PSCustomObject]$SpeedtestObj = @{
    downloadspeed = [math]::Round($SpeedtestResults.download.bandwidth / 125000, 2)
    uploadspeed = [math]::Round($SpeedtestResults.upload.bandwidth / 125000, 2)
    packetloss = [math]::Round($SpeedtestResults.packetLoss)
    isp           = $SpeedtestResults.isp
    ExternalIP    = $SpeedtestResults.interface.externalIp
    InternalIP    = $SpeedtestResults.interface.internalIp
    UsedServer    = $SpeedtestResults.server.host
    ResultsURL    = $SpeedtestResults.result.url
    Jitter        = [math]::Round($SpeedtestResults.ping.jitter)
    Latency = [math]::Round($SpeedtestResults.ping.latency)
}
$SpeedtestHealth = @()
# Comparing against previous result. Alerting is download or upload differs more than 20%.
if ($PreviousResults) {
    if ($PreviousResults.download.bandwidth / $SpeedtestResults.download.bandwidth * 100 -le 80) { $SpeedtestHealth += "Download speed difference is more than 20%" }
    if ($PreviousResults.upload.bandwidth / $SpeedtestResults.upload.bandwidth * 100 -le 80) { $SpeedtestHealth += "Upload speed difference is more than 20%" }
}

# Comparing against preset variables.
if ($SpeedtestObj.downloadspeed -lt $MinimumDownloadSpeed) { $SpeedtestHealth += "Download speed is lower than $MinimumDownloadSpeed Mbit/ps" }
if ($SpeedtestObj.uploadspeed -lt $MinimumUploadSpeed) { $SpeedtestHealth += "Upload speed is lower than $MinimumUploadSpeed Mbit/ps" }
if ($SpeedtestObj.packetloss -gt $MaxPacketLoss) { $SpeedtestHealth += "Packetloss is higher than $maxpacketloss%" }

if (!$SpeedtestHealth) {
$SpeedtestHealth = "Healthy - ISP: $($speedtestObj.isp) Download Speed: $($SpeedtestObj.downloadspeed) Upload Speed: $($speedtestObj.uploadspeed) Jitter: $($speedtestObj.jitter) Lattency:Lattency: $($speedtestObj.Latency) PacketLoss: $($speedtestObj.packetLoss)"
}

Write-Output -InputObject $SpeedtestObj


text:
Q: XUnit Using a Dictionary As MemberData I am having trouble with the syntax of how to get an XUnit Test Method to accept a dictionary as a paramater. This is my code which is broken:
Public static Dictionary<string, string> vals = new Dictionary<string, string> { { "a", "1" }, { "b", "2" }, { "ca", "3" } };
public static object[] dicList = new object[] { vals };

[Theory]
[MemberData(nameof(dicList))]

public void CheckSomething_ReturnsSomething(Dictionary<string, string> values)
{
 test stuff...

I am getting an error I understand from the error thrown that I need a return type of
IEnumerable<object[]>

I am unsure of how to achieve this with a dictionary.
Have added some code as suggested: I am still getting an error:
public static Dictionary<string, string> vals = new Dictionary<string, string> { { "a", "1" }, { "b", "2" }, { "ca", "3" } };
public static IEnumerable<object[]> dicList = new List<object[]> { new object[] { vals } };
[Theory]
[MemberData(dicList)] //error here
    public void DriverLogon_CheckParams(Dictionary<string, string> values)
    {
    }

The new error is
error. "Cannot convert from IEnumerable<object[]> To string

A: The dicList must be an IEnumerable<object[]> like the error message says. This is because one item in the dicList contains all the parameter values for one test (this doesn't matter for your case since you only have one parameter, but it's good to know).
So your dicList becomes a List<object[]> instead of just plain object array:
public static Dictionary<string, string> vals = new Dictionary<string, string> { { "a", "1" }, { "b", "2" }, { "ca", "3" } };
public static IEnumerable<object[]> dicList = new List<object[]> { new object[] { vals } };