text:
Q: JDBC is not executing SHOW DATABASES command i want to get a list of databases stored in mysql and put in java table using command "show databases" via a resultset. but its not working.
DefaultTableModel model=(DefaultTableModel)dbTbl.getModel();
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql//localhost/:3306","root","password");
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("show databases;");
    while(rs.next())
   {
    String db=rs.getString(1);
    model.addRow(new Object[] {db});
   }
    rs.close();
    stmt.close();
    con.close();
}
catch(Exception e)
{
    JOptionPane.showMessageDialog(null,"nahi chalda");
}

A: That's not the best way to get a list of Databases in JDBC. Here's the way it's done - using MetaData
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/:3306","root","password");
DatabaseMetaData meta = con.getMetaData();
ResultSet resultSet = meta.getCatalogs();
while (resultSet.next()) {
   String db = resultSet.getString("TABLE_CAT");
   model.addRow(new Object[] {db});
}
resultSet.close();
con.close();

See also: how to get list of Databases "Schema" names of MySql using java JDBC

A: I just forgot to add colon after "jdbc:mysql
Correct code is:
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/:3306","root","password");

It works ,......... !!!


text:
Q: Proper way to initialize a std::array from a C array I'm getting an array from a C API, and I'd like to copy this to a std::array for further use in my C++ code. So what is the proper way of doing that ?
I 2 uses for this, one is:
struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
memcpy((void*)a.data(), f.kasme, a.size());

And this
class MyClass {
  std::array<uint8_t, 32> kasme;
  int type;
public:
  MyClass(int type_, uint8_t *kasme_) : type(type_)
  {
      memcpy((void*)kasme.data(), kasme_, kasme.size());
  }
  ...
}
...
MyClass k(kAlg1Type, f.kasme);

But this feels rather clunky. Is there an idiomatic way of doing this, that presumably doesn't involve memcpy ? For MyClass` perhaps I'm better off with
the constructor taking a std::array that get moved into the member but I can't figure out the proper way of doing that either. ?

A: You can use algorithm std::copy declared in header <algorithm>. For example
#include <algorithm>
#include <array>

//...

struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
std::copy( f.kasme, f.kasme + a.size(), a.begin() );

If f.kasme is indeed an array then you can also write
std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Knockout foreach not matching length I'm having trouble displaying items from a knockout observable array.
The code below displays a length of 3 (so I know there are elements), yet the foreach does not display any rows.

            woot

The result of

is:
 [ { "Description" : null,
    "DeviceId" : "fake1",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake2",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake3",
    "DeviceType" : null,
    "Policy" : null
  }
]

Any advice much appreciated

A:

          woot

A: Are you showing all your javascript code in your question?
Regardless, here is a simple working example that includes a table cell for displaying the DeviceId;
hope it helps.
http://jsbin.com/UZIDira/2/edit?html,js,output
HTML

          woot

Javascript
var myJSON = [ { "Description" : null,
    "DeviceId" : "fake1",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake2",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake3",
    "DeviceType" : null,
    "Policy" : null
  }
];

function ViewModel() {
    var self = this;
    self.Data = ko.observableArray(myJSON);
}

// Activates knockout.js
ko.applyBindings(new ViewModel());


text:
Q: Is there a way to set Identity-core that do not allow same password when a user is changing the password at the project startup? Is there a way to set Identity-core that do not allow same password when a user is changing the password at the project startup ?
i do not want to check it with IF clause , i wanna set in Identity-core options or some where like this to manage it globally at my project( ASP.net core with C#)

A: First, you will have to store the previous password hashes separately in a table. Then
you will need to implement your own password validator and register it which should overwrite the default password validator for asp.net core identity.

*

*Implement Microsoft.AspNetCore.Identity.IPasswordValidator as
public class MyPasswordValidator: IPasswordValidator
{
    public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
    {
        // custom validation logic
        // search for previous passwords based on user's id and see if they match
    }
}

*Register it in the services. Make sure you place it at after registering all the default asp.net identity identity services.
services.AddScoped<IPasswordValidator<ApplicationUser>, MyPasswordValidator>();

You can also implement an additional property for previous passwords in your ApplicationUser class so that all the previous passwords are already present in your user variable

A: You don't need to have as a function in User class to be access it easy, because password change should be allowed in 1 page only, so the code that checks also can live on that page (model/controller).
THE EASIEST WAY is the obvious one - in password change controller you MUST collect OLD password and NEW one as a plain text - so why not just compare them? :D
Less easy way: Just use signInManager.CheckPasswordSignInAsync in password change controller (if for some reason you dont have old password as a plain text), BEFORE changing pass. If success you would know that new pass is the same.
The best way: [checking old passwords to protect from setting the same after first setting new, then resetting to old (the same)] password History for Identity Core


text:
Q: Re-sizing prestashop 1.5 shome slider im using Prestashop 1.5 and i want the home slider to be 600px tall and 2000px wide... So I changed those dimensions in the back-office inside the modules configuration..
The size changed but images are no longer centered, they cover the whole slider but seem to be zoomed in a way so that I cant see the image correctly..
Should I change anything else? See picture attached!

A: Delete your existing slides, then create them again, but with images that are wider than 2000px and higher than 600px.
After that, empty your PrestaShop cache.


text:
Q: Objective-c the init/initialize method I don't understand some cases :
1)
  +(void)initialize {

        if(self == [Bicycle class]) // Make sure it's not executed more than once
        _defaultMark = @"Unbranded product";

   }

I understand that this method is the first method called. But I don't understand why it permits to be sure that's not executed more than once ? After one execution , the self is always equal to Bicycle class in this case, non ?
2)
if(self = [ super init])

Can someone explain me clearly why it's really necessary to do it in the init or initWithSomething method ?
3) A HS question
@protocol StreetLegal <NSObject>

What if we don't use  avec the protocol name ?

A: I think that in case 1) self points to the Class object.
In the case 2) self points to the instance object.
+(void)initialize is guaranteed that it is called only once per Class (is the Class initializer). This is ensured by the framework/language.
I think that the initialize you posted is in some base class. If it is in the base class, than the initialize is called also for the descendent classes. In this way you ensure that the if-then is executed only for the Bicycle class. But.. I think that a better design can be achieved...
EDIT:
point 2). It is necessary because you have to call explicitly the initializer of your parent class.
point 3) I don't understand your question...

A: 1) This method is called once per class - suppose you have
@interface Foo : NSObject
@end

@implementation Foo
+ (void) initialize { .... };
@end

@interface Bar : Foo
@end

@implementation Bar
@end

In this case the same method will be called the first time Foo is used and when Bar is used the first time it would be called again. So the condition if (self == [Foo class]) ensures to execute the body only once.
2) constructors can assign to self... and can return nil... so you should check

A: Most of your init methods will look like this:
if ((self = [super init]) != nil)
{
}

return self;

First, you must call an init method of the superclass, or your object will not be initialised properly. Second, the superclass can return a different object, so you must assign the result to self, and third the superclass can return nil, so you must check that it isn't nil.
In your own initialisers, you will yourself set self to nil and return nil if your init method discovers that the object cannot be initialised properly.

A: Question 1:
Is nicely answered in the documentation

The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize].

