text:
Q: Can file copy failures be caused by file content? I was copying some files from my laptop's hard drive on to a USB thumb drive/pen drive/key/stick earlier today, using KDE 5 to do the copy (drag and drop in Dolphin). I encountered a problem: the copy operation would finish the first file and then stop, or at least pause long enough that it exceeded my patience. It never advanced to the second file.
A friend who was present at the time suggested that this could be caused by CRC errors, namely that there's something about the content of the file itself that means it's never going to pass some CRC check that Linux or KDE is doing behind the scenes. This sounds fishy to me. Not that there may be "hidden" checksums or other verification procedures built into the copy operation at sum level (:-P); that's totally reasonable. But I would expect these verification procedures to be able to cope with any sequence of bytes whatsoever, because the content of a file can be literally anything. Right?
In short, what I'm asking is this: if a file copy operation fails, is there any possible way that failure could be caused by the content of the copied file, and not by a hardware error nor a bug in the software that handles copying?
I suspect the real problem in my case was a hardware error on the USB drive, but it doesn't really matter.

A: This may be a case where both of you are correct.  To quote from Cool Hand Luke, "What we've got here is failure to communicate".
You are correct, there is no content that could cause failure of a copy operation in the manner you describe.
However, you may have misinterpreted what your friend was saying. If verification is happening, the error stems from the source and destination files being compared. An error would mean that the file wasn't faithfully copied (for some reason independent of file content), not that the source file contained content that was already in error or was impossible to copy.


text:
Q: How do I surround different blocks of code with the same repeating block of code? For instance:
public void foo(string something, Boolean flag, Object obj){
  try{
    if(flag){
       //some code
    }
 } catch(Exception e) {
     // handle exception
 }
}

public void doo(string something, Boolean flag){
  try{
    if(flag){
       //different code
    }
 } catch(Exception e) {
     // handle exception
 }
}

public void roo(string something, Boolean flag, Integer id){
  try{
    if(flag){
       //a bit of code
    }
 } catch(Exception e) {
     // handle exception
 }
}

My question is, is there any way to not have all the repeating code in every function (e.g. the try-catch blocks and the ifs)? It would really clear up my project and would help me focus on the important code.

A: What about passing a Runnable to a new method that catch exceptions?
public void foo(String something, Boolean flag, Object obj) {
    runSafe(something, flag, () => /*some code capturing obj*/);
}

public void doo(String something, Boolean flag) {
    runSafe(something, flag, () => /*different code*/);
}

public void roo(String something, Boolean flag, Integer id) {
    runSafe(something, flag, () => /*some code capturing id*/);
}

private void runSafe(string something, Boolean flag, Runnable r) {
    try {
        if (flag) {
            r.run();
        }
    } catch(Exception e) {
        // handle exception
    }
}

However, passing a boolean saying whether or not to execute code looks wrong to me. Why don't you use some sort of null-object implementation of these methods (doing nothing) instead of passing false?

A: You can surround with try-catch the call of this methods. If you need a unique response for each Exception, you can either create an object that extends Exception, or just use the Exception constructor with a string message.

A: This may not be what you want to hear but you may want to consider cutting down on your try/catch blocks.
https://softwareengineering.stackexchange.com/questions/145941/efficient-try-catch-block-usage

redpajama_set_name: RedPajamaStackExchange


text:
Q: High latency, packet loss and keyboard lag when typing on an OpenVPN client I have an OpenVPN server that has two clients in the subnet. When I ssh from Client 1 to Client 2, there is long lag when I type and when letter appears in terminal. SSH from OpenVPN server to Client 2, there is no lag. There is lag between OpenVPN server and Client 2 back and forth using SSH. All three nodes are running Debian, the server is configured UDP. How can I begin to troubleshoot this?
Did the ping test and the results are"

*

*Ping from client 1 to client 2 via the tunnel

20 packets transmitted, 14 received, 30% packet loss, time 19169ms

rtt min/avg/max/mdev = 70.827/72.071/78.295/1.815 ms

*Ping from client 2 to client 1 via the tunnel

60 packets transmitted, 55 received, 8% packet loss, time 59383ms

rtt min/avg/max/mdev = 70.730/176.441/5773.739/761.702 ms, pipe 6

*Ping from OpenVPN server to client 2: Here the avg latency varies from 35 ms to 1741 ms. The results below are from second trial of ping.

20 packets transmitted, 20 received, 0% packet loss, time 19251ms

rtt min/avg/max/mdev = 26.454/1741.058/5625.208/1952.415 ms, pipe 6

*Ping from Client 2 to OpenVPN server

20 packets transmitted, 20 received, 0% packet loss, time 19251ms

rtt min/avg/max/mdev = 26.454/1741.058/5625.208/1952.415 ms, pipe 6

*Ping from Client 1 to OpenVPN server

Try 1: Significant packet loss
38 packets transmitted, 27 received, 28% packet loss, time 37260ms

rtt min/avg/max/mdev = 44.601/516.754/6025.636/1480.910 ms, pipe 6

Try 2: Not much packet loss

20 packets transmitted, 20 received, 0% packet loss, time 19022ms

rtt min/avg/max/mdev = 44.712/98.499/1077.521/224.708 ms, pipe 2

*Ping from OpenVPN server to client 1

Try 1:

20 packets transmitted, 20 received, 0% packet loss, time 19027ms

rtt min/avg/max/mdev = 44.703/44.979/45.196/0.192 ms

Try 2:

20 packets transmitted, 20 received, 0% packet loss, time 19028ms