For example, if you override +initialize in class A and then you create a subclass B of A without overriding +initialize, then the method +[A initialize] will be called once for class A and once for class B. The class equals check is there to avoid the block to be called multiple times.
Question 2:
Again, you will find lots of information in the documentation. You want to call [super init] because you need the superclass initializer to run (otherwise the superclass structures wouldn't be initialized properly). The assignment to self is necessary because you don't always know what will be returned. In case of an unexpected error, you should expect a nil returned and check accordingly.
Question 3:
You are declaring a protocol which itself inherits from another protocol. NSObject isn't only a root class, there is also a root protocol called NSObject. You don't have to use it, of course. However, when you then declare a variable as id<MyProtocol> without MyProtocol being a subprotocol of NSObject, you won't be able to call NSObject protocol methods on that variable.


text:
Q: Setting a custom Adapter for a ListView causes my app to jump to the previous activity When I try to populate my listview with my custom adapter or object of my custom class, the application jumps back to the previous activity.
I tried to debug, but I can't find the row that causes this behavior.
Maybe there's something with the layout that at the moment to to be inflated and drawn encounters some problem.
ACTIVITY CODE
try {
        JSONObject obj = new JSONObject(response);

        String objservice = obj.getString("service");
        String objstatuCode = obj.getString("status-code");
        String objdescription = obj.getString("status-description");

        JSONObject result = obj.getJSONObject("result");

        JSONArray cronologie = result.getJSONArray("dettaglioAttivita");

        inputItems = new ArrayList<DTOLibrettoCronologia>();

        for (int i = 0; i < cronologie.length(); i++) {

            JSONObject row = cronologie.getJSONObject(i);

           DTOLibrettoCronologia tmp = new DTOLibrettoCronologia("s", "s", "s", "s", "s", "s", "s");
            inputItems.add(tmp);

        }

    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }

    librettoCronologiaAdapter adapter = new librettoCronologiaAdapter(getApplicationContext(),
            R.layout.libretto_cronologia, inputItems);

    listView = (ListView) findViewById(R.id.cronologia_listview);
    listView.setAdapter(adapter);
    listView.setSmoothScrollbarEnabled(true);

XML ELEMENT CODE
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id = "@+id/libretto_cronologia_element"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="0dp"
    android:background="@color/transparent">
    <!-- primary wrapper -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/transparent">

        <!--image -->
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/transparent"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="16dp">
            <ImageView
                android:id="@+id/cronologiaState"
                android:layout_width="36dp"
                android:layout_height="40dp"
                android:src="@drawable/check_cronologia_fail"/>
        </LinearLayout>

        <!--text -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/transparent"
            android:paddingLeft="8dp"
            android:paddingTop="8dp">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Data Appello: "/>
                <TextView
                    android:id="@+id/cronologiaDataAppello"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="tipo: "/>
                <TextView
                    android:id="@+id/cronologiaTipo"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Voto/Giudizio: "/>
                <TextView
                    android:id="@+id/cronologiaVoto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
                </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Stato: "/>
                <TextView
                    android:id="@+id/cronologiaStato"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Data Verb: "/>
                <TextView
                    android:id="@+id/cronologiaVerb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Superato: "/>
                <TextView
                    android:id="@+id/cronologiaSuperato"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="content"/>
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

XMLACTIVITY CODE
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cronologia_materia"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal|bottom">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- TOP BAR -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/colorPrimary"
            android:padding="20dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="cronologia esami per"
                android:textSize="13dp"/>
            <TextView
                android:id="@+id/nomeMateria"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="-"
                android:textSize="18dp"/>
        </LinearLayout>

        <!-- general info -->
        <LinearLayout
            android:id="@+id/recapWrapper"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparent"
            android:orientation="vertical"
            android:padding="20dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/annoCorso"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Anno di Corso:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/annoCorsoValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/tipologia"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Tipologia d'esame:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/tipologiaValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/corso"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Corso di Studio:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/corsoValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/dataSperamento"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Data di Superamento:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/dataSperamentoValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/votoFinale"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Voto Finale"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/votoFinaleValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/peso"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Peso:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/pesoValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/Valutazione"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Valutazione:"
                    android:paddingRight="10dp"/>
                <TextView
                    android:id="@+id/ValutazioneValue"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="-" />
            </LinearLayout>

        </LinearLayout>

        <!-- LISTVIEW -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="@color/transparent"
            android:padding="20dp">

            <ListView
                android:id="@+id/cronologia_listview"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </ListView>

        </LinearLayout>

    </LinearLayout>
</FrameLayout>

CUSTOM ADAPTER CODE
public class librettoCronologiaAdapter extends ArrayAdapter<DTOLibrettoCronologia> {

    Context context;
    int rand = 0;

    public librettoCronologiaAdapter(Context context, int risorsaId,
                                     List<DTOLibrettoCronologia> items) {
        super(context, risorsaId, items);
        this.context = context;
    }

    //metodo getView --> ritorna la view da inserire nella ListView

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

        //controllo se c'è gia un layout
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        DTOLibrettoCronologia content = getItem(position);

        Toast.makeText(getContext(), "adapter", Toast.LENGTH_SHORT).show();

        return convertView;
    }

LOGCAT
FATAL EXCEPTION: main
                                                                    Process: design.ubris.myuni, PID: 14189
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
                                                                        at android.widget.AbsListView.obtainView(AbsListView.java:2436)
                                                                        at android.widget.ListView.makeAndAddView(ListView.java:1986)
                                                                        at android.widget.ListView.fillDown(ListView.java:709)
                                                                        at android.widget.ListView.fillFromTop(ListView.java:770)
                                                                        at android.widget.ListView.layoutChildren(ListView.java:1749)
                                                                        at android.widget.AbsListView.onLayout(AbsListView.java:2210)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                        at com.android.internal.policy.DecorView.onLayout(DecorView.java:774)
                                                                        at android.view.View.layout(View.java:17702)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2519)
                                                                        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2234)
                                                                        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1372)
                                                                        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6774)
                                                                        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                                                                        at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                                                                        at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                                                                        at android.os.Handler.handleCallback(Handler.java:761)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                        at android.os.Looper.loop(Looper.java:156)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

A: simply adding this to the adapter getView method:
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.libretto_cronologia, null);
    }

:D :D


text:
Q: How to get total number of rows after conditional query search I'm running a query search of consecutive blocks on the bitcoin blockchain looking for consecutive blocks that were mined more than 2 hours apart. The code I have below works perfectly and returns all the values that I'm looking for, but I'm struggling with getting the code to output the COUNT(*) of all the rows from my query. I'm new to SQL and have managed to get the code to output exactly what I need so far. I would just like to get a count output, I've manually counted and it should be 152.
This is the query site that I am using since I do not have the tech specs to set up a node and have the whole blockchain available to run on my computer. https://blockchainsql.io/
Thank you all in advance.
SELECT
    B1.Height AS FromBlock,
    B2.Height AS ToBlock,
    B1.TimeStampUtc AS FromTime,
    B2.TimeStampUtc AS ToTime,
    IIF(B2.TimeStampUTC < B1.TimeStampUTC, '-', '') +
    RIGHT('00' + CONVERT(varchar, (DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) / 86400)), 2) + ':' +
    CONVERT(varchar, DATEADD(ss, DATEDIFF(SECOND, IIF(B1.TimeStampUTC < B2.TimeStampUTC, B1.TimeStampUTC, B2.TimeStampUTC), IIF(B2.TimeStampUTC > B1.TimeStampUTC, B2.TimeStampUTC, B1.TimeStampUTC)), 0), 108)
    AS Duration_DDHHMMSS,
    DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) as DurationSeconds
FROM
    Block B1 INNER JOIN
    Block B2 ON B1.Height = B2.Height - 1
WHERE
    B1.BranchID = 1 AND  -- Ignore orphaned blocks
    B2.BranchID = 1 AND  -- Ignore orphaned blocks
    (DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) >=  7200 OR DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) <= -7200)
ORDER BY
    Duration_DDHHMMSS DESC

A: SELECT SQL_CALC_FOUND_ROWS
    B1.Height AS FromBlock,
    B2.Height AS ToBlock,
    B1.TimeStampUtc AS FromTime,
    B2.TimeStampUtc AS ToTime,
    IIF(B2.TimeStampUTC < B1.TimeStampUTC, '-', '') +
    RIGHT('00' + CONVERT(varchar, (DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) / 86400)), 2) + ':' +
    CONVERT(varchar, DATEADD(ss, DATEDIFF(SECOND, IIF(B1.TimeStampUTC < B2.TimeStampUTC, B1.TimeStampUTC, B2.TimeStampUTC), IIF(B2.TimeStampUTC > B1.TimeStampUTC, B2.TimeStampUTC, B1.TimeStampUTC)), 0), 108)
    AS Duration_DDHHMMSS,
    DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) as DurationSeconds
FROM
    Block B1 INNER JOIN
    Block B2 ON B1.Height = B2.Height - 1
WHERE
    B1.BranchID = 1 AND  -- Ignore orphaned blocks
    B2.BranchID = 1 AND  -- Ignore orphaned blocks
    (DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) >=  7200 OR DATEDIFF(SECOND, B1.TimeStampUTC, B2.TimeStampUTC) <= -7200)
ORDER BY
    Duration_DDHHMMSS DESC;

And then run a second query
SELECT FOUND_ROWS();

But it would just be so much simpler to count the result set in the programming language you are using.
SQL_CALC_FOUND_ROWS is mostly useful when using Limit inside the query


text:
Q: How can i push data into react-admin store? I'm trying to build a web app with react-admin and need to push data to the redux store. I read the React-admin docs (https://marmelab.com/react-admin/Actions.html) and when I try to do that, I get Failures.
Here is my code
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withStyles, MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import {
    Menu,
    Notification,
    Sidebar,
        setSidebarVisibility,
} from 'react-admin';

import {kidsLoad} from './customActions/KidsActions'

import AppBar from './MyAppBar';
const styles = theme => ({
    root: {
        display: 'flex',
        flexDirection: 'column',
        zIndex: 1,
        minHeight: '100vh',
        backgroundColor: theme.palette.background.default,
        position: 'relative',
    },
    appFrame: {
        display: 'flex',
        flexDirection: 'column',
        overflowX: 'auto',
    },
    contentWithSidebar: {
        display: 'flex',
        flexGrow: 1,
    },
    content: {
        display: 'flex',
        flexDirection: 'column',
        flexGrow: 2,
        padding: theme.spacing.unit * 3,
        marginTop: '1em',
        paddingLeft: 5,
    },
});

class MyLayout extends Component {
    componentWillMount() {
        this.props.setSidebarVisibility(true);
        }

        componentDidMount(){
            const { kidsLoad, record } = this.props;

            kidsLoad({data: "HELLOOOOOOOOOOOO!!!!!"})

        }

    render() {
        const {
            children,
            classes,
            dashboard,
            isLoading,
            logout,
            open,
            title,
        } = this.props;
        return (

                    <AppBar title={title} open={open} logout={logout} />

                            {children}

                    <Notification />

        );
    }
}

MyLayout.propTypes = {
    children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
    dashboard: PropTypes.oneOfType([
        PropTypes.func,
        PropTypes.string,
    ]),
    isLoading: PropTypes.bool.isRequired,
    // logout: componentPropType,
    setSidebarVisibility: PropTypes.func.isRequired,
        title: PropTypes.string.isRequired,
        kidsLoad: PropTypes.func,
};

const mapStateToProps = state => ({ isLoading: state.admin.loading > 0 });
export default connect(mapStateToProps, { setSidebarVisibility, kidsLoad })(withStyles(styles)(MyLayout));

I did everything like in the documentation (https://marmelab.com/react-admin/Actions.html).
What did I do wrong?
How do you add data to the store in this framework?

A: This is going to be a quick answer that I leave for further improvement.
If I understand your question correctly you got some of your resources (entities) updated and you want react-admin to know about it and update its store accordingly triggering updates in app views if necessary.
The first thing we have to get is the dispatch function of the react-admin store. In my case, the source of resource update was a React component, so I used withDataProvider decorator to receive a reference to the dispatch function.
Once you have the dispatch function you dispatch, for example, CRUD_UPDATE_SUCCESS action for a particular resource update in the react-admin store.
import { CRUD_UPDATE_SUCCESS, FETCH_END, UPDATE } from 'react-admin';

dispatch({
  type: CRUD_UPDATE_SUCCESS,
  payload: { data },
  meta: {
    resource,
    notification: {
      body: 'ra.notification.dataSaved',
      level: 'info'
    },
    fetchResponse: UPDATE,
    fetchStatus: FETCH_END
  }
});

You can also use action creators from react-admin. Like showNotification, for example.
import { showNotification } from 'react-admin';

dispatch(showNotification(errorMessage, 'warning', { autoHideDuration: 10000 }));

A bit more consistent piece of code here to show how all this can work together. The Updater component here renders its child components passing them a resource record and subscribes for their onSubmit callback to perform entity saving and updating react-admin store.
import React from 'react';
import {
  CRUD_UPDATE_SUCCESS, FETCH_END, UPDATE, withDataProvider, showNotification
} from 'react-admin';

class Updater extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleUpdate(record) {
    const { resource, dataProvider, dispatch } = this.props;

    const payload = {
      id: record.id,
    };

    payload.data = {...record};

    return new Promise((resolve, reject) => {
      dataProvider(UPDATE, resource, payload)
        .then(({data}) => {
          dispatch({
            type: CRUD_UPDATE_SUCCESS,
            payload: { data },
            meta: {
              resource,
              notification: {
                body: 'ra.notification.dataSaved',
                level: 'info'
              },
              fetchResponse: UPDATE,
              fetchStatus: FETCH_END
            }
          });

          resolve(data);
        })
        .catch(e => {
          const errorMessage = e.message || e;

          this.setState({ errorMessage });

          dispatch(
            showNotification(errorMessage, 'warning', { autoHideDuration: 10000 })
          );

          reject(errorMessage);
        });
    });
  }

  render() {
    const { record, children } = this.props;
    const { errorMessage } = this.state;

    return React.Children.only(React.cloneElement(children, {
      record,
      errorMessage,
      onUpdate: this.handleUpdate
    }));
  }
}

export default withDataProvider(Updater);

HTH,
Ed


text:
Q: Create wireless access point and share internet connection with nmcli How can I create a Wi-Fi hotspot with the command line tool nmcli and share/bridge the ethernet internet connection with the wireless access point? Furthermore, how can I start this automatically at boot?
Is this possible with nmcli?

A: I created a Hotspot with the GNOME Network-Manager. The problem was, that I can not configure the SSID and password in GUI. If you create the Hotspot with the Network-Manager GUI, it creates the file /etc/NetworkManager/system-connections/Hotspot. In that file it is possible to edit the SSID and the password.
sudo vim /etc/NetworkManager/system-connections/Hotspot

The content of the file looks like this:
[connection]
id=Hotspot
uuid=0bf627gd-8e34-48c6-865a-06f898b4y1hb
type=wifi
autoconnect=true
permissions=
secondaries=

[wifi]
hidden=false
mac-address=YOUR_WIFI_INTERFACE_MAC_ADDRESS
mac-address-blacklist=
mode=ap
seen-bssids=
ssid=SSID_NAME

[wifi-security]
group=ccmp;
key-mgmt=wpa-psk
pairwise=ccmp;
proto=rsn;
psk=YOUR_WIFI_AP_PASSWORD

[ipv4]
dns-search=
method=shared

[ipv6]
dns-search=
method=auto

I changed the ssid and the psk properties to my needs. To enable autostart you have to set the parameter autoconnect to true. Then I restarted my computer because the command: sudo systemctl restart NetworkManager for network restart seems not to work correctly, because in the Network-Manager GUI:

I have no wireless network settings anymore and also the following command worked not before the restart. After restart you can use the nmcli command to start the access point.
nmcli con up Hotspot ifname YOUR_WIFI_INTERFACE

YOUR_WIFI_INTERFACE you can find out with the command iwconfig.
I used Antergos / Arch Linux for the above solution and found the hint to this at the ask.fedoraproject.org site.

A: I know this is an old question, but thought I would add my comments as this may help someone in the future.
The whole process is just three commands as @Dzik has correctly mentioned.
nmcli connection add type wifi ifname wlan0 con-name local-ap autoconnect yes ssid test-ap mode ap
nmcli connection modify con-name 802-11-wireless.mode ap 802-11-wireless-security.key-mgmt wpa-psk ipv4.method shared 802-11-wireless-security.psk 'PASSWORD'
nmcli connection up con-name

This will start an AP for you.
To verify, we can use:
nmcli dev wifi list

A: You can create a hotspot with the following:
nmcli dev wifi hotspot ifname wlp4s0 ssid test password "test1234"

(where wlp4s0 is the name of your Wifi interface).
Reference: https://wiki.debian.org/WiFi/HowToUse#Troubleshooting_.26_Tips_for_NetworkManager

A: Just
nmcli dev wifi hotspot

will generate a password and start a hotspot with SSID Hotspot-<YOUR_HOSTNAME> on the default wifi interface.
To show the Wi-Fi name and password (and a QR code):
nmcli dev wifi show-password

From nmcli dev wifi --help:
ARGUMENTS := hotspot [ifname <ifname>] [con-name <name>] [ssid <SSID>]
                                         [band a|bg] [channel <channel>] [password <password>]

Create a Wi-Fi hotspot. Use 'connection down' or 'device disconnect'
to stop the hotspot.
Parameters of the hotspot can be influenced by the optional parameters:
ifname - Wi-Fi device to use
con-name - name of the created hotspot connection profile
ssid - SSID of the hotspot
band - Wi-Fi band to use
channel - Wi-Fi channel to use
password - password to use for the hotspot

Note: You need a DHCP server installed (e.g. dnsmasq), or you'll get
IP configuration could not be reserved (no available address, timeout, etc.).

For the "start on boot" part: see Autostarting page in ArchWiki for an overview.
(The first command here was intended as a comment to ysdx's answer, but I don't have enough rep)

A: On a Centos 7 it looks like this.
Check if AP is possible at all:
iw list | less

and search for "AP" among supported interface modes.
Browse your devices to find the name:
nmcli d

And setup and start your hotspot.
Mind that wifi-device, connection-name and hotspot-ssid are specific to your system.
nmcli c add type wifi ifname wifi-device con-name connection-name autoconnect no ssid hotspot-ssid
nmcli connection modify connection-name 802-11-wireless.mode ap 802-11-wireless.band bg ipv4.method shared
nmcli connection modify connection-name wifi-sec.key-mgmt wpa-psk
nmcli connection modify connection-name wifi-sec.psk "le password"
nmcli connection up connection-name