rtt min/avg/max/mdev = 44.759/76.936/678.993/138.122 ms```


text:
Q: How to change the database schema with Oracle Workspace Manager versioned tables We have an Oracle database that uses Oracle Workspace Manager (OWM) to version several of our tables. Currently we are supporting 4 workspaces in our system. We have now identified the need to change our database schema by introducing a new table to help create a level of abstraction. The current schema looks like the following:

       Table A ---- FK ----> Table B
           |
           |
            ------- FK ----> Table C

We want it to look like the following:

        Table A ------ FK ----> Table A' ----- FK ------> Table B
                                    |
                                    |
                                     ---------- FK ------> Table C

Table A is a version enabled table, while both Table B and C are not version enabled. We would like to keep Table B and C not-version enabled after the migration, and ideally Table A' would also not be version enabled. We would also like to have these foreign key columns to be non-nullable in their tables.
Any idea on how to accomplish this schema migration?

A: Why would you use OWM anyhow? There is little support for it and there aren't any serious projects that use OWM that I'm aware of. Good luck.


text:
Q: How define action in the case of different parameters? - asp.net mvc4 I try define actions for diff params but its not working:
public class HomeController : Controller
  {
    public ActionResult Index()
    {
      return  View();
    }

    public ActionResult Index(string name)
    {
      return new JsonResult();
    }

    public ActionResult Index(string lastname)
    {
      return new JsonResult();
    }

    public ActionResult Index(string name, string lastname)
    {
      return new JsonResult();
    }
    public ActionResult Index(string id)
    {
      return new JsonResult();
    }
 }

but i get error:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods ....
Edit:
If it not possible please suggest the best way to do it.
Thanks,
Yosef

A: You could use the ActionNameAttribute attribute:
[ActionName("ActionName")]

Then, you'd have different names for each of the Action methods.

A: You cannot have overloaded action methods when they respond to same type of requests(GET, POST etc.). You should have a single public method with all the parameters you need. If the requests don't provide them they will be null and you can decide which overload you can use.
For this single public method you can take advantage of default model binding by defining a model.
public class IndexModel
{
    public string Id { get; set;}
    public string Name { get; set;}
    public string LastName { get; set;}
}

Here's how your controller should look like:
public class HomeController : Controller
{
    public ActionResult Index(IndexModel model)
    {
        //do something here
    }
}

A: These two can't live together because the compiler can't tell them apart.  Either rename them or delete one, or add an additional param.  This is true for all classes.
public ActionResult Index(string name)
{
  return new JsonResult();
}

public ActionResult Index(string lastname)
{
  return new JsonResult();
}

Try using a single method with default parameters:
    public ActionResult Index(int? id, string name = null, string lastName = null)
    {
        if (id.HasValue)
        {
            return new JsonResult();
        }

        if (name != null || lastName != null)
        {
            return new JsonResult();
        }

        return View();
    }

OR
    public ActionResult Index(int id = 0, string name = null, string lastName = null)
    {
        if (id > 0)
        {
            return new JsonResult();
        }

        if (name != null || lastName != null)
        {
            return new JsonResult();
        }

        return View();
    }


text:
Q: using hook on OPENFILEW dialog disables resize control Using this code the resulting dialog box is drawn without ability to be able to be resized by mouse:
#include <windows.h>

static UINT_PTR CALLBACK OFNHookProc (HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam) {
  return 0;
}

int main() {
  OPENFILENAMEW ofn;
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(OPENFILENAMEW);
  ofn.nMaxFile = MAX_PATH;
  ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_ENABLEHOOK;
  ofn.lpfnHook = OFNHookProc;
  GetOpenFileNameW(&ofn);
  return 0;
}

Removing OFN_ENABLEHOOK shows correct dialog window with resize indicator at bottom right corner. How to make dialog that is user-resizeable and with hook procedure ?
(of course that hook is mock here, only to illustrate the error, no matter what I put inside, of course if it is correct on other matters, result is the same)

A: You need to include the OFN_ENABLESIZING flag when using OFN_ENABLEHOOK.  This is documented behavior:
OPENFILENAME structure

OFN_ENABLESIZING
  0x00800000
  Enables the Explorer-style dialog box to be resized using either the mouse or the keyboard. By default, the Explorer-style Open and Save As dialog boxes allow the dialog box to be resized regardless of whether this flag is set. This flag is necessary only if you provide a hook procedure or custom template. The old-style dialog box does not permit resizing.


text:
Q: How to implement the same querying logic for both database and collections So far I've used OrmLite's QueryBuilder for implementation of filtering logic in my project. However, necessity for applying the same filtering logic to objects in java collections has emerged. I could reimplement the logic and keep two separate implementations but it doesn't seem like a good idea. Another idea I had was inserting data from a collection to an embedded RDB like H2 but this solution is very inefficient. Then I tried JoSQL, it seems promising, it's only about 10x slower than raw java code but it's no longer maintained.
Are there any better solutions?


text:
Q: Integrate of the primitive $\frac x{(2x-1)^3}$ By using a suitable substitution or otherwise, find the value of
$$\int_1^3\frac x{(2x-1)^3}dx$$
This is what I've got so far:
let $$u=2x-1$$
$$dx=\frac{du}2$$
$x=\frac{u+1}2$
$$\int_1^3\frac{u+1}{4u^3}du$$
Integrating giving $$\left[\frac{-1}{4u}-\frac{1}{8u^2}\right]_1^3$$
giving $\frac{5}{18}$, but this is the wrong answer. I should be getting $0.32$.

A: Your work is mostly correct. When making the substitution $u = 2x - 1$ you mustn't forget to change the limit of integration. In this case $x = 1 \Rightarrow u = 1$ and $x = 3 \Rightarrow u = 5$. So we have
$$ \int_1^5 \dfrac{u + 1}{4u^3} \text{d}u$$
Can you solve this from here?

A: \begin{align}
\int_{1}^{3} \frac{x \ dx}{(2x-1)^{3}} &= \frac{1}{2} \ \int_{1}^{3} \frac{[ (2x-1) + 1] \ dx}{(2x-1)^{3}} \\
&= \frac{1}{2} \ \int_{1}^{3} \frac{dx}{(2x-1)^{2}} + \frac{1}{2} \ \int_{1}^{3} \frac{ dx}{(2x-1)^{3}} \\
&= - \frac{1}{4} \left[ \frac{1}{2x-1} \right]_{1}^{3} - \frac{1}{8} \left[ \frac{1}{(2x-1)^{2}} \right]_{1}^{3} \\
&= \frac{8}{25}
\end{align}


text:
Q: pace-rails not showing for post requests I have written a custom ajax function which uses POST and I need to show the pace progress bar until the ajax stops and returns. It is working fine for GET request because there is no config needed. I need to know how to set a method to show the Pace on ajax calls.
gem 'pace-rails'

Jquery for all ajax requests.
  $(document).on({
    ajaxStart: function() { Pace.start() },
    ajaxStop: function() { Pace.stop() }
  });

A: By default track method is set to GET we can add additional methods using these options:
<script>
    window.paceOptions = {
        ajax: {
            trackMethods: ['GET', 'POST', 'PUT', 'DELETE', 'REMOVE']
        },
        restartOnRequestAfter: true
    };
</script>


text:
Q: KineticJs change Image Object I am trying to replace an existing image object on a kineticJS stage/layer with a new image when the user choose an item in a drop down menu. The code below works but when the image is changed by #template_select the original image doesn't look like it is being removed, the new image is just being added.
Once again...Thank you so much,
Todd
KineticJS:
    var stage = new Kinetic.Stage({
        container: 'tag_canvas',
        width: 306,
        height: 306
    });

    var layer = new Kinetic.Layer();
    var imageObj = new Image();

    var kinetic_common_name = new Kinetic.Text({
        x: 30,
        y: 40,
        text: commonname,
        fontSize: commonFontSize,
        fontFamily: commonFont,
        fill: 'green',
        draggable: true
    });
    var kinetic_botanical_name = new Kinetic.Text({
        x: 80,
        y: 115,
        text: latinname,
        fontSize: latinFontSize,
        fontFamily: latinFont,
        fill: 'green',
        draggable: true
    });

    imageObj.onload = function() {

        var template_image = new Kinetic.Image({
            x: 0,
            y: 0,
            image: imageObj,
        });

        // add the shape to the layer
        layer.add(template_image);
        layer.add(kinetic_common_name);
        layer.add(kinetic_botanical_name);

        // add the layer to the stage
        stage.add(layer);

    contextt.translate(306, 0);
    contextt.scale(-1, 1);

    contextt.drawImage(newRev, 0, 0);

    }; //END imageObj.onload
    imageObj.src = getTemplatePath(tag_template);

    var canvass = document.getElementById('reverse_tag_canvas');
    var contextt = canvass.getContext('2d');
    var newRev = layer.getCanvas().getElement();

  layer.afterDraw(function(){
        contextt.drawImage(newRev, 0, 0); //redraw reverse image
  });

    //change template
  $("#template_select").change(function(){
        imageObj.src = getTemplatePath($(this).val());
    layer.draw();

  });

HTML
Choose a template:
<select id="template_select" name="template_select">
  <option value="sm_oval">Small Oval</option>
  <option value="lg_oval">Large Oval</option>
  <option value="xlg_oval">Extra Large Oval</option>
  <option value="hibiscus">Hibiscus</option>
</select>

I usually do not like to put my url up but a js fiddle didn't seem to work with kinetic js. So you can try the template select menu here: http://planttagmaker.herobo.com/index copy.php

A: Make image.onload do only change image and nothing else. Therefore move out all unnecessary code from that function.
In your code, whenever image is loaded, you are adding shapes, layers, and much more.
That's causing the issue that you have.
imageObj.onload = function() {
    layer.draw();
};


text:
Q: ModuleNotFoundError: No module named 'numpy' in Python 3.7 on Mac I have python 3.7.2. I am trying to import numpy and keep getting this error. I use the terminal on Mac OS Mojave V 10.14.2
import numpy

Traceback (most recent call last):

 File "< stdin >", line 1, in < module >

ModuleNotFoundError: No module named 'numpy'

A: I think this could be a duplicate of this question.
numpy is not part of the python standard library and needs to be installed separately.
There are instructions for mac install in the question I linked for you.


text:
Q: Returning a nested hashmap I have the two following HashMapswhere Student is an object I created and has the format Student(String, String)
static HashMap<String, Student> hashMap = new HashMap<>();
static HashMap<String, HashMap<String, Student>> finalHashMap = new HashMap<>();

I created the following Students and added them to hashMap with the firstName as the Key
Student st1 = new Student("julian", "rogers");
Student st2 = new Student("jason", "Smith");

hashMap.put("julian", st1);
hashMap.put("jason", st2);

Then I added hashMap to finalHashMap with the first letter of firstName as the key
finalHashMap.put("j", hashMap);

How can I return the hashmap with the key j?
I tried creating a new hashmap and used get() but it did not work. I get a null pointer exception
static HashMap<String, Student> hashMapTemp = new HashMap<>();
hashMapTemp.putAll(finalHashMap.get('j'));

for (String key : hashMapTemp.keySet())
{
    System.out.println(key + " " + hashMapTemp.get(key));
}

OUTPUT
 java.lang.NullPointerException
    at java.util.HashMap.putAll(Unknown Source)

Note: I tried using put() and also got the same error.

A: hashMapTemp.putAll(finalHashMap.get('j'));
I think this should be :
hashMapTemp.putAll(finalHashMap.get("j"));
Your key in finalHashMap is a String, not a Character.

A: hashMapTemp.putAll(finalHashMap.get('j'));

This line is kind of odd, you look for a character instead of a string (as you defined).
Consider using static HashMap<Character, Student> finalHashMap = new HashMap<>()

A: public static HashMap<String, Student> find(String key, HashMap<String, HashMap<String, Student>> dataMap) {
    HashMap<String, Student> result = null;
    for (String s : dataMap.keySet()) {
        if (s.equalsIgnoreCase(key)) {
            result = dataMap.get(s);
            break;
        }
    }
    return result;
}

And then just call that method like this:
HashMap<String, Student> result = find("j", finalHashMap);


text:
Q: Is Ext JS's MVC an anti-pattern? I work in a team of 25 developers. We use ExtJS MVC pattern of Sencha. But we believe that their definition of MVC is misleading. Maybe we might call their MVC an anti-pattern too.
AMAIK, in MVC controller only knows the name or the path of the view, and has no knowledge on the view's internal structure. For example, it's not the responsibility of the controller, whether view renders the list of customers a simple drop down, or an auto-complete.
However, in Ext JS's MVC, controller should know the rendering of view's elements, because controller hooks into those elements, and listens to their events. This means that if an element of the view change (for example a button become a link), then the relevant selector in the controller should change too. In other words, controller is tightly-coupled to the internal structure of the view.
Is this reason acceptable to denounce Ext JS's MVC as anti-pattern? Are we right that controllers are coupled to views?

A: UPDATE (March 2015): Ext 5.0 introduced ViewControllers that should address most of the concerns discussed in this thread. Advantages:

*

*Better/enforced scope around component references inside the ViewController

*Easier to encapsulate view-specific logic separately from application flow-control logic

*ViewController lifecycle managed by the framework along with the view it's associated with

Ext 5 still offers the existing Ext.app.Controller class, to keep things backwards-compatible, and to give more flexibility for how to structure your application.
Original answer:

in Ext JS's MVC, controller should know the rendering of view's elements, because controller hooks into those elements, and listens to their events. This means that if an element of the view change (for example a button become a link), then the relevant selector in the controller should change too. In other words, controller is tightly-coupled to the internal structure of the view.

I actually agree that in most cases this is not the best choice for the exact reasons you cite, and it's unfortunate that most of the examples that ship with Ext and Touch demonstrate refs and control functions that are often defined using selectors that violate view encapsulation.  However, this is not a requirement of MVC -- it's just how the examples have been implemented, and it's easy to avoid.
BTW, I think it definitely can make sense to differentiate controller styles between true application controllers (control app flow and shared business logic, should be totally uncoupled from views -- these are what you're referring to), and view controllers (control/event logic specific to a view, tightly-coupled by design).  Example of the latter would be logic to coordinate between widgets within a view, totally internally to that view.  This is a common use case, and coupling a view-controller to its view is not an issue -- it's simply a code management strategy to keep the view class as dumb as possible.
The problem is that in most documented examples, every controller simply references whatever it wants to, and that's not a great pattern.  However, this is NOT a requirement of Ext's MVC implementation -- it is simply a (lazy?) convention used in their examples.  It's quite simple (and I would argue advisable) to instead have your view classes define their own custom getters and events for anything that should be exposed to application controllers.  The refs config is just a shorthand -- you can always call something like myView.getSomeReference() yourself, and allow the view to dictate what gets returned.  Instead of this.control('some > view > widget') just define a custom event on the view and do this.control('myevent') when that widget does something the controller needs to know about.  Easy as that.
The drawback is that this approach requires a little more code, and for simple cases (like examples) it can be overkill. But I agree that for real applications, or any shared development, it's a much better approach.
So yes, binding app-level controllers to internal view controls is, in itself, an anti-pattern.  But Ext's MVC does not require it, and it's very simple to avoid doing it yourself.

A: I use ExtJS 4's MVC everyday. Rather than spaghetti code, I have an elegant MVC app that has tightly defined separation of concens and is ridiculously simple to maintain and extend. Maybe your implementation needs to be tweaked a bit to take full advantage of what the MVC approach offers.

A: Of course the controllers are bound to the views in some way. You need to target exactly which elements in your views you want to listen to.
eg: listen to that button clicks or to that form element change or to that custom component/event.
The goal of MVC is components decoupling and reusability and the Sencha MVC is awesome for that. As @bmoeskau says, you have to be careful in separation of the view controllers (builtin for the view/widgets itself) and the application controllers (top level views manipulations) to take full advantage of the MVC pattern. And this is something not obvious when your read http://docs.sencha.com/ext-js/4-1/#!/guide/application_architecture. Refactor your MVC approach, create different controllers, create custom component, and embrace the full ExtJS MVC architecture to take advantage of it.
There's still a slight problem in Sencha approach IMHO, the MVC refs system doesnt really work when you have multiple instances of the same views in an Application. eg: if you have a TabPanel with multiple instances of the same Component, the refs system is broken as it will always target the first element found in the DOM... There are workarounds and a project trying to fix that but i hope this will be adressed soon.

A: I'm currently undergoing the Fast Track to ExtJS 4 from Sencha Training. I have a strong background in ExtJS (since ExtJS 2.0) and was very curious to see how the MVC was implemented in ExtJS 4.
Now, previously, the way I would simulate kind of a Controller, would be to delegate that responsibility to the Main Container. Imagine the following example in ExtJS 3:
Ext.ns('Test');

Test.MainPanel = Ext.extend(Ext.Container, {
    initComponent : function() {
        this.panel1 = new Test.Panel1({
            listeners: {
                firstButtonPressed: function(){
                    this.panel2.addSomething();
                },
                scope: this
            }
        });
        this.panel2 = new Test.Panel2();

        this.items = [this.panel1,this.panel2];

        Test.MainPanel.superclass.initComponent.call(this);
    }

});

Test.Panel1 = Ext.extend(Ext.Panel, {
    initComponent : function() {
        this.addEvents('firstButtonPressed');

        this.tbar = new Ext.Toolbar({
           items: [{
             text: 'First Button',
               handler: function(){
                   this.fireEvent('firstButtonPressed');
               }
           }]
        });

        Text.Panel1.superclass.initComponent.call(this);
    }
});

Test.Panel2 = Ext.extend(Ext.Panel, {
    initComponent : function() {
        this.items = [new Ext.form.Label('test Label')]

        Test.Panel2.superclass.initComponent.call(this);
    },

    addSomething: function(){
        alert('add something reached')
    }
});

As you can see, my MainPanel is (besides the fact that is holding both panels) also delegating events and thus creating a communication between the two components, so simulating sort of Controller.
In ExtJS 4 there is MVC directly implemented in it. What really striked me was that the way the Controller actually fetches the components is through QuerySelector which in my opinion is very prone to error. Let's see:
Ext.define('MyApp.controller.Earmarks', {
    extend:'Ext.app.Controller',
    views:['earmark.Chart'],

    init:function () {
        this.control({
             'earmarkchart > toolbar > button':{
                click:this.onChartSelect
            },
            'earmarkchart tool[type=gear]':{
                click:this.selectChart
             }
        });
    }
});

So as we can see here, the way the Controller is aware of the earmarkchart button and tool is through selectors. Let's imagine now that I am changing the layout in my earmarkchart and I actually move the button outside of the toolbar. All of a sudden my application is broken, because I always need to be aware that changing the layout might have impact on the Controller associated with it.
One might say that I can then use itemId instead, but again I need to be aware if I delete a component I will need to scatter to find if there is any hidden reference in my Controllers for that itemId, and also the fact that I cannot have the same itemId per parent Component, so if I have an itemId called 'testId' in a Panel1 and the same in a Grid1 then I would still need to select if I want the itemId from Panel1 or from the Grid1.
I understand that the Query is very powerful because it gives you a lot of flexibility, but that flexibility comes at a very high price in my opinion, and if I have a team of 5 people developing User Interfaces and I need to explain this concepts I will put my hands on the fire that they will make tons of mistakes because of the points I referenced before.
What's your overall opinion on this? Would it be easier to just somehow communicate with events? Meaning if my Controller is actually aware of what views he's expecting events, then one could just fire an event dosomethingController and the associated Controller would get it, instead of all this Query problem.

A: I think if you use the Sencha Architect to produce the Views then Inherit from that View to create Your own View.
Now this View Can be responsible to hook up to any events and raise meaningful events.
This is just a thought...
//Designer Generated
Ext.define('MyApp.view.MainView', {
    extend: 'Ext.grid.GridPanel',
    alias: 'widget.mainview',
    initComponent: function() {
    }
});

//Your View Decorator
Ext.define('MyApp.view.MainView', {
    extend: 'MyApp.view.MainViewEx',
    alias: 'widget.mainviewex',
    initComponent: function() {
    this.mon(this, 'rowselect', function(){
        this.fireEvent('userselected', arguments);
    }, this);
    }
});

A: I think there is a pretty bad problem here - its very difficult to shard isolated units within a page.
The approach I'm experimenting with (which makes it somewhat easier to write tests aswell) is to have a vanilla js context object for each page which contains the logic (and has the benefit of being very easy to break up and delegate to different objects).  The controllers then basically call methods on the context objects when they receive events and have methods on them for retrieving bits of the view or making changes to the view.
I'm from a wpf background and like to think of the controllers as code-behind files.  The dialog between presenter/context and view is a lot chattier than wpf (since you dont have binding + data templating) but its not too bad.
Theres also a further problem I haven't had to solve yet - the use of singletons for controllers causes problems for reuse of UI elements on the same page.  That seems like a serious design flaw.  The common solution I've seen is (yet again) to pile everything into one file and in this case to ditch the controller altogether.  Clearly that's not a good approach as soon as things start to get complicated.
It seems like getting all the state out of the controller should help though and you'd then have a second level of context objects - the top level one would basically just assign a unique id to each view and have a map of context=>view and provide dispatch to the individual context methods - it'd basically be a facade.  Then the state for each view would be dealt with in the objects dispatched to.  A good example of why statics are evil!


text:
Q: Want to conditionally change Console foreground color based on input I'm trying to make a KeyDown statement work. So I'm writing:
private void KeyDown(object sender, System.Windows.Forms.KeyEventArgs e);

System.Windows.Forms won't work I read that its a Visual Studio Code thing you have to go to Project.json and add System.Windows.Forms as a dependency. I don't know what to write to add it. I searched the web and searched stock overflow. I can't find anything.
I don't know what to type in to add it.

A: I could be wrong, but I don't believe you can use the System.Windows.Forms assembly with a .Net Core project. My Visual Studio is acting up so I wasn't able to try using it via the project.json imports feature. Having said that, it wouldn't provide you with what you want anyway.
Since you are wanting to capture the input from the user, via the console, and change the color based on some conditions - you'll have to do that manually yourself.
The following is a complete application example that shows how to do that. Essentially you have to evaluate each character entered into the console and determine if it's a number. If it is a number, you have to move the cursor back 1 position so you can overwrite the value that was just entered. Prior to overwriting the value, you change the consoles foreground color.
using System;
namespace ConsoleApp2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Set up an infinite loop that will allow us to forever type unless 'Q' is pressed.
            while(true)
            {
                ConsoleKeyInfo pressedKey = Console.ReadKey();

                // If Q is pressed, we quit the app by ending the loop.
                if (pressedKey.Key == ConsoleKey.Q)
                {
                    break;
                }

                // Handle the pressed key character.
                OnKeyDown(pressedKey.KeyChar);
            }
        }

        private static void OnKeyDown(char key)
        {
            int number;

            // Try to parse the key into a number.
            // If it fails to parse, then we abort and listen for the next key.
            // It will fail if anything other than a number was entered since integers can only store whole numbers.
            if (!int.TryParse(key.ToString(), out number))
            {
                return;
            }

            // If we get here, then the user entered a number.
            // Apply our logic for handling numbers
            ChangeColorOfPreviousCharacters(ConsoleColor.Green, key.ToString());
        }

        private static void ChangeColorOfPreviousCharacters(ConsoleColor color, string originalValue)
        {
            // Store the original foreground color of the text so we can revert back to it later.
            ConsoleColor originalColor = Console.ForegroundColor;

            // Move the cursor on the console to the left 1 character so we overwrite the character previously entered
            // with a new character that has the updated foreground color applied.
            Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
            Console.ForegroundColor = color;

            // Re-write the original character back out, now with the "Green" color.
            Console.Write(originalValue);

            // Reset the consoles foreground color back to what ever it was originally. In this case, white.
            Console.ForegroundColor = originalColor;
        }
    }
}

The output to the console will look like this:


text:
Q: Write value from 12 column on another worksheet if two conditions in columns 4 and 8 are true Sub CreateTable()
Dim bf As Boolean
Dim aTable(), aRes()
Dim i As Long, k As Long, n As Long
  With Worksheets("DOHADNÉ POLOŽKY")   ' List s tabulkou, kde se hleda
    i = .Cells(.Rows.Count, "A").End(xlUp).row
    aTable = .Range("A1:P" & i).Value ' tabulka do pole

    ReDim aRes(1 To i + 1, 1 To 1) ' velikost pole
        End With

For i = 1 To UBound(aTable)  ' od 1 do poctu radky tabulky
    If aTable(i, 1) <> Empty Then ' kdyz neni prazdna
        If aTable(i, 4) = "Depo" And aTable(i, 8) = "CZK" Then

                    aTable(i, 12) = aRes(i, 1): i = i + 1
                                           End If
                                End If
Next i
' upload vysledku na list do sloupce J
Worksheets("List1").Range("A1").Resize(UBound(aRes), 1).Value = aRes
Range("A1").Select
ActiveCell.FormulaR1C1 = "KUK"

End Sub

Something is wrong. It has no errors, but it doesn't write value in array I think. So the result on Worksheet("List1") is just empty.


text:
Q: asp net mvc login page doesn't work inside iframe I am working on a feature where our site is able to load another mvc site.
Basically I am using a Iframe with Id=aquaVetIframe where I put the url for my mvc site(setup of the src attribute for the iframe is done from codebehind). Everything is working fine in chrome. but at moment to test it using IE 10 the only thing what i can see in IE is the login page.
After sign in with the user the page return to the same login page. I could suppose that is related with the caching but i am not 100% sure.
here some code:
My aspx container:
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
<meta http-equiv="Cache-Control" content="max-age=0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<style type="text/css">
    html, body{height: 100%;}
</style>
</asp:Content>

<asp:Content ID="Content5" ContentPlaceHolderID="MainContent" runat="server">
  <div style="height: 100%; width: 100%;">
      <iframe id="aquaVetIframe" runat="server" allowfullscreen="true"  style="position: absolute;height: 100%; width: 100%;border:0px"> </iframe>
    </div>
</asp:Content>

Code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim urlQueryString = Request.QueryString("urlId")

    aquaVetIframe.Attributes("src") = urlQueryString

End Sub

At the top of my page I tried add the next tags, but with no luck:
<meta http-equiv="Cache-Control" content="max-age=0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

Here an image of the http post requests using IE10 and chrome (browser where currently is working my app)
http://postimg.org/image/iaifcljdz/

UPDATE:
Adding this line to my mvc application, cookies are allowed from IE and the application run fine while I executing the page directly in the browser (right click on run on IE browser in VS2013)
context.BeginRequest += (sender, args) => HttpContext.Current.Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

The issue what i have now is that my mvc aplication is not executing when I run my application from the begining.. for some strange reason the js libraries from mvc app are not loading..
see screenshot

A: Go to IE > interntet options > security > custom level > Scroll down Misc > find "Launching programs and files in an Iframe" > enable

A: Three things at a first look:
1) the iframe loads a full html page. So I recommend you to import the jquery libs inside the page you loaded inside the iframe (the login page);
2) IE is a good source of problem when testing a localhost server. It sometimes force a compatibility to IE8 or even IE7 on intranet (that includes localhost) pages. Ensure you have the IE10+ mode enabled. This question shows you how to do it:
You can achieve it by adding the following  tag to your page
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</head>

OR you can also add the following code in your web.config, inside the system.webserver tag (create it if it doesn't exist):
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=Edge" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

3) As you didn't show your tags including the JS files, then It's a good idea to take a look at them (including the jquery ones). Ensure:

*

*You are opening and closing <script></script> tags correctly. NEVER USE THE SHORT FORM <script /> when including a JS file because it won't work;

*Make sure you are using the correct path. Using a relative path (like ~/scripts/jquery.js) doesn't work because of '~'. You can also find some trouble if you are using a subfolder for your site's root, like http://localhost/mysite/. In this case, your includes should include the folder /mysite or use relative paths (like scripts/jquery.js, ../scritps/jquery.js, etc).

Maybe this is isn't enought, but is a first needed step to get closer to a working code.

A: Consecutive ajax call with no change in request are often considered as cached by some browsers and this issue is particularly reproducible in IE 10. The response for request is HTTP 304 Not Modified and request doesn't hit the database. The solution is to use ajaxSetup to set cache to false like :
$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

NOTE: This will set cache false for all ajax calls in the session.
OR
Using cache: false in particular ajax calls, if you don't want to disable cache for all ajax calls.
$.ajax({
         ...
         cache: false,
         ...
      });

For non-ajax call you can use :
Response.Cache.SetExpires(DateTime.Now.AddSeconds(0));

to response for suspected cached calls.
Also, it may be seems odd but I also faced similar issue in IE but that was due to cookie. Somehow there were two different cookies are created with same name & thus values stored in cookie wasn't found thus user was stuck on login page. Check if COOKIE is also not culprit in your case too.


text:
Q: Serial COM port timeout setting I have a USB to serial COM port that when I run the command in the screenshot below, I see the timeout value is ON.  Where is this setting come from? I can't find anywhere for it when looking at the device properties in my device manager.  Basically I am doing some testing and I would like to turn this value from ON to OFF.
I have some virtual com ports as well and on them the value is OFF.

A: You can set it in the command prompt itself.
mode com7 to=off

Here, 'to' stands for time-out.
You can check additional commands by using following.
mode /?

Hope this helps.


text:
Q: OpenCV: Find similar object with contours matching I have a bundle of different images with birds but some of them contains feathers, slightly visible birds etc. I need to find images where the bird visible well and remove images with feathers, far distant birds, etc.
I already tried ORB, simple template matching, Canny edge detection. And I cannot use neural nets.
Now i try with such algorithm:

*

*Binarize template image to get shapes

*Slide window over another binarized image with sliding window and calculate matchShape with template in every window

*Find best match

As you can see this method gives me strange result
Binary template
.
Shape on the other binary image, for example:

I calculated matchShapes in different parts of this image and the best result ~ 0.05 I got in this part:

which is obviously not similar to original shape.
Code for sliding window:
import cv2

OFFSET = 5
SCALE_RATIO = [0.5, 1]

def get_scaled_list(img_path, template):
    matcher_list = []

    img = cv2.imread(img_path)
    #JUST BINARIZATION AND RESIZING
    img = preprocess(resize_image(img))

    height, width = img.shape

    # building size of scale window
    for scaler in SCALE_RATIO:
        x_point = 0
        y_point = 0

        x1_point = int(width * scaler)
        y1_point = x1_point

        if x1_point > height:
            y1_point = height

        while y1_point <= height:
            while x1_point <= width:
                img1 = img[y_point:y1_point, x_point:x1_point]

                #Comparing template and part of image
                diff = cv2.matchShapes(template, img1, cv2.CONTOURS_MATCH_I1, 0)

                data_tuple = (img_path, x_point, y_point, int(width * scaler), diff)
                matcher_list.append(data_tuple)

                x_point += OFFSET
                x1_point += OFFSET

            x_point = 0
            x1_point = int(width * scaler)

            y_point += OFFSET
            y1_point += OFFSET
    return matcher_list

How can I perform correct shape matching and why is the best result performs here?

A: The naive window sliding method with a rigid template will work very poorly. In particular, the sizes are different making correct overlap impossible.

What you are trying to achieve is difficult because you only have edge information and the edges are complex, broken in several independent arcs and with junctions.
You can find many solutions when you have a single closed curve (lookup "elastic contour matching" for instance), but not for your case. This would be a case of "approximate elastic graph matching".
Other possible approaches are by special distance functions such as the chamfer or Hausdorff distances, but you can still be stuck because of the size mismatch.


text:
Q: Paradox in conservation of energy
Let us assume there is a constant electric field in an interested region (finite volume)and a non-conducting object is thrown into it with speed $v$ and now take the second scenario with the same region of the constant electric field but now a conducting object of the same volume as before is thrown into it with same speed $v$?

So, comparing total energy in the first and second case would both energy be same? keeping in mind that in metallic object electric field will be zero due to electrons movement and the dipole will be formed.
So in terse,would there be difference in total energy in both the scenario?


text:
Q: gremlin filter on Hashmap property without using a lambda If I have a vertex in a graph database where one of the properties is a map, is there a way to filter on properties of the map without using a lambda?
Create the vertex like this:
gremlin> v = graph.addVertex(label, 'LABEL')
==>v[68]
gremlin> g.V(68).property('prop', [ key: 'val' ])
==>v[68]
gremlin> g.V(68).valueMap()
==>{prop=[{key=val}]}

Is there a way to filter for vertices by prop.key == 'val' without using a lambda?
 gremlin> g.V().filter{ it.get().values('prop').next().get('key') == 'val' }

A: Here you go:
gremlin> g = TinkerGraph.open().traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> g.addV('LABEL').
......1>     property('prop', [ key: 'val' ]).
......2>   addV('LABEL').
......3>     property('prop', [ key: 'val2' ]).iterate()
gremlin> g.V().valueMap(true)
==>[prop:[[key:val]],id:0,label:LABEL]
==>[prop:[[key:val2]],id:2,label:LABEL]
gremlin> g.V().filter(values('prop').select('key').is('val'))
==>v[0]
gremlin> g.V().filter(values('prop').select('key').is('val2'))
==>v[2]

A: If all you are trying to do is find all vertices that have 'prop'='val' you can do this using the gremlin has step (documentation here) and your query would look like this:
g.V().has('prop', 'val')


text:
Q: Comparing two dates in swift in order to check if a day has gone by In my program, i have a "reset" button that i want to make appear when the user opens the app for the first time each day. So When the view loads, i create a variable to hold what day it is (i.e: 19), and then set that day as a user default. I then use an if statement to determine whether the user default is equal to the actual day it is. I'm not able to get the hiding and unhiding of the "reset" button completely figured out.
Here is the code i have so far. Im new to swift, so any advice or feedback on my approach would be greatly appreciated! Thanks
class UserInfoViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

   let date = Date()
   let calendar = Calendar.current

   let dateToday = calendar.component(.day, from: date)
   let dateToCompare = calendar.component(.day , from: date)

   UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")

   let userDefaultDate = UserDefaults.standard.value(forKey: self.userDefaultDate) as? Int

    if userDefaultDate != dateToCompare {

        resetLabel.isHidden = false
        UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")

    }

    if userDefaultDate == dateToCompare {

        resetLabel.isHidden = true
    }
}

A: Your code cannot work.
The logic is supposed to be:

*

*Get the day from UserDefaults,

*Compare it to the current day.

*If the values are not equal save the new day to UserDefaults

class UserInfoViewController: UIViewController {

    override func viewDidLoad() {
       super.viewDidLoad()

       let dateToday = Calendar.current.component(.day, from: Date())
       let dateToCompare = UserDefaults.standard.integer(forKey: "userDefaultDate")
       if dateToCompare != dateToCompare {
           UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
           resetLabel.isHidden = false
        } else {
           resetLabel.isHidden = true
        }
    }
}

Note:
Never use value(forKey: with UserDefaults.
There are many convenience methods and for objects use object(forKey:
Edit
It's more reliable to save the Date object and compare using isDateInToday of Calendar
class UserInfoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let dateToday = Date()
        let calendar = Calendar.current
        let dateToCompare = UserDefaults.standard.object(forKey: "userDefaultDate") as? Date ?? Date.distantPast
        if calendar.isDateInToday(dateToCompare) {
            resetLabel.isHidden = true
        } else {
            UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
            resetLabel.isHidden = false
        }
    }
}

A: Let me modify your code:
class UserInfoViewController: UIViewController {
let userDefaultDate = "userDefaultDate"

override func viewDidLoad() {
    super.viewDidLoad()

    let date = Date()
    let calendar = Calendar.current
    let dateToCompare = calendar.component(.day , from: date)

    let userDefaultDate = UserDefaults.standard.integer(forKey: "userDefaultDate")

    if userDefaultDate != dateToCompare {
        resetLabel.isHidden = false
        UserDefaults.standard.set(dateToCompare, forKey: self.userDefaultDate)
    } else {
        resetLabel.isHidden = true
    }
}

What you are wrong is that you set the value the user default before you check. So your comparison is always equal. This line I mean: UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")

A: try this, hope will help you.
override func viewDidLoad() {
    super.viewDidLoad()
            let date = Date()
            let calendar = Calendar.current

            let dateToday = calendar.component(.day, from: date)
            let dateToCompare = Int(calendar.component(.day , from: date))

            UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")

            let userDefaultDate = UserDefaults.standard.value(forKey: "userDefaultDate") as? Int

            if userDefaultDate != dateToCompare {
                UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")
                resetLabel.isHidden = true

            } else {
                resetLabel.isHidden = true
            }
}

in this code if userDefaultDate != dateToCompare, dateToCompare save in UserDefaults and hide you resetLabel, else if userDefaultDate = dateToCompare, its simply hide you resetLabel
but if you need show resetLabel if userDefaultDate != dateToCompare you will change this one:
UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")
resetLabel.isHidden = false

A: You will not be able to achieve your requirement as dateToday & dateToCompare will always be equal. Also you might want to use a button instead of a label(resetLabel) if you want a button action.
Try this code:
    override func viewDidLoad() {
    super.viewDidLoad()

    let presentDate = Date()

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/mm/yyyy"
    let dateString = dateFormatter.string(from: presentDate)

    guard let userDefaultDate = UserDefaults.standard.object(forKey: "userDefaultDate") as? String else {
        UserDefaults.standard.set(dateString, forKey: "userDefaultDate") //this line would be executed when you are setting the date for the first time, i.e on your first app launch.
        resetLabel.isHidden = true
        return
    }

    if userDefaultDate != dateString {
        resetLabel.isHidden = false
        UserDefaults.standard.set(dateString, forKey: "userDefaultDate")
    } else {
        resetLabel.isHidden = true
    }
}

Here I'm converting the date into a string in the format dd/mm/yyyy and saving it in the UserDefaults


text:
Q: xhr.send(params) - multiple parameters I am trying to pass multiple parameters but dont know the syntax..PLz help
function formSubmit() {

    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;
    var phone = document.getElementById('phone').value;
    var message = document.getElementById('message').value;

    // This is where the problem is:
    var params = "name="+name&"email="+email&"phone="+phone&"message="+message;

    var xhr = new XMLHttpRequest;
    xhr.open('POST' , 'ajax.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')

    xhr.onload = function() {
        if(this.status ==200) {
            console.log(this.responseText);
        }
    }
    xhr.send(params);
}

A: I see correct coments from bdalina and AamirR.
But i didint see answer uder your question.
So I make one used good coments from (bdalina and AamirR) for others who problem you and I have.
function formSubmit() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;

// This is where the problem is:
var params = "name="+name"&email="+email"&phone="+phone"&message="+message;
//for send more parameters them one use "$" in the next POST identifier.
// like "nameOfValue="+value1"&NameNextValue"+value2

var xhr = new XMLHttpRequest();
//XMLHttpRequest is a function so u must have () on end of function name. XMLHttpRequest()
xhr.open('POST' , 'ajax.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')

xhr.onload = function() {
    if(this.status ==200) {
        console.log(this.responseText);
    }
}
xhr.send(params);}


text:
Q: RabbitMQ - How to stop a Publisher Service when Subscriber service fails with some error I have 2 windows services in C#.
Service 1 publishes messages to the RabbitMQ queue.
Service 2 subscribes the RabbitMQ queue.
Service 2 also connects to a TCP server and sends the messages it has received from RabbitMQ to this server.
My question is, is there any way to stop Service 1 from publishing messages on to the queue when Service 2 which consumes this message has failed out due to some error (Mostly, SocketException if it cannot connect to the Server).
Any pointer would be really helpful.
Please let me know if any more information is required.
Thanks in Advance.

A: Just a few of my(opinionated) ideas on how to approach it:

*

*One option would be to create some sort of hartbeat messaging system between the two
and check if the service is OK on intervals, this has the downside of somethings happening
after you do one check and before the next.

*Another would be to add to Service 1 a lock flag to have it stop sending to Service 2
and toggle the flag by having Service 2 send a message back to Service 1 on an Exception,
but for this again on intervals you will need to check when the calls start working again and
toggling back Service 1 to an ON state.

*You could add exponential backoff to Service 1, this would have the upside of not flooding
Service 2, and would also avoid the checks and ping-pong of messages, the downside is that
the backoff time could grow really large.
Cheers


text:
Q: Is there any ways to copy images to the clipboard when clicking on custom button? I'm trying to copy an image to the clipboard and use it in my webpage. But I couldn't store the image data in the clipboard. I tried executing copy commands but I could only able to copy text.  Kindly Help.
    function copyThings(event){
            var msgelem = event.target.previousElementSibling;
            // msgelem = the element of current button
            var msgcopied = theMsg(msgelem); // returns the content of text if text and url of the image if image.
            var copydiv = '
'+msgcopied+'
';
            msgdiv.find('#txtarea').after(copydiv);
            msgdiv.find("#copyhidden").select();
            document.addEventListener(event, function(){
                event.stopPropagation();
                event.datatransfer.setData('URL',msgcopied); //No I18N
                event.preventDefault();
            });
            document.execCommand('copy');//No I18N
            msgdiv.find("#copyhidden").remove();

        }

I just wanted when I click on a particular button the image gets stored in the DataTranferItem.(i.e) the event.clipboardData.items must contain {kind : file, type: image/png}

If I can't do that, what can be the alternate solution?

Thanks in Advance!


text: Q: Aplicação da variável variável Visualizei uma aula sobre variável variável em PHP e me surgiu a seguinte dúvida, qual a aplicação deste formato variável variável? se não for pedir muito, um exemplo simples e prático. Agradecido!


text:
Q: T- SQL Capture data Overflow errors Aim - To capture data overflow errors from source to destination tbls.
I've have a source table that is being dumped with data and column data type is varchar
While the destination table has specific column type like decimal (12, 5), or Int etc...
Is the anyway I can find all the rows that don't fit the spec and flag it so that they are not part of insert and hence not cause the script to fail..
MS-SQL 2008 R2

A: Yes. You can do it by checking whether the value in the column of source table is a number before inserting to the destination table using ISNUMERIC in SQL Server.
SOURCE TABLE
CREATE TABLE #SOURCE(SCOL VARCHAR(300))

INSERT INTO #SOURCE
SELECT 'ABC'
UNION ALL
SELECT '121'
UNION ALL
SELECT '-145.78'
UNION ALL
SELECT '200,000'
UNION ALL
SELECT N'£100.20'
UNION ALL
SELECT '0E0'
UNION ALL
SELECT N'₤'

DESTINATION TABLE
CREATE TABLE #DESTINATION(DCOL NUMERIC(5,2))

-- Only the numeric values will be inserted and is Type-safe
INSERT INTO #DESTINATION
SELECT SCOL
FROM #SOURCE
WHERE ISNUMERIC(SCOL)=1

SELECT * FROM #DESTINATION

EDIT :
If ISNUMERIC doesn't satisfy the values in your column, create the below function and check the value in your column in WHERE clause. I got the function from here.
CREATE FUNCTION dbo.isReallyNumeric
(
    @num VARCHAR(64)
)
RETURNS BIT
BEGIN
    IF LEFT(@num, 1) = '-'
        SET @num = SUBSTRING(@num, 2, LEN(@num))

    DECLARE @pos TINYINT

    SET @pos = 1 + LEN(@num) - CHARINDEX('.', REVERSE(@num))

    RETURN CASE
    WHEN PATINDEX('%[^0-9.-]%', @num) = 0
        AND @num NOT IN ('.', '-', '+', '^')
        AND LEN(@num)>0
        AND @num NOT LIKE '%-%'
        AND
        (
            ((@pos = LEN(@num)+1)
            OR @pos = CHARINDEX('.', @num))
        )
    THEN
        1
    ELSE
    0
    END
END
GO

And in the query to select and insert, use the above function
INSERT INTO #DESTINATION
SELECT SCOL
FROM #SOURCE
WHERE DBO.isReallyNumeric(SCOL)=1


text:
Q: Creating time windows with Ruby Having an array of several time series (timestamp, value) like this:
time_series = [[[1234567, 0.8], [1234568, 0,9], [1234569, 1.0]],
               [[1234568, 0,7], [1234569, 0,2], [1234570, 1.2]],
               [[1234560, 0,9], [1234561, 0.2], [1234568, 0,1]]]

I want to create an array of time windows of a given size time_size. For example, if I wanted to create time windows of time_size = 2:
    time_size = 2
    time_windows = create_time_windows(time_series, time_size)
    puts time_windows
#   time_windows => [[[], [], [[1234560, 0,9], [1234561, 0.2]]],
#                    [[[1234567, 0.8], [1234568, 0,9]], [[1234568, 0,7], [[1234568, 0,1]]],
#                    [[[1234569, 1.0]], [[1234569, 0,2], [1234570, 1.2]], []]]

I know it is not a very readable example, but the operation can be summarized as splitting an array of time series into an array of subarrays containing the segments of those time series whose timestamp is included into the pertinent interval of time.
In the example, I wanted to do that with a time window size of 2, so I picked the earliest time of the whole array of series, and began to count from there. So, my first time window contains all points from the three earlier series whose timestamp was included between 1234560 (the origin in my series, because the earlier point was that) and 1234560 + 2. You can see that the first window doesn't have elements from the first and second series, since there are no points whose timestamp was included within the interval. The next interval would be (1234560 + 2, 1234560 + 4), and so on.
I am not specially proficient in Ruby, so I would be glad if the community can help me solving this problem. I have considered using Enumerable methods such as slice_when combined with inject, but I got impossibly lost trying to code that.


text:
Q: Invalid OAuth2 token in GAE/GWT java app I am developing an GWT/GAE java application which

*

*simply gets the users location via GWT geolocation implementation (works very well)

*on button click should write the latitude, longitude and accuracy into a Google spreadsheet

When I click on the "save to spreadsheet" button, I am getting the following error messages in my eclipse console:
04.09.2012 16:44:01 com.google.appengine.repackaged.org.apache.http.impl.client.DefaultRequestDirector handleResponse
WARNUNG: Authentication error: Unable to respond to any of these challenges: {authsub=WWW-Authenticate: AuthSub realm="https://www.google.com/accounts//AuthSubRequest"}
com.google.gdata.client.GoogleService$SessionExpiredException: OK

<TITLE>Token invalid - Invalid token: Stateless token parent not found</TITLE>

Token invalid - Invalid token: Stateless token parent not found

Error 401

at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:570)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:645)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at com.cloudpilots.locator.server.GSpreadsheetServiceImpl.insertRow(GSpreadsheetServiceImpl.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:370)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

So it has to be a problem with the credential/token.
Here is the server-side RPC service code:
public class GSpreadsheetServiceImpl extends RemoteServiceServlet implements
        GSpreadsheetService {

    @Override
    public void insertRow(String latitude, String longitude, String accuracy) {

        try {
            String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
            Credential credential = OAuth2Utils.initializeFlow().loadCredential(userId);

            SpreadsheetService service = new SpreadsheetService("Locator-v1");

            service.setOAuth2Credentials(credential);

            // Define the URL to request.  This should never change.
            URL SPREADSHEET_FEED_URL = new URL(
                "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

            // Make a request to the API and get all spreadsheets.
            SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
                SpreadsheetFeed.class);
            List<SpreadsheetEntry> spreadsheets = feed.getEntries();

            // TODO: Choose a spreadsheet more intelligently based on your
            // app's needs.
            SpreadsheetEntry spreadsheet = spreadsheets.get(0);
            for (SpreadsheetEntry spreadsheetEntry : spreadsheets) {
                if (spreadsheetEntry.getKey() == "MY_SPREADSHEET_KEY") {
                    spreadsheet = spreadsheetEntry;
                    break;
                }
            }

            // Get the first worksheet of the first spreadsheet.
            // TODO: Choose a worksheet more intelligently based on your
            // app's needs.
            WorksheetFeed worksheetFeed = service.getFeed(
                spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
            List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
            WorksheetEntry worksheet = worksheets.get(0);

            // Fetch the list feed of the worksheet.
            URL listFeedUrl = worksheet.getListFeedUrl();
            ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);

            // Create a local representation of the new row.
            ListEntry row = new ListEntry();
            row.getCustomElements().setValueLocal("Latitude", latitude);
            row.getCustomElements().setValueLocal("Longitude", longitude);
            row.getCustomElements().setValueLocal("Accuracy", accuracy);

            // Send the new row to the API for insertion.
            row = service.insert(listFeedUrl, row);
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Here is the OAuth2Utils class:
public class OAuth2Utils {
    /** Global instance of the HTTP transport. */
    static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

    /** Global instance of the JSON factory. */
    static final JsonFactory JSON_FACTORY = new JacksonFactory();

    static String getRedirectUri(HttpServletRequest req) {
        GenericUrl url = new GenericUrl(req.getRequestURL().toString());
        url.setRawPath("/oauth2callback");
        return url.build();
    }

    static GoogleAuthorizationCodeFlow initializeFlow() throws IOException {
        return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                JSON_FACTORY, "MY_CLIENT_ID",
                "MY_KEY",
                Collections.singleton("https://spreadsheets.google.com/feeds/"))
                .setCredentialStore(new AppEngineCredentialStore())
                .setAccessType("offline").build();
    }
}

Does anybody know what the problem could be?
Best regards,
Juri Wiens

A: This way works:
1) use Google drive DrEdit example for OAuth https://developers.google.com/drive/examples/java
Note: you need to add refresh token, I found adding it was not hard to do.
2) Connect like this:
    SpreadsheetService service = new SpreadsheetService("cellmaster-v0.2");

    // Authorize the service object for a specific user (see other sections)
    service.setHeader("Authorization", "Bearer " + accessToken);

    URL SPREADSHEET_FEED_URL = getSpreadsheetUrl(spreadsheetKey);
    spreadsheet = service.getEntry
            (SPREADSHEET_FEED_URL, SpreadsheetEntry.class);

I looked at lots of examples. It took me a few days to find this solution.


text:
Q: How do I export to a cvs file using php I'm having a problem getting my export to create and download a cvs file. Using the code below, this exports the data, but it prints out in the browser, rather than creating an actual csv file. I call the php from a link on another page with Export Details but all it does is show the data in the browser rather than creating a csv file.
This is my code in the file export.php:
<?php
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);

?>

Can anyone see where it's going wrong?

A: So, after a whole afternoon of fun with this one, I finally got to the bottom of the problem. The issue wasn't with the code, it was the database I am running locally. I'm using Mamp to set up my wordpress db locally and that's where the problem was. The solution is with Output Buffering and the solution can be found here http://hibbard.eu/php-headerlocation-not-working-in-mamp/. Thanks guys for your help ;-)

A: CSV Files are files having comma separated values on each line, maybe enclosed by a string enclosure.
First thing that catches my eye is that you pass single values to fputcsv(). But fputcsv() wants an array of values (fields) as the second argument. So your explode is redundant - have a look at the manual page,
As you are only outputting to STDOUT (the Browser) you can simply echo your lines:
<?php
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');

$data = array(
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

foreach($data AS $line){
    echo $line.PHP_EOL;
}
?>


text:
Q: why is the Artifactory CE service Port is not the configured Port? the default port of UI is 8081 for  Artifactory CE ,
but In my server ,the 8081 is used by another service ,
so I add  :

artifactory:

  port: 8083

in jfrog/artifactory/var/etc/system.yaml
then restart the Antifactory CE
but if I acess http://IP:8083/ui/, I get : HTTP Status 404 – Not Found
If I access http://174.34.90.112:**8082**/ui , then it seems OK
and in "Set Me Up",
it shows : conan remote add  http://IP:8040/artifactory/api/conan/conan
but the IP:8040 is not work ,
I need to use  IP:8083  to upload the pacakges
how can I configure the Port right?
or how to keep the UI and the system.yaml  consistency ?

A: In artifacroty version 7.*, the UI has a different port then the service, this is why you are able to get to the ui in port 8082.
Regarding the service port, it may be that you have another formating problem that causes artifactory not to pick the new port configuration.
Usually, these kind of errors are written to the console.log file.
Did you check the log file for configuration errors?
Can you upload the entire system.yaml?


text:
Q: osmdroid not centering/registering GeoPoint coordinates Unless I'm understanding this incorrectly, to initialize osmdroid around a given point you would do as following:
    map = (MapView) findViewById(R.id.mapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    MapController mapController = (MapController)map.getController();

    GeoPoint startPoint = new GeoPoint(52370816, 9735936);
    mapController.animateTo(startPoint);
    map.setBuiltInZoomControls(true);
    mapController.setZoom(2);
    map.setUseDataConnection(true);
    map.setMultiTouchControls(true);

When I run this however, the map sorta does whatever it wants. It doesn't center on the given GeoPoint. Changing these numbers doesn't seem to do anything. Am I missing something?
My XML files are all in order as per the tutorials as are my permissions.

A: This is a known bug occuring when you set the map view in onCreate:
https://github.com/osmdroid/osmdroid/issues/22
Issue is closed because assumed to be fixed in source Head, but it's still not fixed in the 4.2 osmdroid release.
setCenter works fine once the mapview has been drawn once.
Various workarounds can be found in osmdroid project Issue.

A: Since 2014-06-24 Osmdroid has this
MapView.addOnFirstLayoutListener(new OnFirstLayoutListener() { ...});

which can be used to set initial zoom, mapcenter, ....


text:
Q: Why do I get 'django core exceptions improperlyconfigured...' when I import from my models? I have had a look through answers regarding this error so my question is specifically why do I get this error when I include the following line?:
from teams.models import clubs

I don't understand why this import causes the problem.
The traceback is:
  File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
 1012, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
 146, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in __ge
tattr__
    self._setup(name)
  File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _set
up
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
 variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.

The full code for 'populate_players.py':
import os
import sys
import django
from teams.models import clubs

club1 = "Arsenal"
club2 = clubs.objects.get(name = club1);

def add_players(name, position, born, height, weight, nationality, club=club2, active=True):
    # run the script per club

    p = players.objects.get_or_create(name=name, position=position, born=born, height=height, weight=weight, nationality=nationality)
    return p

def populate():
    add_players(name='Calum Chambers',
        position = 'DEF', # list
        born = '2015-01-20',
        height = '1.83',
        weight = '65',
        nationality = 'England'
        )

    for p in players.objects.all():
        print p

if __name__ == '__main__':
    print "Starting player population script..."
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "epl.settings")
    django.setup()
    from teams.models import players
    populate()

And models.py:
from django.db import models

# Create your models here.

class clubs(models.Model):
    name = models.CharField(max_length=64)
    nickname = models.CharField(max_length=64)
    logo = models.ImageField(blank=True)
    manager = models.CharField(max_length=128)
    established = models.IntegerField()
    stadium = models.CharField(max_length=64)
    active = models.BooleanField(default=True)

    # Fixtures, form, league position?

    def __unicode__(self):
        return self.name

class players(models.Model):
    GOALKEEPER = 'GK'
    DEFENDER = 'DEF'
    MIDFIELDER = 'MID'
    FORWARD = 'FWD'
    POSITION_CHOICES = (
        (GOALKEEPER, 'Goalkeeper'),
        (DEFENDER, 'Defender'),
        (MIDFIELDER, 'Midfielder'),
        (FORWARD, 'Forward'),
        )

    name = models.CharField(max_length=64)
    club = models.OneToOneField('clubs', related_name= "team")
    position = models.CharField(max_length=64, choices=POSITION_CHOICES, default=GOALKEEPER) # GK, Defender, Midfielder, Attacker -  Field for this?
    born = models.DateField()
    height = models.DecimalField(max_digits=3, decimal_places=2)
    weight = models.IntegerField() # Field for this?
    nationality = models.CharField(max_length=64) # Choices
    active = models.BooleanField(default=True) # active = current epl player
    slug = models.SlugField()

    def __unicode__(self):
        return self.name

A: If you are calling this script locally and not through the django server you need to import/configure the settings before you import e.g. your models:
from django.conf import settings

settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
    TEMPLATE_DIRS=('/home/web-apps/myapp', '/home/web-apps/base'))

You can find more details here.


text: Q: Trick for solving an integral I am trying so solve a practical problem (i.e. not sure if my questions has any nice solution), and I reached a point where I need to solve an integral of the form $\int_0^Tf(t)e^{at}dt$, where $f(t)$ is a function for which I don't know the value at each time, $t$, but I know its time average i.e. $\frac{\int_0^Tf(t)}{T}=f_0$ (in principle $f(t)$ has a given distribution, and I know that distribution, I just don't know each individual value). Formally, in both integrals I would need $T\to \infty$, but in practice I just have a T big enough so you can assume that $T\to \infty$. I know the value of $a$. I was wondering if there is any way to simplify this integral any further (ideally obtaining something in terms of $a$, $f_0$ and $T$). Thank you!


text:
Q: Set language to German in plotly's modebar I'm bulding a shiny app using also plotly. Since release  v1.32.0 at Github there is now also a new feature in plotly available to set the modebar into German language:
https://github.com/plotly/plotly.js/releases
So I installed the latest version of plotly using devtools::install_github("ropensci/plotly") and tried to incorporate the new feature with locale='de':
# devtools::install_github("ropensci/plotly")

library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("event")
)

server <- function(input, output) {

  # renderPlotly() also understands ggplot2 objects!
  output$plot <- renderPlotly({
    plot_ly(mtcars, x = ~mpg, y = ~wt)%>%
    config(plot_ly(),displayModeBar = T, collaborate=F, displaylogo=F,locale='de') %>%
      layout(hovermode = 'closest')
  })

  output$event <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover on a point!" else d
  })
}

shinyApp(ui, server)

There is no change at all, the language is still 'en'. What am I doing wrong, can anyone help?


text:
Q: Can we use "yours" twice in succession? Can we use yours twice in succession? As in:

My sign governs my style; and yours, yours.

Any other possible usage? Is my example otherwise grammatically correct?

A: Sure, English is flexible enough to do this. Repetition is sometimes used for emphasis, and we can conjure some examples that would put the word yours twice in succession without breaking any grammatical rules. For example:

All of what I have is yours – yours and yours alone.
I think this should be yours, yours and not his.
Everything I gave you today is yours: yours to keep, yours to cherish, yours to treasure.

Lovers sometimes write to each other using such prose. In a letter from Louise Whitfield to Andrew Carnegie:

"I am yours, yours, all yours, for you have thrown the mantle of your great love around me, and I am no more cold and trembling, but warm and strong."

And here's an example written by Canadian naturalist John A. Livingston:

"Wildlife is yours; yours to manipulate in your own best interest."

And in a work of fiction by Amanda Hemingway:

"My world will become yours, yours mine — and all that we have achieved will not be lost."

A: It seems plausible to me that there might be a grammatical constraint preventing double "yours", since there is at least one such constraint known, the "double -ing" constraint discovered by Ross in 1972 and much discussed since (for instance here).  However, I find the examples of "yours yours" I've seen so far to be acceptable.


text:
Q: can an actionscript function find out its own name? given the following
function A(b:Function)   { }

If function A(), can we determine the name of the function being passed in as parameter 'b' ?  Does the answer differ for AS2 and AS3 ?

A: I've been trying out the suggested solutions, but I ran into trouble with all of them at certain points. Mostly because of the limitations to either fixed or dynamic members. I've done some work and combined both approaches. Mind you, it works only for publicly visible members - in all other cases null is returned.
    /**
     * Returns the name of a function. The function must be publicly visible,
     * otherwise nothing will be found and null returned.
Namespaces like
     * internal, protected, private, etc. cannot
     * be accessed by this method.
     *
     * @param f The function you want to get the name of.
     *
     * @return  The name of the function or null if no match was found.

     *          In that case it is likely that the function is declared
     *          in the private namespace.
     **/
    public static function getFunctionName(f:Function):String
    {
        // get the object that contains the function (this of f)
        var t:Object = getSavedThis(f);

        // get all methods contained
        var methods:XMLList = describeType(t)..method.@name;

        for each (var m:String in methods)
        {
            // return the method name if the thisObject of f (t)
            // has a property by that name
            // that is not null (null = doesn't exist) and
            // is strictly equal to the function we search the name of
            if (t.hasOwnProperty(m) && t[m] != null && t[m] === f) return m;
        }
        // if we arrive here, we haven't found anything...
        // maybe the function is declared in the private namespace?
        return null;
    }

A: Heres a simple implementation
    public function testFunction():void {
        trace("this function name is " + FunctionUtils.getName()); //will output testFunction
    }

And in a file called FunctionUtils I put this...
    /** Gets the name of the function which is calling */
    public static function getName():String {
        var error:Error = new Error();
        var stackTrace:String = error.getStackTrace();     // entire stack trace
        var startIndex:int = stackTrace.indexOf("at ", stackTrace.indexOf("at ") + 1); //start of second line
        var endIndex:int = stackTrace.indexOf("()", startIndex);   // end of function name

        var lastLine:String = stackTrace.substring(startIndex + 3, endIndex);
        var functionSeperatorIndex:int = lastLine.indexOf('/');

        var functionName:String = lastLine.substring(functionSeperatorIndex + 1, lastLine.length);

        return functionName;
    }

A: The name? No, you can't. What you can do however is test the reference. Something like this:
function foo()
{
}

function bar()
{
}

function a(b : Function)
{
   if( b == foo )
   {
       // b is the foo function.
   }
   else
   if( b == bar )
   {
       // b is the bar function.
   }
}

A: I use the following:
private function getFunctionName(e:Error):String {
    var stackTrace:String = e.getStackTrace();     // entire stack trace
    var startIndex:int = stackTrace.indexOf("at ");// start of first line
    var endIndex:int = stackTrace.indexOf("()");   // end of function name
    return stackTrace.substring(startIndex + 3, endIndex);
}

Usage:
private function on_applicationComplete(event:FlexEvent):void {
    trace(getFunctionName(new Error());
}

Output:
FlexAppName/on_applicationComplete()
More information about the technique can be found at Alex's site:
http://blogs.adobe.com/aharui/2007/10/debugging_tricks.html

A: Are you merely looking for a reference so that you may call the function again after?  If so, try setting the function to a variable as a reference.
    var lastFunction:Function;
var func:Function = function test():void
{
    trace('func has ran');
}

function A(pFunc):void
{
    pFunc();
    lastFunction = pFunc;
}
A(func);

Now if you need to reference the last function ran, you can do so merely through calling lastFunction.
I am not sure exactly what you are trying to do, but perhaps this can help.

A: I don't know if it helps, but can get a reference to the caller of the function which arguments (as far as I know just in ActionScript 3).

A: Use arguments.callee with toString() and match in general:
function foo(){return arguments.callee.toString().match(/\s\w+/).toString()}

References

*

*arguments callee method

*Tracing Function Arguments


text:
Q: Get the final SQLite expression when using PHP PDO I experience some weird results on certain queries to an SQLite database. Therefore I'd like to see the real query sent to the database. I'm using PDO, and the closest I can get is
$statement->debugDumpParams();

but this is just an abstract representation, not the final query.
Is there any way to see, what's actually sent to the db driver? There seems to be a C interface trace(), but as far as I can tell, I have no means of accessing it from within PHP.


text:
Q: how to send response to a specific ip address in nodejs or javascript? I am working with nodejs, and i want to send response from server to a specific ip address but server will be able to listen request from any ip address. Please suggest me how to do this.
thanks in advance.

A: Your question is not very clear and also didn't give any code example of what you have tried. Anyway here is a basic code showing how to get the ipaddress of the client that requested the server and send a response back based in the ip address:
var http = require('http');

var s = http.createServer(function(req, res){
     var ipAddress = req.connection.remoteAddress;
     //check if user is accessing from localhost ip
     if(ipAddress=="127.0.0.1"){
        res.writeHead(200, {'content-type':'text/plain'})
        res.end('Hello localhost');
     } else {
        res.writeHead(200, {'content-type':'text/plain'})
        res.end('Hello '+ipAddress);
     }
});
s.listen(8000);


text:
Q: Changing the value of a copy also changes the value of the original Changing the value of a variable b, which is a copy of a, also changes the value of a.
a = [[0]]
b = a.copy()

print("a before", a)

b[0][0] = 1

print("a after ", a)

prints:
a before [[0]]
a after  [[1]]

Although this works:
a = [0]
b = a.copy()

print("a before", a)

b[0] = 1

print("a after ", a)

prints:
a before [[0]]
a after  [[0]]

A: Turns out copy.deepcopy works.
import copy

a = [[0]]
b = copy.deepcopy(a)

print("a before", a)

b[0][0] = 1

print("a after ", a)

prints:
a before [[0]]
a after  [[0]]


text:
Q: Center UI elements in view with autolayout How do you use Autolayout to make a UI Element centered left-to-right when in both landscape and portrait mode? Can you have variables in autolayout?

A: If you are using Interface builder to create & set position of your view, Select your View & do as the screenshot suggests below.

After that, click on "Add constraint" & you are done. This is just to set your view in horizontal centre. But you have to still add some more constraints. They are:

*

*Height

*Width

*Distance from top/bottom layout guide/view.

Let me know if you don't know how to do this.

A: set constraints both vertical and horizontal
more understand autolayout easily follow this link
http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2

output portait

output landscape

A: in your xib ,you should add 3 constraints :

*

*Hirizontal Center in Container;

*Width ;

*Height ;


text:
Q: Not able to insert Value in Redis This is a bit simple question but I am struggling for an 2 hours so I thought it might be better to ask for help.
I want to read values from a properties file through java program and dump in to redis using jedis.
Property files contain value that contain single qoutes eg:
welcomemsg='hi\n'

basically, an html file,
But single quotes are not inserted and also slashes.
I tried escaping slashes and quotes eg:
\'hi\\\n' etc..
but it did not help.
I tried searching google but was not able to find any topics which could point me in a right direction.
If I can get any advice it will be great !!
Thanks.

A: For me this code works fine
Jedis jedis = new Jedis("localhost");
jedis.set("foo", "\'hi\\n\'");
String value = jedis.get("foo");
System.out.println(value);

And on redis CLI
127.0.0.1:6379> get foo
"'hi\\n'"


text:
Q: Pop up message on selectindexchanged in vb I was wondering how can I display a pop up warning message every time the selected item in dropdown list has changed. I've managed to get it working , but the message will unfortunately also pop up when loading the form as in some cases the default value has already been set and is not empty. So far i have this:
Private Sub cboNew_DropDown(sender As Object, e As EventArgs) Handles   cboNew.SelectedIndexChanged

    If cboNew.SelectedItem = "%" Then
        MessageBox.Show(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
    End If

    If cboNew.SelectedItem = "Value" Then
        MessageBox.Show(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
    End If

    If cboNew.SelectedItem = "REVOKE" Then
        MessageBox.Show(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
    End If
End Sub

A: Sometime it's hard to determine where the error came from. You could add a boolean flag to help you out.
Private _isLoading As Boolean = False

Private Sub YourLoadingSub
    _isLoading = True
    ' Do your loading code
    _isLoading = False
End Sub

Private Sub cboNew_DropDown(sender As Object, e As EventArgs) Handles   cboNew.SelectedIndexChanged

    If Not _isLoading  Then
        ' Show message box
    End If

End Sub

An other option is to remove the event and put it back when needed.

A: The mistake is in this statement  MessageBox.Show( change this as  msgbox() then your code will be like the following:
  Private Sub cboNew_DropDown(ByVal sender As Object, ByVal e As EventArgs) Handles cboNew.SelectedIndexChanged

            If cboNew.SelectedItem = "%" Then
                MsgBox(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
            End If

            If cboNew.SelectedItem = "Value" Then
                MsgBox(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
            End If

            If cboNew.SelectedItem = "REVOKE" Then
                MsgBox(String.Format(" You Selected = " & cboNew.SelectedItem, MessageBoxButtons.OK))
            End If
 End Sub


text:
Q: DIV height too great over fixed background image I am creating a sort of text-slide presentation in HTML. The basic layout is a full-screen fixed background image with text in a centered full-height column in front of it. The basic HTML structure is quite simple:

Test

         Text.

         Text.

Setting this up is not difficult, except for one thing: In order for the text-containing div to appear the full height of the window, the height of all three main elements--the html, body, and the div--must be set to 100%. I'm not sure if I'm interpreting what happens correctly, but it seems to result in a situation where any margin or padding on elements within the div are added to the div's height after the div has already been expanded to 100% of the height of the viewport. Thus, even though the actual content of the div is less than the height of the window, its calculated height is greater than the height of the viewport, and a vertical scrollbar results, even for minimal content.
What am I missing here?
CSS code is below, please check out this fiddle to see what I mean: http://jsfiddle.net/NL4gg/3/
[I have so far tested this in webkit browsers (Chrome and Safari); if you don't see the issue I've described in the fiddle, that may be why.]
html {
    height:100%;
}

body {
    color: #000;
    background: url(https://farm9.staticflickr.com/8173/8038716643_270547eb16_o.jpg) no-repeat fixed center center;
    margin:0 auto;
    height:100%;
    width:50%;
}

div {
    background-color:rgba(255,255,255,0.5);
    height:100%;
    padding:1em;
}

Note: This may be the same question asked, but not answered, here.

A: DEMO
Add
*, *:before, *:after {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing:border-box;
}


text:
Q: How to join mp3 files with their ends overlapping
Possible Duplicate:
Join multiple MP3 files (lossless)

I need to join hundreds of small mp3 files into one.
I know there are several mp3 cutters and joiner tools, what I need is their start/end points get mixed/overlapped. One should be able to specify time span in seconds, that will goes fade in / fade out / intermixed / overlapped over another.
I need to be able to do it in a batch.  Any solution must be free.


text:
Q: Expectancy of stationary 2-dimensional autoregression model Let us have the following AutoRegression process, expressed in term of lag operators:
$$ \begin{pmatrix} 1-0.4L & 0.1L \\ 0.1L & 1-0.4L \end{pmatrix} \begin{pmatrix} x_t \\ y_t \end{pmatrix} = \begin{pmatrix} 10 + e_{1t} \\ 1 + e_{2t} \end{pmatrix}$$
I have checked that $1-0.8L+0.15L^2$ has roots $\frac{10}{3}$ and $2$ so the process is stationary. I know how to find mean for a one-dimensional process, which is just applying "inverse operator" to the constant term. You just omit $L$s
I tried to do the same
$$ \frac{1}{0.35} \begin{pmatrix} 0.6 & -0.1  \\  -0.1 & 0.6 \end{pmatrix} \begin{pmatrix} 10 \\ 1 \end{pmatrix} = \begin{pmatrix} \frac{10}{7} \\ \frac{40}{35} \end{pmatrix}$$
Is this method still legit?

A: I think you are considering a vector autoregressive (VAR) process. VAR($p$) is written as:
$$\mathbf{\pi}(L)\mathbf{Y}_t = \mathbf{c} +\epsilon_t$$
where $\mathbf{\pi}(L)=\mathbf{I}_n-\pi_1L-...-\pi_pL^p$, and VAR($p$) is said to be stable if $\det\left(\mathbf{\pi}(L)=\mathbf{I}_n-\pi_1z-...-\pi_pz^p\right)$ have modulus greater than one. If it is stationary then:
$$\mathbf{\mu} = (\mathbf{I}_n-\pi_1-...-\pi_p)^{-1}\mathbf{c}$$
So, for bivariate VAR($1$) model: $\mathbf{Y}_t=\pi\mathbf{Y}_{t-1}+\epsilon_t$
$$\begin{matrix}
y_{1t} \\
y_{2t}
\end{matrix} = \begin{matrix}
\pi_{11} & \pi_{12} \\
\pi_{21} & \pi_{22}
\end{matrix}\times\begin{matrix}
y_{1t-1} \\
y_{2t-1}
\end{matrix}+\begin{matrix}
\epsilon_{1t} \\
\epsilon_{2t}
\end{matrix}$$
Then $\det(\mathbf{I}_2-\pi z)=0$ becomes:
$$(1-\pi_{11})(1-\pi_22 z)-\pi_{12}\pi_{21}z^2=0$$
Notice if $\pi_{12}=\pi_{21}=0$ then it reduces to univariate stability condition. I will leave it here, as extensive material is available online on this matter.
Reference Links

*

*https://faculty.washington.edu/ezivot/econ584/notes/varModels.pdf

*https://newonlinecourses.science.psu.edu/stat510/lesson/11/11.2


text:
Q: SCCM 2012 - some remote clients unable to download some applications, 401.2 error I've got a small SCCM 2012 deployment with about 35 clients attached. Most of these clients are in the same network as the single SCCM host, but three are about 1000 miles away.
Oddly, these three clients have stopped being able to download some application packages over BITS. Publishing a new package works for all the other clients, but for these three it never seems to download. If I go to the software centre, it just hangs at "0% downloaded".
On the client, the DataTransfer.log says (repeatedly):
CDTSJob::HandleErrors: DTS Job '{2DCBBB4C-6D84-479A-9218-885B72C834B9}' BITS Job '{E78147DD-4A26-4942-B4FD-6EC3EB77EECD}' under user 'S-1-5-18' OldErrorCount 442 NewErrorCount 443 ErrorCode 0x80072EE2    DataTransferService 30/07/2012 09:27:41 2964 (0x0B94)
CDTSJob::HandleErrors: DTS Job ID='{2DCBBB4C-6D84-479A-9218-885B72C834B9}' URL='http://sccm-host:80/SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1' ProtType=1   DataTransferService 30/07/2012 09:27:41 2964 (0x0B94)

Cas.log says (repeatedly):
Location update from CTM for content Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1 and request {AD041FCB-03D2-4FE6-A6FA-38A6B80FB2A1}  ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)
Download location found 0 - http://lonsbrndsccm02.mcs.int.thomsonreuters.com/SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1  ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)
Download request only, ignoring location update ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)

On the server, I've enabled failed request log tracing. The raw IIS log says the following:
2012-07-30 08:28:42 10.13.111.35 GET /SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1/sccm /NSCP-0.4.0.172-x64.msi 80 - 10.2.27.19 Microsoft+BITS/7.5 401 2 5 293

Which is a 401.2 error, meaning access denied. The failed request log is large, but the punchline is that it chucks out a Unauthorized: Access is denied due to invalid credentials. message.
All clients are members of the same domain and appear to be (otherwise) working great. I've re-installed the SCCM client, deleted and re-added the computer to SCCM.
Some other packages seem to work fine, the daily anti-malware delta gets downloaded and patched without issue.
Why are these packages failing?

A: Unsure if you resolved this yet, I'm dealing with similar issues but have found this article to help with some, but not all, clients having this issue.
http://support.microsoft.com/kb/2682514

A: Had a similar problem and I fixed it this way:

*

*Log onto DP server

*Go to IIS on server.

*Select Server and open ISAPI and CGI Restrictions

*If there is not an entry for SMS_DP add it with this path "C:\Windows\system32\inetsrv\smsfileisapi.dll"