Check also:

*

*https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/sec-Using_the_NetworkManager_Command_Line_Tool_nmcli.html

*https://www.hogarthuk.com/?q=node/8


text:
Q: Laravel websocket in subdirectory please can you help me.
My scheme of files is:
var/www/turnerosac --> files base projects
/var/www/html/turnerosac --> files public

When executing the command:
/usr/bin/php /var/www/turnerosac/artisan websocket:serve

Throw the following message in the console
Starting the WebSocket server on port 6001...
New connection opened for app key e992c96bf63f43766490.
Connection id 154192426.353203179 sending message {"event":"pusher:connection_established","data":"{"socket_id":"154192426.353203179","activity_timeout":30}"}

My bootstrap.js
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'e992c96bf63f43766490',
    cluster: 'us2',
    wsHost: window.location.hostname,
    wsPort: 6001
    // disableStats: true,
});

In browser


text:
Q: Jupyter Notebook + Matplotlib; Freeze on plot.show() OBJECTIVE

*

*Use Matplotlib to plot the state of Texas

CODE
import pandas as pd
import numpy as np
matplotlib.use('QT4Agg')
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

map = Basemap(projection='merc', lat_0 = 57, lon_0 = -135,
    resolution = 'h', area_thresh = 0.1,
    llcrnrlon=-106.65, llcrnrlat=25.83,
    urcrnrlon=-93.50, urcrnrlat=36.50)

map.drawcoastlines()
map.drawstates()
map.drawcountries()
map.fillcontinents(color = 'white')
map.drawmapboundary()

plt.show(block = False)

OUTPUT

DEBUG

*

*Apparently changing backend helps, however matplotlib.use('QT4Agg') yields the following error "Gtk* backend requires pygtk to be installed"

*Looked online for solutions, read you had to install PyGTK, however, when installing, I receive the following error: Building PyGTK using distutils is only supported on windows. (after inputting pip install PyGTK)

*Additionally, despite calling matplotlib.use('QT4Agg'), I receive the error matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time..
ISSUE

*

*Cannot properly install packages necessary to prevent matplotlib from running in a continual loop. Am I missing something here? Are there workarounds?

*Why, despite calling matplotlib('QT4Agg') before importing matplotlib, I receive the error (bullet point #3) listed above?

A: Is this in Jupyter Notebook or something of the sort? Usually you shouldn't be able to do
matplotlib.use('QT4Agg')
import matplotlib

in that order, as matplotlib wouldn't be in the namespace. Change the order, then restart your Jupyter kernel or dump all this into a .py file.
In Jupyter, you should be able to call
%matplotlib qt4

before importing matplotlib to set the backend instead of calling use().


text:
Q: Windows 7 boot from read only disk Is there a way to make Windows 7 boot from a read-only disk?
I want to have a system, that no Windows Update, no other Software will change. After a reboot everything should be recovered.
If there is not such an option, is there an option, that every reboot writes an image to the primary disk and boot it?

A: When I was in college for Computer Science, I remember the computers in the tech labs were installed with Deep Freeze, which holds the initial image of the Windows install (I believe in a hidden partition?), and erases all changes and restores it every reboot.
While it wasn't exactly a "read-only" system, nothing you did was saved on the drive after the reboot. Even if you screwed Windows over royally, all changes were undone.

A: You can do this if you build the Windows 7 box in VMware, there is an option to set the disk so any changes are temporary - it reverts on reboot.
Alternatively you can use WinPE for a read only (but limited) Windows system.

A: If you are a home user, you could try Returnil for free. It works slightly differently, in that you have to turn it on by hand, but when you do, it will discard all changes until you reboot. The main advantage here is that it is super easy to set up, no complicated configuration needed.
VMs are also a good choice (I like VirtualBox), but the other answers have already covered them some detail.


text:
Q: calculating jquery datatable column inside jquery datatable I'm using sum plugin in order to sum values from particular column
 $('#example').DataTable( {
    drawCallback: function () {
      var api = this.api();
      $( api.table().footer() ).html(
        api.column( 4, {page:'current'} ).data().sum()
      );
    }
  } );

How can use this api call to calculate another column (for example column 6).
$( api.table().footer() ).html(
    api.column( 4, {page:'current'} ).data().sum()
    // calculate column 7
);

also calculate result is injected inside first column of the footer instead of 4.

A: You were nearly there but your reference to api.table().footer() got the whole footer. To target specific column footers you need to use api.column(?).footer(). That way your issue should be addressed like this:
$(api.column(4).footer()).html(
  api.column(4, {
    page: 'current'
  }).data().sum()
);
$(api.column(6).footer()).html(
  api.column(6, {
    page: 'current'
  }).data().sum()
);

Here's a working example, hope that helps.


text:
Q: How to replace last occurrence of characters in a string using javascript I'm having a problem finding out how to replace the last ', ' in a string with ' and ':
Having this string:
test1, test2, test3
and I want to end out with:
test1, test2 and test3
I'm trying something like this:
var dialog = 'test1, test2, test3';
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');

but it's not working

A: foo.replace(/,([^,]*)$/, ' and $1')

use the $ (end of line) anchor to give you your position, and look for a pattern to the right of the comma index which does not include any further commas.
Edit:
The above works exactly for the requirements defined (though the replacement string is arbitrarily loose) but based on criticism from comments the below better reflects the spirit of the original requirement.

console.log(
   'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1')
)

A: result = dialog.replace(/,\s(\w+)$/, " and $1");

$1 is referring to the first capturing group (\w+) of the match.

A: regex search pattern \s([^,]+)$
Line1: If not, sdsdsdsdsa sas ., sad, whaterver4
Line2: If not, fs  sadXD sad ,  ,sadXYZ!X
Line3: If not d,,sds,, sasa sd a, sds, 23233

Search with patterns finds
    Line1: whaterver4
    Line3: 23233
Yet doesnt find  Line2: sadXYZ!X
Which is only missing a whitespace


text:
Q: why form is submitted while new window is open? Hi I have the javascript function to open a new window and based on the value selected its populated the parent window field .But the problem is while open the new window the form is submitted .I just didn't attach the validation part. Can any body tell what might be the problem.

$(function() {
//Popup window for Nationlity
function nationalityPopUp() {
        var nationalUrl="%bind(:9)";
     new_Window = window.open(nationalUrl,"","width=220, height=500, left=250, top=50, scrollbars, resizable");
}

//Disable Parent Window
function parent_disable() {
 if(new_Window && !new_Window.closed){
  new_Window.focus();
 }
}

 <form name="Basicinfo" id="Basicinfo" method="post" action="%bind(:8)" onsubmit="return validateForm();">

       <input type="text" name="Nationality" id="Nationality" value ="" />
                <input type="image" src="%bind(:14)" name="Ntlylkp" onclick="nationalityPopUp();"  />

*Country Of Residency:
       <input type="text" name="Residency_country" id="Residency_country" value ="" onblur="validateResCountry(value)"/>
    <input type="image" src="%bind(:14)" name="Cntrylkp" onclick="countryPopUp();"/>

*National Id:
        <input id="Emirates_Id" name="Emirates_Id" type="text" value=""  style="margin-left:10px;">

*Marital Status:
             <select name="marital_status" id="marital_status">
      :%bind(:3);
                </select>

 *Regional Preference:
             <select name="religious" id="religious">
      :%bind(:4);
                </select>
<input type="Submit" value="Submit And Next" style="float:right" >

</form>

A: return false while the for is submitted with jquery -
$('#Basicinfo').on('submit', function() {
     if (some check needed) { // if want to add any check to submit the form or not
         return false;
     }
})


text:
Q: Insecure content in iframe on secure page I'm in the in the process of developing an application for a client, which will have an SSL certificate and be served under https. However, to integrate with their existing site they want to provide their navigation inside an iframe.
I can see this causing trouble, as I'd expect the browser to complain about the mix of secure and insecure content on the page. I've had a look at similar questions on here and they all seem to refer to this the other way round (secure content in the iframe).
What I'd like to know, then, is: will it cause issues to have insecure content included inside an iframe, placed on a secure page , and if so what sort of problems would they be?
Ideally if it's not a good idea (and I have a strong feeling that it isn't) I need to be able to explain this to the client.

A: If your page is http then it allows iframe with https content.
But if your page is https then it does not allow http content.
Lets put down following possibilities.
page - iframe - status

http - http  - allowed
http - https - allowed
https- http  - not allowed
https- https - allowed

A: If your page is being accessed using https://www.example.com/main/index.jsp (SSL) then your browser will complain with "This page contains both secure and insecure items" if there are any resources in the HTML code that are referenced with http:// (non-SSL). This includes iframes.
If your navigation page is hosted on the same server then you can prevent the "insecure content" message by using a relative URL like this...
<iframe src="/app/navigation.jsp" />

From your question it sounds like your navigation page is being served from a separate host and you're being forced to use something like this
<iframe src="http://otherserver.example.com/app/navigation.jsp" />

which will of course cause the "insecure content" message in your browser.
Your only solutions are to either

*

*implement SSL on the server holding your navigation page so you can use https:// for your iframe reference, or

*move the navigation application to the same server so you can use a relative URL.
Personally I can't see why your navigation would be on a different host because then you're going to get JavaScript cross-domain scripting issues (unless some funky JSONP is involved).

A: Try removing the http: characters in the src attribute's value as so:
<iframe src="//example.com/thefile.htm"></iframe>

This is of course a workaround, security is important so don't bypass blithely, but anyway this once got me past a similar problem.


text:
Q: GWT RPC call doesn't rollback transaction after runtime exception I yet don't know GWT such deep as I want. So I'd want to ask someone who know GWT well.
I have problem with rollback transaction in GWT 2.3. Say, GWT makes RPC call of service, and there will be thrown NullPointerException. As far as I am seeing now, implementation of doUnexpectedFailure in the class AbstractRemoteServiceServlet doesn't rethrow any exception - it just resets response and logging exception. Also, documentation for that method says that I should override this method to handle unexpected exception in GWT. Did anybody deal with this problem? Did anybody override doUnexpectedFailure? How could I correct do this?
Thanks for any comment in advance and sorry for my English!

A: Take a look in the manual:
http://www.gwtproject.org/doc/latest/tutorial/RPC.html
Say, you have a service in your client:
private MyServiceAsync service= GWT.create(MyService.class);

Now, the service is created
This is the way a call in your client will look like:
// Set up the callback object.
AsyncCallback<MyModel> myCallback = new AsyncCallback<MyModel>() {
  public void onFailure(Throwable caught) {
    try {
      throw caught;
    } catch (NullPointerException e) {
       // TODO: Handle your NPE
    }
  }

  public void onSuccess(MyModelresult) {
    // everything is ok
  }
};
// Make the call to the stock price service.
service.doSomethingOnTheServer(callback);

In the onFailure method you can handle your NPE on the client side. The doUnexpectedFailure-method is called, because your NPE is not a checked exception.


text:
Q: XPATH EXPRESSION: removing a node in between I have this xml file:
  <Item Text="Reports" Navigateurl ="Reports/Default.aspx" Select="true">
  <Group>
    <Item Text="Customers" NavigateUrl="Reports/Customers/Default.aspx" Select="true">
      <Group>
        <Item Text="Customers" NavigateUrl="Reports/Customers/CustomerList.aspx"
            Select="true"   />
        <Item Text="Customer Products"
         NavigateUrl="Reports/Customers/CustomersProducts.aspx" Select="true" />
        <Item Text="Customer Measurements"
        NavigateUrl="Reports/Customers/CustomerLocationMeasurements.aspx" Select="true"  />
        <Item Text="Customer Groups" NavigateUrl="Reports/Customers/CustomerGroups.aspx"
         Select="true"/>
        <Item Text="Customer Outages" NavigateUrl="Reports/Customers/CustomerOutages.aspx"
         Select="true" />
      </Group>
    </Item>
    <Item Text="Rules" NavigateUrl="Reports/Rules/Default.aspx" Select="true" >
      <Group>
        <Item Text="Customer Product Rules"
         NavigateUrl="Reports/Rules/CustomerProducts.aspx" Select="true"/>
        <Item Text="Customer Product Rules Event Limits"
          NavigateUrl="Reports/Rules/CustomerProductEventLimits.aspx" Select="true" />
        <Item Text="Customer Product  Rules Curtailable Days/Hours"
         NavigateUrl="Reports/Rules/CustomerProductCurtailableDaysHours.aspx"
          Select="true"  />
      </Group>
    </Item>
     </Group>
  </Item>

SO, when I use this XPATH Expression,
          XmlDataSource XmlDataSource1 = new XmlDataSource();
        XmlDataSource1.DataFile = "~/Menu.xml";
        XmlDataSource1.XPath = "//Item[@Text ='Reports']/Group/Item
                                  [@Select='true']
        XmlDataSource1.DataBind();
        SiteMap1.DataSource = XmlDataSource1;

I get this output:
         Customers
            Group
               Customer Pages
          Rules
             Group
               Rules Pages

But I dont want the Group tag to be shown in the output. Can u please let me know how this can be achieved?

A: XPath is a query language for selecting nodes or extracting other data from an XML document. As such it cannot modify the structure of a document -- such as delete a node.
Such kind of processing -- called transformation, can be easily done with XSLT and (not so easily) with XQuery.


text:
Q: "Invalid object name"Error in fluent nhibernate configuration I'm using fluent nhibernate in my application and I also use sql server 2012. this is my configuration:
public class SessionFactory
    {
        private static ISessionFactory _sessionFactory;

        public static string ConnectionString
        {
            get { return ConfigurationManager.ConnectionStrings["ECommerceConnectionString"].ToString(); }
        }

        private static void Initialize()
        {
            var config = Fluently.Configure().Database(
                MsSqlConfiguration
                    .MsSql2008
                    .ConnectionString(ConnectionString).ShowSql().Dialect<MsSql2012Dialect>());
            _sessionFactory = config.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ContactMapping>()).BuildSessionFactory();
        }

        private static ISessionFactory GetSessionFactory()
        {
            if (_sessionFactory == null)
                Initialize();

            return _sessionFactory;
        }

        private static ISession GetNewSession()
        {
            return GetSessionFactory().OpenSession();
        }

        public static ISession GetCurrentSession()
        {
            var sessionStorageContainer = SessionStorageFactory.GetStorageContainer();

            var currentSession = sessionStorageContainer.GetCurrentSession();

            if (currentSession == null)
            {
                currentSession = GetNewSession();
                sessionStorageContainer.Store(currentSession);
            }

            return currentSession;
        }
    }

although I'm using MsSql2012Dialect but I still got the sql server compatibility error, how can I fix this please??

A: You should really use
 Fluently.Configure()
            .Database(
                MsSqlConfiguration
                .MsSql2012
                .ConnectionString(conString)
                .ShowSql)

works for me fluently
The error "Invalid object name" usually references to a SQL exception that for example a table does not exist or something like that... A full stack trace/error message would help.


text:
Q: Multithreading violation core data I have an app where I download the data on startup using a list of operations and it crashes randomly for unknown core data reasons so I spent few days on checking the best practices to update/fetch data in multithreading core data with MagicalRecord. One of the options was to enable the multithreading debugger -com.apple.CoreData.ConcurrencyDebug 1 where Xcode stops the apps when it violates one of their rules. So, Xcode stops my app on this line [SyncRequestEntity MR_createEntityInContext:[self getPrivateContext]]
+ (MagicalRecordVersionNumber) version
{
    return MagicalRecordVersionNumber2_3;
}
@implementation NSManagedObjectContext (MagicalRecord)

+ (NSManagedObjectContext *) MR_context
{
    return [self MR_contextWithParent:[self MR_rootSavingContext]];
}

+ (NSManagedObjectContext *) MR_contextWithParent:(NSManagedObjectContext *)parentContext
{
    NSManagedObjectContext *context = [self MR_newPrivateQueueContext];
    [context setParentContext:parentContext];
    [context MR_obtainPermanentIDsBeforeSaving];
    return context;
}

- (void) MR_obtainPermanentIDsBeforeSaving
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(MR_contextWillSave:)
                                                     name:NSManagedObjectContextWillSaveNotification
                                                   object:self];
}
+ (NSManagedObjectContext *) MR_newPrivateQueueContext
{
    NSManagedObjectContext *context = [[self alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    MRLogInfo(@"Created new private queue context: %@", context);
    return context;
}

@end

@implementation MyClass

    - (NSManagedObjectContext *) getPrivateContext
    {
        if (self.privateContext == nil)
        {
            self.privateContext = [NSManagedObjectContext MR_context];
        }
        return self.privateContext;
    }

    - (SyncRequestEntity *) getSyncRequest
    {
        SyncRequestEntity *syncRequest = [SyncRequestEntity MR_findFirstByAttribute:@"key" withValue:self.itemKey inContext:[self getPrivateContext]];

        // Checking if the entity was sync previously with the same filters.
        if (syncRequest == nil)
        {
            syncRequest = [SyncRequestEntity MR_createEntityInContext:    [self getPrivateContext]];
        }

        return syncRequest;
    }
@end

@implementation NSManagedObject (MagicalRecord)
+ (id) MR_createEntityInContext:(NSManagedObjectContext *)context
{
    if ([self respondsToSelector:@selector(insertInManagedObjectContext:)] && context != nil)
    {
        id entity = [self performSelector:@selector(insertInManagedObjectContext:) withObject:context];
        return entity;
    }
    else
    {
        NSEntityDescription *entity = nil;
        if (context == nil)
        {
            entity = [self MR_entityDescription];
        }
        else
        {
            entity  = [self MR_entityDescriptionInContext:context];
        }

        if (entity == nil)
        {
            return nil;
        }

        return [[self alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    }
}
@end

The privateContext is a local variable for each operation so I have private contexts for each operation in order to not interrupt the main one. The point is that I create one private context for each thread and I'm just trying to create a new NSManagedObject instance using this context and Xcode says that I'm violating the multithreading core data rules. Does anyone have any clue on what's happening?

A: We have the same issue when developing our own app.
When you try to perform a write operation in a thread different to the context one, it crash sometimes.
Our solution was to make a private manager on the AppDelegate.m file. Just add this code:
- (NSManagedObjectContext *)getPrivateManagedObjectContext
{
    if (self.managedObjectContext != nil) {
        return self.managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self getPersistentStoreCoordinator];
    if (coordinator != nil) {
        self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [self.managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return self.managedObjectContext;
}

Then when you need to perform any operation, you should use this method that ensures the block is running on the same thread of the context:
[self.managedObjectContext performBlock:^{...}];
[self.managedObjectContext performBlockAndWait:^{...}];


text:
Q: Can Gases conduct Electricity? Liquid electrolytes ionize and hence a current can pass through them. So if a gas can ionize, can it conduct electricity too? If so, what are a few such gases?

A: Gases do conduct electricity, as all materials do. However, they conduct electricity so poorly that we consider them insulators.
"Electricity" requires the movement of electrons. In a gas, these electrons are too dispersed to provided any measurable current.
The "lightning" example is slightly different. This refers to capacitative discharge. When the two sides of a capacitor (i.e. the ground and the clouds) store too much charge, that charge eventually jumps the dielectric (i.e. the stuff in between the ground and clouds). We still don't say that the dielectric "conducts" electricity, although it obviously does. The best insulators in the world could not stop a discharge of sufficient strength. The defining quality of a conductor is that it conducts electricity "more easily" than most substances. There is no perfect conductor or perfect insulator.
In short, gases can conduct electricity, but they are considered insulators for the most part.

A: At atmospheric pressure, air and other gases are poor conductors (Insulators) of electricity. Because, they don't have any free electrons to carry current. But, once the free electrons are produced in gas by ionization (they become plasmas), electric discharge occurs.
This could be done in many ways such as by applying a large potential difference across a gas column at very low pressure, or by allowing high frequency EM-waves such as the X-Rays through the gas. This question is not proper to ask. Indeed, gases become plasmas once they're ionized!
All dielectrics have a certain value of breakdown potential. In most of them like air, ceramics, etc. (including semiconductors like Silicon), this potential provides sufficient energy to ionize a few atoms. The free electrons formed as a result of this ionization are energized enough to bump the neighborhood atoms, break some covalent bonds and produce more free electrons.
These free electrons are then accelerated by the applied electric field and they collide and ionize the other atoms to produce more free electrons (multiplication by collision). Now, there are large number of free electrons available for current flow. Thus, an electric arc is produced!
However, this isn't applicable for all gases. As @mikuszefski has mentioned, there are a few other cases such as the noble gases which are mono-atomic (and are used in most of the discharge tubes), whose breakdown potentials are only meant to ionize them!

A: Carbon is the only gas, when solidified, that can conduct electricity. This is of the form Graphite, when it only has 3 bonds between the atoms. This leaves electrons to flow through the network structure.

A: Gas on its own
cannnot conduct
electricity but it
can be made to
conductor
electricity by
subjecting it under
LOW PRESSURE and
HIGH VOLTAGE.

Gas can conduct electricity under two condition using a discharge tube; (1)low pressure (about ~0.01mmHg) (2)high voltage (>1000v)


text:
Q: ES6 modules - best approach for creating an immutable service I'm using the following approach for creating a singleton-like service in my application:
myService.js:
let myService = {};

myService.doSomething = function() {
    //doing something
};

export {myService};

usage in other module:
import {myService} from 'myService.js'

myService.doSomething();

export {myService};

Generally this works fine, but the problem is that it's possible to modify the service in a module that is importing it:
import {myService} from 'myService.js'

myService.doSomething = function() {
    //do something different
};

export {myService};

This is not desireable for a singleton-service, it should be immutable.
How can immutability can be achieved? Does anybody have a completely different/better approach for creating immutable services as ES6 modules?

A: Hi we can achieve by using Object.freeze method. i have created one demo https://stackblitz.com/edit/react-wfhq4c kindly check mozilla dev website.
you can also refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

A: You can create a private function in myService. Also create a default function pub in myservice and call doSomething from this default function.
Then in the other file when you will call myService it will give access to only default function
let myService = {}
myService.doSomething = function() {
  console.log('Test');
  return 'myservice doSomething executed'
};
export function pub() {
  return myService.doSomething()
}

import * as test from './myService'
console.log(test.pub());

Please check console of this DEMO


text:
Q: Download Xcode 4.2 documentation for offline install I've read a few posts on how to install the missing documentation on Xcode 4.2 by going into the documents manager and downloading it directly. Other questions suggest me to look into the rss feed, but I get only the Mac OS Lion Core reference, I want the iOS reference as well.
That's very nice, but I can't connect to the internet from the Mac where I work, no need to enter in details, nor can install Mac OS on the PC where I connect, so my question is pretty simple:
Where can I obtain the required files to install them into Xcode and how do I install them?
Any links or instructions would be useful.
Thanks in advance
EDIT To download the Xcode documentation I just need the actual URL where the files are located, can't download them using Xcode because the PC I have with internet has Windows.
EDIT Although the @Saurabh's answer didn't gave a 100% to what I wanted, if you check the image well, there is a field saying feed and there is where everybody having this issue should look.
EDIT: In order to complete the question and make life easier for those looking for the actual files, these are the links

*

*Apple iOS Documentation V 9.0

*Apple iOS Documentation V 8.3

*Apple iOS Documentation V 8.1

*Apple iOS Documentation V 8.0

*Apple iOS Documentation V 7.1

*Apple iOS Documentation V 7.0

*Apple iOS Documentation V 6.1

*Apple iOS Documentation V 6.0

*Apple iOS Documentation V 5.1

*Apple iOS Documentation V 5.0

*Apple iOS Documentation V 4.2 (Xcode 4)

*Apple iOS Documentation V 4.2 (Xcode < 4?) No so sure on this one

*Apple iOS Documentation V 4.3

*Apple iOS Documentation V 4.3 (Another?)

*Apple iOS Documentation V 4.1

*Apple iOS Documentation V 4.1 (Xcode 4)

*Apple iOS Documentation V 4.0

*Apple iOS Documentation V 3.1

*Apple iOS Documentation V 2.2
Finally, as stated in this question yu can find the Mac OS Lion reference here:
Mac OS Lion Core Reference

A: Here you are the steps:
Download the documentation from Xcode from any machine.
Go the download installation (See Figure Below)
Copy the "documentation set" files (it is actually packages with a lot of file so it is recommend to zip them).
Move them to the same location where you installed Xcode on the other machines
Restart Xcode.
Done.
How to download documentation file online -
If you are connected to Internet you can download the documentation file. Go to Xcode -> Preferences -> Downloads (this is the screen I attached). Here you will find iOS 4.3 Library in listing and and button on right "Install". Just Click the button "Install" for the items you want to download.
After documentation download you can see its path and copy the files to other systems.
Hope it clears your question completely.. if not please post in comments.

Edited
As I am still getting upvotes on this answer I thought its better to post some links to download new SDK's documentations.
iOS SDK 5.1 - https://developer.apple.com/rss/com.apple.adc.documentation.AppleiPhone5_1.atom
iOS SDK 6.0 - https://developer.apple.com/rss/com.apple.adc.documentation.AppleiPhone6.0.atom
Mac OS X 10.6 core library - https://developer.apple.com/rss/com.apple.adc.documentation.AppleSnowLeopard.atom
Mac OSX 10.8 - https://developer.apple.com/rss/com.apple.adc.documentation.AppleOSX10_8.atom
Xcode 4.0+ developer library - https://developer.apple.com/rss/com.apple.adc.documentation.AppleXcode4_0.atom


text:
Q: How does phpmyadmin open a small window both in firefox and IE? When you edit a datetime column via its datepickup,a window pops up instead of a new tab.
How to do it?
I tried window.open(..) but it just opens a new tab.

A: I don't know phpmyadmin in particular, but could it be:
window.showModalDialog(...);

showModalDialog("URL"[, arguments[, "features"]])
http://javascript.gakaa.com/window-showmodaldialog-4-0-5-.aspx

A: You'll need to provide more than just the url: https://developer.mozilla.org/En/DOM/Window.open - take a look at the windowFeatures parameter. They happen to be using the following function:
function openCalendar(params, form, field, type) {
    window.open("./calendar.php?" + params, "calendar", "width=400,height=200,status=yes");
    dateField = eval("document." + form + "." + field);
    dateType = type;
}

A: It calls a openCalendar function which looks like this:
function openCalendar(params, form, field, type, fieldNull) {
    window.open("./calendar.php?" + params, "calendar", "width=400,height=200,status=yes");
    dateField = eval("document." + form + "." + field);
    dateType = type;
    if (fieldNull != '') {
        dateFieldNull = eval("document." + form + "." + fieldNull);
    }
}

Basically just setting the width and height attributes (btw, if it's opening in a new tab, it's your browser that opens it that way, not the javascript).


text:
Q: How can I find out which button was clicked? I've got my buttons working right, and I'm a listener to each button like this:
for(int i = 0; i <= 25; ++i) {
    buttons[i] = new Button(Character.toString(letters[i]));
    buttons[i].addActionListener(actionListener);
    panel1.add(buttons[i]);
}

Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?
ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getSource());
    }
};

I need some way to find the button in the array.

A: In order to get label, try this.
ActionListener actionListener = new ActionListener()
{
      public void actionPerformed(ActionEvent actionEvent) {
            JButton button = (JButton)actionEvent.getSource();
            String label = button.getLabel(); //Deprecated

            String label2 = button.getText();
     }
};

A: ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).

A: try this
ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getActionCommand());
    }
};

A: private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    l1.setText("");//name of level what you want

    t1.setText(null);//text field what you want

    t2.setText(null);//text field what you want
}


text:
Q: Get user root directory from windows service I have a Windows Service written in C#.  I need to add a file to each user directory.  How can I find the path to start in?  I realize this is really dumb but this is what I'm currently doing:
  if (Directory.Exists("C:\\Users"))
  {
    path = "C:\\Users";
  }
  else if (Directory.Exists("C:\\Documents and Settings"))
  {
    path = "C:\\Documents and Settings";
  }

I've looked at the special folders: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
None of them seem to return what I need.  For example, ApplicationData is returning the path to the System32 directory.  I presume this is because it is running as a windows service.  The code I'm currently using works for the few tests I've done.  It just seems like there should be a more intelligent (error proof) way of getting this path.
Another thought...maybe there is a registry key that will give me what I'm looking for?  Hmmm

A: I found this under Win7 registry.   XP looks to have the same registry keys, but the values have "All Users" profile within it.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders]
"Common Desktop"="C:\\Users\\Public\\Desktop"
"Common Start Menu"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu"
"CommonVideo"="C:\\Users\\Public\\Videos"
"CommonPictures"="C:\\Users\\Public\\Pictures"
"Common Programs"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"
"CommonMusic"="C:\\Users\\Public\\Music"
"Common Administrative Tools"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools"
"Common Startup"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
"Common Documents"="C:\\Users\\Public\\Documents"
"OEM Links"="C:\\ProgramData\\OEM Links"
"Common Templates"="C:\\ProgramData\\Microsoft\\Windows\\Templates"
"Common AppData"="C:\\ProgramData"

A: I might not have understood you completely but I think you just need to get the location where you are running from and then get the Root off of it.
Path.GetPathRoot(Assembly.GetEntryAssembly().Location);

Update
The special folders is what you need to research.  There isn't a simple go-here do-this because your question wasn't detailed enough.  If the service is running as a specific user or as system then makes a difference.  Also, you didn't specify how it was being used so that would matter.  Is it a place to hold config files vs temp location to write files vs should anyone else want to get at the folder?  All these things matter so if you add some additional details then I will update my answer.

A: How about HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList and key ProfilesDirectory? It points to %SystemDrive%\Users on my PC. Just not sure which versions of Windows have this key (7 & 10 do).


text:
Q: How can I create two different notifications for laravel? (like orderquote and booking) I am trying to create two notifications using Laravel. First when the client fills out the orderquote form, the admin user at the backend gets the notification on their dashboard showing a notification of a new quote received, and if the client proceed further towards this booking and confirm it, the admin user again gets the notifications of a new bookings. But I want this booking to show separately. I have New quote icon and i also have new booking icon separate. so I want it  show the notifications accordingly. So far, I can only do it one notification. I want something similar to this website if we see on top right corner on the navigation bar. We all have separate notifications for various things. How can I do that?
Code for the Quote Notifications:

App/Http/Controller/newQuoteController.php

$user = user::all();
\Notification::send($user,new NotifyUser($newquote));

then in my App/notifications/NotifyUser.php

public $newquote;

public function __construct(NewQuote $newquote)
{
    $this->newquote=$newquote;
}

public function via($notifiable)
{
    return ['database'];
}

public function toDatabase($notifiable)
{
    return [
       'data' => $this->newquote->id,
    ];
}

Now for the booking:

App/Http/Controller/confirmedBookingController.php

  $user = user::all();
  \Notification::send($user,new BookingNotification($bookings));

then in my App/notifications/BookingNotification.php

public $bookings;

public function __construct(Bookings $bookings)
{
    $this->bookings=$bookings;
}

public function via($notifiable)
{
    return ['database'];
}

public function toDatabase($notifiable)
{
  return [

     'data' => $this->bookings->id,
  ];
}


text:
Q: How to exclude folders from a directory using power shell script I have directory which contains few folders, I wanted to exclude folder names which contains a string. I tried with following command using wild card option (in the exclude variable) which is not working in exclude section.
$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{$_.Name -notin $excludes} | Copy-Item -Destination $dirName -Recurse -Force

Example:- Let say I have folders in monitors directory like SQLMonitor, CSTK123_SQLMonitor, TEST_SQLMonitor , SQLMonitor_abc ... now I wanted to exclude these folders using wildcards
How to achieve this in PowerShell.

A: $dirName = "C:\Users\sj01856\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\sj01856\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{$_.Name -notmatch ($excludes -join "|")} | Copy-Item -Destination $dirName -Recurse -Force

You need to match against the array and not take the asterisks literally.

A: You should be able to do all of this within the Get-ChildItem call, with an -Excludes parameter, which takes an array of patterns to exclude:
$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors" -Directory -Exclude $excludes |
  Copy-Item -Destination $dirName -Recurse -Force


text:
Q: Is a local constant string in global memory Is I define a global pointer(char*). Then give an address of a constant string. Is this address  will be freeed. for example:
static char *str;
const char * test()
{
    str = "hello world";
    return str;
}

Q1: Now is it safe to use the content of the address get by test anywhere.
Q2: If the test is in a DLL. Is it safe to use out side by other program
Q3: If it's safe . When I reassign another const string  to variable str. Will the old const string be freeed

A: If only from code perspective, this is safe. But you should make sure in test(), you can only assign a string const to str. If you do like following:
const char *test() {
  char somestr[somesize];
  str = somestr;
  return str;
}

That's still not safe.

A: If you do the following, you can use the result of foo() anywhere. You should not modify or free it however. It is irrelevant if this code is part of a DLL or a Library.
const char * foo() {
    return "hello";
}

// This is identical.
const char * foo() {
    const char *x = "hello";
    return x;
}

If you want to be able to modify, you could do something like this. Note that every call to foo() will be referring to the same piece of memory because x is static. Note that here, you can modify x, but you still should not free it.
char * foo() {
    static char x[] = "hello";
    return x;
}

If you wanted to be able to free the result of foo(), you must allocate the space with malloc().

A: The assignment to str isn't even necessary. Even without it, it would be safe to return the address of a string literal from a function and to subsequently use the string anywhere.

A: It's safe if you assign a string literal to the pointer, but if you're going to do that it seems like it would be best to leave the function out of the picture entirely:
static char str[] = "hello world";

Then you could just use str like a static char * since arrays just decay to pointers.


text:
Q: AngularJS: Migrate Expression to Javascript (Coffeescript) I have an expression I would like to migrate to javascript to keep an object's value available in $scope:

LTV

{{(total_financing ? total_financing : financing)/ property_value}}

But migrating the same expression to javascript will always result in financing and not total_financing (Coffeescript):
$scope.ltv = (if $scope.total_financing then $scope.total_financing else $scope.financing) / $scope.property_value

I have been reading the documentation on angular expressions to no avail.  Can anyone suggest a better method of migrating expressions to javascript?

A: $scope.ltv = ($scope.total_financing ? $scope.total_financing : $scope.financing) / $scope.property_value;

Is this what you want?

A: Your javascript code is completely wrong. Firstly, javascript doesn't have an if-then construct like visual basic or some other languages, the syntax goes rather like this:
if(...) {
   doSomething
} else {
   do someThingElse
}

The other mistake you make is that you have to assign an expression to a variable and not a statement which the if-else construct is. You may as Nikhil suggested use a ternary operator or, if you aren't comfortable with ternary operators, a function like this:
$scope.ltv = function() {
   if($scope.total_financing) {
      return $scope.total_financing;
   }
   return $scope.financing;
}

and then use a function call in the html binding like {{ltv()}}


text:
Q: Dollar sign to Peso Sign This code:
string currentPrice = String.Format("{0:c}", ((TblProduct)e.ListItem).Price);

shows the price in dollars, ie $320.00. But I want to show a peso sign instead of a dollar sign. What system.string should I use? {?:?}

A: You need to specify an additional argument (a format provider) in order to acquire the appropriate currency symbol and formatting.  For example, to format for the Philippines:
var currentPrice = String.Format(CultureInfo.GetCultureInfo("en-PH"),
                                 "{0:c}",
                                 ((TblProduct)e.ListItem).Price);

If a format provider is not specified, CultureInfo.CurrentCulture is used.

A: Try this one works for me.
im using a Unicode character escape sequence which is "\u" then followed by its hexidecimal unicode value.
Unicode Character 'PESO SIGN' (U+20B1)
string currentPrice = String.Format("\u20B1{0}", ((TblProduct)e.ListItem).Price);


text:
Q: What is the most optimal solution (time wise) for multiple if statements The examples below are from my chess game but the question is more general for runtime optimizing if-statements in Python. What type of code will run faster, and is there a huge difference? Bare in mind that in this case I will calculated this inside a minimax algorithm (thousands of times). Case 3 if of course nicer, but is it faster to run?
Another question would be if there is a difference in the order of which I put these values in? In this case the pawn option will come up the most times, is it then better to have that one first in the if-statements/dict?
# Case 1:

if piece_type == 'K':
    value = 20000
elif piece_type == 'Q':
    value = 900
elif piece_type == 'B':
    value = 330
elif piece_type == 'N':
    value = 320
elif piece_type == 'R':
    value = 500
elif piece_type == 'p':
    value = 100

return value

# Case 2:

if piece_type == 'K':
    return 20000
elif piece_type == 'Q':
    return 900
elif piece_type == 'B':
    return 330
elif piece_type == 'N':
    return 320
elif piece_type == 'R':
    return 500
elif piece_type == 'p':
    return 100

# Case 3:

piece_values = {'K': 20000, 'Q': 900, 'B': 330, 'N': 320, 'R': 500, 'p': 100}
return piece_values.get('K')

A: import timeit
piece_type = 'p'
def case1():
    if piece_type == 'K':
        value = 20000
    elif piece_type == 'Q':
        value = 900
    elif piece_type == 'B':
        value = 330
    elif piece_type == 'N':
        value = 320
    elif piece_type == 'R':
        value = 500
    elif piece_type == 'p':
        value = 100
    return value

def case2():
    if piece_type == 'K':
        return 20000
    elif piece_type == 'Q':
        return 900
    elif piece_type == 'B':
        return 330
    elif piece_type == 'N':
        return 320
    elif piece_type == 'R':
        return 500
    elif piece_type == 'p':
        return 100

piece_values = {'K': 20000, 'Q': 900, 'B': 330, 'N': 320, 'R': 500, 'p': 100}
def case3():
    return piece_values.get(piece_type)

N = 1000
r1 = 0
r2 = 0
r3 = 0
for i in range(N):
    r1 += timeit.timeit("case1()", setup="from __main__ import case1", number=100000)
    r2 += timeit.timeit("case2()", setup="from __main__ import case2", number=100000)
    r3 += timeit.timeit("case3()", setup="from __main__ import case3", number=100000)
print(r1/N)
print(r2/N)
print(r3/N)

Results
For piece_type = 'p'
0.043659273699999786
0.042489134299999745
0.025282950800000023

For peice_type = 'K'
0.017085672599999883
0.015899844999999937
0.02493290909999991

As if we see the results, accessing elements of dictionary doesn't matter where the element is located.
Accessing elements down the if-else ladder cost more time compared to the elements at the top of ladder.
So if the conditionals are less then if-else is better, if there are large number of conditionals then dictionary is better as dictionary is always O(1).


text:
Q: addeventlistener not working (function() {
var divs = document.getElementsByClassName('data');
var myFunction = function()
{
    alert("hello");
    var el = this;
    var st = window.getComputedStyle(el, null);
    var tr = st.getPropertyValue("transform") ||
     st.getPropertyValue("-moz-transform") ||
     st.getPropertyValue("-ms-transform") ||
     st.getPropertyValue("-o-transform") ||
     st.getPropertyValue("transform") ||
     "Either no transform set, or browser doesn't do getComputedStyle";
     console.log(tr);
}

for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('mouseover', myFunction, true);
}
})();

data1

data2

data3

data4

I am using pure javascript to add event listener to the div .
The add event listener not working
Some guys said to me to add the event listener at window.load but i am getting my dom objects here in this javascript.
Any help?

A: There is no error in your code. you just need to put your code below the DOM.

Best place to add your script is before the end of body tag. Use external script files instead of internal of script.

For example only I am using script inside html. You should use script as external file which is best practice.
Working Code -
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

data1

data2

data3

data4

DOMContentLoaded event will execute your code after DOM is loaded and parsed. so it will not give error.

A: Your code works. You must run your script after DOM is loaded, or you must write
DOMContentLoaded eventListener:
document.addEventListener("DOMContentLoaded", function(event) {
    (function() {
        var divs = document.getElementsByClassName('data');
        var myFunction = function()
        {
            //.... Your code
        }

        for (var i = 0; i < divs.length; i++) {
            divs[i].addEventListener('mouseover', myFunction, true);
        }
    })();
});


text:
Q: how to add new filed to opencart I want to add three more filed to cart page .()
<input name="pr_name">
<input name="pr_phone >
<input name="pr_add">

can any one help me to add these files to cart .

A: you will need to modify the following:
the model for the cart /catalog/model/checkout
the controller for the cart /catalog/controller/checkout
the view for the cart whatever theme you are using
finally you will need to do the same for the admin panel and depending on where you would like to see them for example you might want to view them in the invoice you will need to change the model / controller that correspond to that. unfortunately its not like a plug and play thing.


text:
Q: Proper use of assert() in c++ My professor gave us a exercise where we have to decide when it's appropriate to use the assert(check_inv()) that keeps the objected in a state well-formed respecting the class invariant.
I'm not sure when it's necessary to check the class invariant, i know that before returning a object from his constructor is a good practice checking the class invariant, but in case of other functions i'm not completely sure.
this is the exam text:
class C
{

    public:

        bool check_inv() const
        {
            // Implementation of class invariant code
        }

        C(int a, int b)
        {
            // Implementation of class constructor.
        }
        void foo(C& y)
        {
            // Implementation of method foo.
        }
        void bar(const C& y)
        {
             // Implementation of method bar.
        }
        void ying(const C& y)
        {
            // Implementation of method ying.
        }
        void yang(const C& y) const
         {
             // Implementation of method yang.
         }
        ~C()
         {
             // Implementation of class destructor.
         }
        static void zen(int i, double d)
        {
            //Implementation of method zen.
        }
// ... Some other code ...
}; // class C

Where should i check the class invariant?
EDIT: this isn't supposed to be homework question at all, i just need to understand the functioning of assertions through an example.

A: Think about the life cycle of an object: it gets created by a constructor, it gets examined by const member functions, it gets modified by non-const member functions, and eventually it gets destroyed by its destructor. So as far as the class invariant goes, it must be satisfied at the end of the constructor and at the end of any non-const member functions. That's sufficient to ensure that the invariant is satisfied everywhere. Checking it on entry into a function doesn't make the class robust; it might detect overwrites from outside, but that's not part of the abstraction that the class presents. So: check the invariant at the end of each constructor and at the end of each non-const member function.

A: Possible you should checking the class invariant in all other public class member functions except destructor function.And you should check twice, first after enter the function, then before exit the function, while between this two process, you can do sth to invariant.