Q:

Is there any performance difference between x+=y and x=x+y (x and y are both simple types) in C#?

In C/C++,

The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as
expression1 += expression2
can be understood as
expression1 = expression1 + expression2
However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.

(Quoted from Microsoft Docs)

For example:

For i+=2;, i would be modified directly without any new objects being created.
For i=i+2;, a copy of i would be created at first. The copied one would be modified and then be assigned back to i.

        i_copied = i;
        i_copied += 2;
        i = i_copied;

Without any optimizations from compiler, the second method will construct a useless instance, which degrades the performance.

In C#, operators like += are not permitted to be overloaded. And all simple types like int or double are declared as readonly struct (Does that mean all of structs in C# are immutable in truth?).
I wonder in C#, is there a certain expression to force object be modified (at least for simple types) directly, without any useless instances being created.
And also, is it possible the C#-compiler optimizes the expression x=x+y to x+=y as expected, if there's no side-effect from constructors and deconstructors.

A:

C#
When you compile C# into a .NET assembly, the code is in MSIL (Microsoft Intermediate Language). This allows the code to be portable. The .NET Runtime will compile it JIT for execution.
MSIL is an stack language. It does not know details of the target hardware (such as how many registers does the CPU have). There is only one way to write that addition:
    ldloc.0
    ldloc.1
    add
    stloc.0

Load the first local in the stack, load the second, add※ them, set the first local from the stack.
※: add pops two elements from the stack, adds them, and pushes the result back into the stack.
Thus, both x=x+y and x+=y will yield the same code.

Of course, there are optimizations that happens after. The JIT compiler will convert that into actual machine code.
This is what I see with SharpLab:
mov ecx, [ebp-4]
add ecx, [ebp-8]
mov [ebp-4], ecx

So, we copy [ebp-4] into ecx, add [ebp-8] to it, and then copy ecx back to [ebp-4].
So... Is the register ecx a useless instance?

Well, that is SharpLab, and that is JIT. A different compiler could in theory convert the code into something different on a different platform.
You can compile .NET code AOT to a native image, which will be more aggressive with optimizations. Although, I do not see how you are going to improve upon a simple addition. Oh, I know, it might see that you do not use this value and remove it, or may see that you are always adding the same values and replace it with a constant.
It might be worth noting that modern .NET JIT is able to continue to optimize the code during execution (it will quickly make a poorly optimized native version of the code, and later - once it is ready - replace it with a better version). This decision comes from the fact that on a JIT runtime, the performance depends on both the time it takes to create the native code and the time that native code takes to run.

C++
Let us see what C++ does. This is what I see for both x = x + y and x += y using godbolt (default settings※):
    mov     eax, DWORD PTR [rbp-8]
    add     DWORD PTR [rbp-4], eax
    mov     eax, DWORD PTR [rbp-4]

The instructions mov, add, mov match the ones we got from SharpLab, with a different choice of registers.
※: x86-64 gcc 9.3 with -g -o /tmp/compiler-explorer-compiler2020424-22672-17cap6k.bjoj/output.s -masm=intel -S -fdiagnostics-color=always /tmp/compiler-explorer-compiler2020424-22672-17cap6k.bjoj/example.cpp
Adding the compiler option -O made the code go away. Which makes sense because I was not using it.

A:

To answer such questions you can use SharpLab.
As you can see both the generated IL and the JITted code are the same in both cases.


Q:

Length of the first line in an UTF-8 file with BOM

Good afternoon. Suppose I have an utf-8 file with a single letter, say "f" (no \n and spaces) and I try to get a sequence of line lengths.
(with-open [rdr (reader "test.txt")]
  (doall (map #(.length %) (line-seq rdr))))

And I get
=> (2)

Why? Is there any elegant way to get the right length of the first string?

A:

The problem of BOM in Java is covered in Reading UTF-8 - BOM marker. It seems that it can be abstracted away using BOMInputStream from Apache's Commons or it has to be removed manually, i.e.
(defn debomify
  [^String line]
  (let [bom "\uFEFF"]
    (if (.startsWith line bom)
      (.substring line 1)
      line)))

(doall (map #(.length %) (.split (debomify (slurp "test.txt")) "\n")))

If you want to read a file lazily using line-seq, for instance because it's huge, you have to treat the first line using debomify. Remaining ones can be read normally. Hence:
(defn debommed-line-seq
  [^java.io.BufferedReader rdr]
  (when-let [line (.readLine rdr)]
    (cons (debomify line) (lazy-seq (line-seq rdr)))))


Q:

Best way to retrieve all the table records in Apache Gora 0.5

I know about
 query.setStartKey(startKey);
 query.setEndKey(endKey);

Isn't there something similar to
 SELECT * FROM TABLE;

in Apache Gora while creating queries, that would return me all the result set.
EDIT*
I executed the program without setting anything. But still, the result set is null.
 Query<String, Obj> query = store.newQuery();
 Result<String, Obj> result= query.execute();

A:

If you don't set the start nor the end key, it will retrieve all the table like the select you talk about -at least with HBase-.


Q:

Ajax pass value to other php file and use the value in if statement

Asset

then ajax
$.ajax({
type: 'POST',
url: '__popup-window_ajax.php',
data: { 'AccountType' : $('#account_type').text() },
});

then php
print_r($_POST['AccountType']);

see word Asset exactly as here Asset
but
if (($_POST['AccountType']) == 'Asset') {
echo 'Yes, Asset';
}

echo nothing
What is wrong?
For example tried
$account_type = 'Asset';
if ( $account_type == 'Asset' ) {
echo 'Yes, Asset';
}

and works... Does ajax changes values somehow?
Solution
Thanks to @Ankit Pokhrel. My stupid negligence. After word Asset there was blank space. trim helped.

A:

Try:
if (isset($_POST['AccountType']) && stristr($_POST['AccountType'],'Asset')){
    //extra content is sent within AccountType variable, check your output sourcecode.
}

// or

if (isset($_POST['AccountType']) && trim($_POST['AccountType']) =='Asset'){
//you've got whitespaces in AccountType variable
}

A:

This can only be a whitespace issue. It has nothing to do with the treatment of $_POST or whether or not your data property names are encased in quotes. Trim the value on either side of the transaction.
JS:
data: {AccountType: $('#account_type').text().replace(/^\s|\s$/g, '')},

PHP
trim($_POST['AccountType'])


Q:

How do I load a kernel module later in the boot sequence?

I've been experimenting with the g_mass_storage kernel module.
I first tried loading it by putting it in /etc/modules and the options in /etc/modprobe.d/file.conf
This worked, but when I connected the device to a computer the mass file storage was read only - not what I was looking for.
I reasoned that this was because when the module loads, the root filesystem is mounted as read-only - not read-write.
This is an issue, because the kernel driver tries to get a read-write file handle for its backing storage, and if it can't negotiate this rw handle, it falls back to read-only.
The only solution I can think of is moving the loading of the kernel module later in the boot sequence.
I moved the module initialisation to /etc/rc.local using modprobe, and this worked with both reading & writing - but it feels like a bit of a hack to load the module in there.
Is there a recommended place to load kernel modules that need rw access to a file?

A:

A [probably not perfect] solution to this has been to hook onto the "systemd-remount-fs.service" systemd service, which is the remounting of the filesystem to read-write.
This means the module will be loaded as early as possible, whilst still being loaded after the filesystem becomes readwrite.
My sample systemd config file is as follows:
[Unit]
Description=Starts kernel modules for USB OTG
After=systemd-remount-fs.service
DefaultDependencies=false

[Service]
Type=simple
ExecStart=/home/pi/programs/startmod.sh
WorkingDirectory=/home/pi/programs/

[Install]
WantedBy=local-fs.target

This works, if a little hackily.


Q:

Doctrine DQL Invalid parameter number: number of bound variables does not match number of tokens

I'm getting the error Invalid parameter number: number of bound variables does not match number of tokens on this query.
I really don't see the problem, any ideas?
public function getByPartial($q, Company $company)
{

    $query = $this->createQueryBuilder('u')
        ->join('u.company',':company')
        ->where('u.firstName LIKE :q')
        ->orWhere('u.lastName LIKE :q')
        ->setParameters(array('company' => $company, 'q' => '%'.$q.'%'))
        ->getQuery();
    return $query->getResult();

}

A:

company can't be a parameter, you just have to specify an alias such as :
public function getByPartial($q, Company $company)
{
    $query = $this->createQueryBuilder('u')
        ->addSelect('c')
        ->join('u.company','c')
        ->where('u.firstName LIKE :q OR u.lastName LIKE :q')
        ->andWhere('c.id = :companyId')
        ->setParameters(array('companyId' => $company->getId(), 'q' => '%'.$q.'%'))
        ->getQuery();
    return $query->getResult();
}


Q:

How to specify a name to which object will be serialized by WebApi?

My web api is returning a set of objects which are differ from the Domain object. Forexample, I my domain has an Employee class but I don't want to expose all the members of the Employee class in my api so I created another class called EmployeeApiModel.
Now my WebApi is returning a List of EmployeeApiModel but I want to be able to specify the name to which it should serialize to. That is instead of <EmployeeApiModel> tag in the xml, I want to get <Employee> but without changing the fact that the underlying class which is being serialized is EmployeeApiModel.
How can I achieve this?

A:

Technically, Web Api support both json and xml based on content negotiation mechanism, Json is the default format, if you want to receive xml, just put on header:

Accept: application/xml

To understand more content negotiation, access this
Since you want your api support both json and xml, you should use DataContract and DataMember Attribute for serialization for your model: EmployeeApiModel, something like:
[DataContract(Name = "Employee")]
public class EmployeeApiModel
{
    [DataMember(Name = "Name2")]
    public string Name { get; set; }

    [DataMember]
    public string Email { get; set; }
}

See more on this blog-post


Q:

Why absolute units in CSS are not shown really absolute in different screens?

The so-called absolute units (cm, mm, in, pt and pc) mean the same in
  CSS as everywhere else, but only if your output device has a high
  enough resolution.
source: W3C

when I put the preceding code in my project I expect to see 1cm everywhere...
.myColumn{
   width: 1cm;
}

W3C says for low-resolution screens, case would not be the same.
Why?
Why cannot they produce 1cm correctly?
In cell-phones, and tablets and... the only screen unit is pixel.

A:

CSS units don't necessarily equate to exact dimensions. In the end, every CSS measurement displayed on a screen is eventually calculated in pixels.
CSS assumes screens will have 96 dpi, so using in, pt, and pc is usually safe, although different monitor resolutions, or user-defined zooming may affect your results.
Metric units are a different story though, as there is no exact calculation to pixels, so the numbers are rounded by the browser to deliver a result that will be close to the specified measurement. This is one of the reasons that the W3C only recommends px, %, or em units for screen targeted layouts.


Q:

Can node presented ejs files use offline bootstrap?

I'm new to node and full stack development and hope I ask this correctly and not carelessly or offensively for your particular level of understanding.
My dev environment is Internet connected, production will not be and I want to use bootstrap.css with node. Apache/httpd is not an option in production.
Testing bootstrap locally has been challenging, the correct directory for the css file is believed correct.
The main directory on CENTOS 7 is myapp, contains app0.js, the node_modules with espress and body-parser and all dependencies, and the views directory which contains grid.ejs.

myapp/
    app0.js
    node_modules
    views/
        grid.ejs
    public/
        bootstrap.css

Here is grid.html (which works on apache):
<!DOCTYPE html>

  <title>Bootstrap Grid Test</title>
  <link rel="stylesheet" type="text/css" href="bootstrap.css">

2 columns

7 columns

3 columns

And here is what apache shows for grid.html:
https://imgur.com/VanVZJn "bootstrap with httpd"
However app0.js does not!
So bootstrap.css works (1) when referenced on internet - which I cannot use in production (2) from httpd in my dev environment via http code
but not from an ejs file.
Note: I am able to reach bootstrap from node, because there were 404 errors when it was not reachable showing from the terminal where node was launched. After at least 12 hours trying to understand this, I'm stumped. Sadly with a short timeline to have a solution, I turn to you fine readers!
App0.js
//setup
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser')

app.set('view engine','ejs');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get("/grid", function(req, res, next){
    res.render("grid")
});

app.listen(3000,function(){
    console.log("serving test demo on port 3000")
});

views/grid.ejs
<!DOCTYPE html>

  <title>Bootstrap Grid System</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="public/bootstrap.css">

2

7

3

shown here:
https://imgur.com/ZLOgZKT "bootstrap not working"

A:

You have to define on your app0.js file the public path from where you are going to serve static files. Try the following app0.js file requiring the path module and using express.static after bodyParser.json():
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    path = require('path')

app.set('view engine','ejs');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));

app.get("/grid", function(req, res, next){
    res.render("grid")
});

app.listen(3000,function(){
    console.log("serving test demo on port 3000")
});

And your grid.ejs file link the bootstrap file this way:
<link rel="stylesheet" type="text/css" href="/bootstrap.css">


Q:

Calculating radius using tangent point and center point

I got 2 coordinates which are given to me, they can be random. One is a tangent point coordinate and the other is center point coordinate.
I would like to get the radius of the circle using these 2 points. How would I do that? Is there a formula or something I have forgotten about?

A:

Given the centre $(x_1,y_1)$ and a point on the circumference of the circle $(x_2,y_2)$ then using the general form of a circle in the Cartesian plane$$(x-x_1)^2+(y-y_1)^2=r^2$$
and calculating the radius using the distance formula
$$r=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$$
we would get
$$(x-x_1)^2+(y-y_1)^2=(x_2-x_1)^2+(y_2-y_1)^2$$
which can be expanded and simplified if required.


Q:

Separate a String By Semicolon

I am using following code to separate a string into multiple strings and getting an error
NSArray *arr = [randomStr componentsSeparatedByString:@";"];

Error:

-[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x1758f230
  -[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x1758f230

This is my Sample Data
NSArray *data = {
    {
    name = "name1";
    address = "RWP";
    ID = 0;
},
    {
    name = "name2";
    address = "RWP";
    ID = 1;
},
    {
    name = "name3";
    address = "RWP";
    ID = 2;
},}

NSString *randomStr = data[0];

What's wrong in my code

A:

You have an array of dictionaries, not strings. There is nothing to split.
You want something like this:
NSDictionary *dict = data[0];
NSString *name = dict[@"name"];
NSString *address = dict[@"address"];


Q:

Citrix/XenApp Content Redirection from within Application

I have the situation where we're using XenApp to run a Access 2010 app, as the client PC's aren't capable of doing so.  The app generates Word documents and to avoid printing issues I would like to see if its possible to use XenApp's content redirection so that when opening a document its opened on the client machine?
I've got published content redirection working, but all attempts a initiating it from within our Access app just loads the server side Word.
At the moment I've tried ShellExecute and UNC paths and File URI's.  Also tried Wscript.Shell object and I also tried creating a HTML page with a HREF and opening that.
Is what I'm attempting possible? It would be good to know as then I can just concentrate on alternative solutions.
I've got a vague feeling that a solution could be in using an alternative hWnd in ShellExecute, ie if I could more closely simulate a user opening a file manually, the content redirection would kick in.

A:

No you can't use content redirection for this, see:
http://support.citrix.com/proddocs/topic/xenapp6-w2k8-admin/ps-pub-content-redirect-server-task-v2.html
Content redirection is purely for web links, specifically the following types of links are supported:

HTTP (Hypertext Transfer Protocol)
HTTPS (Secure Hypertext Transfer Protocol)
RTSP (Real Player and QuickTime)
RTSPU (Real Player and QuickTime)
PNM (Legacy Real Player)
MMS (Microsoft Media Format)


Q:

Practical way to find out if SMS has been sent

I am interested in how I can figure out if SMS has been sent from the device.
In order to get notification when SMS is recieved, we use a broadcaster with:
android.provider.Telephony.SMS_RECEIVED

Important to mention that I do not send SMS from my app, I just should listen when SMS is sent from the device.
May be I should listen to some Content provider (which somehow related with SMS) and react for that change. Any ideas how I can achieve that?

A:

Yes, It is possible to listen SMS ContentProvider by using ContentObserver
Here is my example for Outgoing SMS:
First register a ContetObserver with content://sms/
   public class Smssendservice extends Service{

       @Override
       public void onCreate() {
            SmsContent content = new SmsContent(new Handler());
            // REGISTER ContetObserver
            this.getContentResolver().
                registerContentObserver(Uri.parse("content://sms/"), true, SMSObserver);
       }

       @Override
       public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub

            return null;
       }

SMSObserver.class
       public class SMSObserver extends ContentObserver {
            private Handler m_handler = null;

            public SMSObserver(SMSLogger handler){
                 super(handler);
                 m_handler = handler;
            }

            @Override
            public void onChange(boolean selfChange) {
            super.onChange(bSelfChange);
            Uri uriSMSURI = Uri.parse("content://sms");

            Cursor cur = this.getContentResolver().query(uriSMSURI, null, null,
                 null, null);
            cur.moveToNext();

            String protocol = cur.getString(cur.getColumnIndex("protocol"));

            if(protocol == null) {
         //the message is sent out just now
            }
            else {
                 //the message is received just now
            }
      }
  }

}

A:

use the following method to send sms as well as check whether the sms get delivered or not.
send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String phoneNo = "Phone number to sent";
                String message = "Your message";
                if (phoneNo.length() > 0 && message.length() > 0) {
                    TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    int simState = telMgr.getSimState();
                    switch (simState) {
                    case TelephonyManager.SIM_STATE_ABSENT:
                        displayAlert();
                        break;
                    case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_READY:
                        // do something
                        sendSMS(phoneNo, message); // method to send message
                        break;
                    case TelephonyManager.SIM_STATE_UNKNOWN:
                        // do something
                        break;
                    }

                } else {
                    Toast.makeText(getBaseContext(),
                            "Please enter both phone number and message.",
                            Toast.LENGTH_SHORT).show();
                }

            }

            private void displayAlert() {
                // TODO Auto-generated method stub

                new AlertDialog.Builder(YourActivity.this)
                        .setMessage("Sim card not available")
                        .setCancelable(false)
                        // .setIcon(R.drawable.alert)
                        .setPositiveButton("ok",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        Log.d("I am inside ok", "ok");
                                        dialog.cancel();
                                    }
                                })

                        .show();

            }

        });

            private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(YourActivity.this, 0,
                new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(YourActivity.this,
                0, new Intent(DELIVERED), 0);

        // ---when the SMS has been sent---
        final String string = "deprecation";
        registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(YourActivity.this, "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(YourActivity.this, "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(YourActivity.this, "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(YourActivity.this, "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;

                }
            }
        }, new IntentFilter(SENT));

        // ---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(YourActivity.this, "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(YourActivity.this, "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

    }


Q:

What is the name of this elm construct: type X = X {...}?

I am trying to understand this Elm construct:
type Item = Item { name : String, data : String }

It resembles a record, but it behaves very differently.
It is useful for defining recursive data models.
Unlike type alias Item = {...}, it does not provide a "constructor".
I cannot find it in Elm Syntax guides.
I cannot figure out how to access its fields:

> item = Item { name = "abc", data  = "def" }
Item { name = "abc", data = "def" } : Repl.Item

> item.name
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

`item` does not have a field named `name`.

6|   item.name
     ^^^^^^^^^ The type of `item` is:

    Item

Which does not contain a field named `name`.

How is this construct called?
How do you access the contained fields?

A:

It is a Union Type with a single constructor which happens to take a Record as its only type parameter.
The fact that the type name and constructor name are both Item is a common idiom, but holds no significance. It could easily be any other valid constructor name:
type Item = Foo { name : String, data : String }

For practical purposes, it can be useful to use a type alias for the internal record type so you can more succinctly pull values out. If you move things around a little bit:
type alias ItemContents = { name : String, data : String }

type Item = Item ItemContents

You could provide a function that returns the internal contents:
getItemContents : Item -> ItemContents
getItemContents (Item contents) = contents

And now it could be used like this REPL example:
> item = Item { name = "abc", data  = "def" }
Item { name = "abc", data = "def" } : Repl.Item
> contents = getItemContents item
{ name = "abc", data = "def" } : Repl.ItemContents
> contents.name
"abc" : String


Q:

Any CPU ou x64?

Procurei sobre compilação em Any CPU e x64, mas não achei nada em relação a performance e tamanho de arquivos. Existe diferença entre esses dois nesta questão quando a maquina é x64?
Website usando C# em VS 2017, MVC 3, .NET Framework 4.7

A:

No .NET Framework não faz diferença em termos de tamanho de executável porque o código gerado é um CIL e não um código nativo, o que vai é um bytecode que na execução gerará um código nativo através do JITter.
O que muda quando escolhe uma CPU ou deixar para qualquer uma é onde o código poderá rodar, é para criar as dependências certas.
Se tiver alguma dependência nativa pode fazer diferença.
Se escolher x64 não poderá rodar em uma máquina x86 e se escolher x86 rodará em modo de compatibilidade no x64.
Se escolher Any CPU o runtime gerará o código nativo de acordo com a arquitetura que está executando.
Assemblies do .NET não podem misturar arquiteturas, então se escolher uma delas, só poderá rodar junto com assemblies da mesma arquitetura.
O código nativo x64 será um pouco maior porque todo endereçamento ocupará 8 bytes em vez de 4 bytes que é o tamanho do x86. Há outras diferenças de instruções que pode fazer o código nativo na memória ficar maior ou menor.
De forma geral o x64 roda mais rápido, mas nem sempre. Mas não precisa escolher, deixe o Any CPU.
Em alguns casos escolher o x86 pode dar alguma vantagem, só testando para saber.
O CLR escolhe a melhor forma quando está no Any CPU, então quase sempre é a melhor escolha. Em geral só precisa escolher a arquitetura se for rodar junto um código não gerenciado para uma delas especificamente.
Artigo com mais detalhes.


Q:

How can I get device id for push notifications using firebase in android

I found this solution and I think it is not the ID which is required for notification kindly tell me by some samples:
import android.provider.Settings.Secure;

private String androidIdd = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

I guess I don't need an android id. I just want to get the device unique ID for Firebase Notification or GCM.

A:

Instead of using some third party tutorials I would prefer to take a look into the official Firebase Cloud Messaging documentation.
If you have set up everything correctly you can just scroll to the topic

Retrieve the current registration token
When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken(). This method returns null if the token has not yet been generated.

In a nutshell: Call FirebaseInstanceId.getInstance().getToken() to reveive the current device token.
EDIT:
The command FirebaseInstanceId.getInstance().getToken() is deprecated. The same documentation mentions a new approach as below:
FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

            }
        });


Q:

Adding `**` to head of lines with numbers in the beginning

I have the following contexts:
4. Pattern-Matching Conditional: How to use pcase and friends.
5. Iteration: while loops.
6. Generators: Generic sequences and coroutines.

and intent add ** to the head of each lines thus try replace-regexp
^\([::digit::]\) → ** \1
However, nothing happened.
What's the problem with my solution?

A:

The character class name should be enclosed between [: and :](see emacs manual), the correct pattern is
^\([[:digit:]]\)

Since you have a single group you can skip the parentheses and refer to the whole match with \&, e.g:
^[[:digit:]] → ** \&


Q:

How to stop linux timer?

I have a requirement wherein I start a timer and will do a particular task for a certain time. Once the timer expires,I shall set a global variable in the handler. This variable is checked continuously by my process. The process stops once the global variable is set.
But the problem with setitimer as in its description is " When any timer expires, a signal is sent to the process, and the timer (potentially) restarts. "
How do I stop the timer in my handler?

A:

From the getitimer(3p) man page:

Setting  it_value  to  0 shall disable a timer, regardless of the value of
         it_interval.


Q:

How to find all the clients that connected from specific hostname in ChannelGroup

I am learning about the netty framework and Google protobuf, so now I am writing some simple server and client applications.
I wrote a server based on the SecureChat example that come from netty and I want to write a method that return all the channels that connected from a specific ip (no matter what port).
I have a ChannelGroup that holds all the connected channels and I thought about using the write method - write(Object message, SocketAddress remoteAddress), but in the SocketAddress class I have to insert port.
So I thought about other ways but the only way I found working is using a for loop, but there is another ways? Some way that will give me better performance?
Thanks, BBLN.

A:

You could have your own ChannelGroup implementation which supports this. For this you could have a Map of Channels that are using the InetAddress of the Channel as key. So you will be able to lookup all Channels by IP in a fast way.


Q:

Adjust Transparency (alpha) of stat_smooth lines, not just transparency of Confidence Interval

Using ggplot2's stat_smooth(), I'm curious how one might adjust the transparency of the generated regression line. Using geom_points() or geom_line(), one normally sets a value for 'alpha', indicating the percent transparency. However, with stat_smooth(), alpha sets the transparency of the confidence interval (in my sample below, turned off - se=FALSE).
I cannot seem to find a way to make the regression line(s) a lower transparency than 1.
Your advice would be wonderful.
Sample Code
 library(reshape2)
 df <- data.frame(x = 1:300)
 df$y1 <-  0.5*(1/df$x + 0.1*(df$x-1)/df$x + rnorm(300,0,0.015))
 df$y2 <-  0.5*(1/df$x + 0.3*(df$x-1)/df$x + rnorm(300,0,0.015))
 df$y3 <-  0.5*(1/df$x + 0.6*(df$x-1)/df$x + rnorm(300,0,0.015))
 df <- melt(df, id = 1)

 ggplot(df, aes(x=x, y=value, color=variable)) +
   geom_point(size=2) +
   stat_smooth(method = "lm", formula = y ~ 0 + I(1/x) + I((x-1)/x),
               se = FALSE,
               size = 1.5,
               alpha = 0.5)

A:

To set alpha value just for the line you should replace stat_smooth() with geom_line() and then inside the geom_line() use the same arguments as in stat_smooth() and additionally add stat="smooth".
ggplot(df, aes(x=x, y=value, color=variable)) +
  geom_point(size=2) +
  geom_line(stat="smooth",method = "lm", formula = y ~ 0 + I(1/x) + I((x-1)/x),
              size = 1.5,
              linetype ="dashed",
              alpha = 0.5)

A:

As an alternative that's slightly more intuitive -- perhaps created since this answer -- you can use stat_smooth (geom="line"). The SE envelope disappears, though you can add it back with something like:

geom_smooth (alpha=0.3, size=0, span=0.5)
stat_smooth (geom="line", alpha=0.3, size=3, span=0.5) +

The first line creates the SE. with no (0-width) line, and the second line adds the line over top of it. The (current) documentation mentions that stat_smooth is for non-standard geoms (e.g. "line").


Q:

Generalising my query to run on all data instead of specific id

I have a specific query, that works when I hardcode the ID it should run for. I would like to run it for all IDs in my database.
This is a representative setup:
CREATE TABLE `dummy` (
    `total` INT(11) NULL DEFAULT NULL,
    `a_id` INT(11) NULL DEFAULT NULL,
    `month` INT(11) NULL DEFAULT NULL
);

Data:

total | a_id | month
2     | 1    | 3
4     | 1    | 5
3     | 1    | 6
6     | 1    | 9
3     | 2    | 4
6     | 2    | 10

CREATE TABLE `months` (
    `month` INT(11) NULL DEFAULT NULL
);

Data: Just the values 1 through 12

What I want to achieve is to use the month as a timestamp, and for each a_id get their total for that month, with zero for the months that aren't set up (but only between the first month, and the last month, of that a_id).
My query so far:
SELECT c.month, COALESCE(d.total, 0) AS 'total', COALESCE(d.a_id, 1) AS 'a_id'
FROM (
    SELECT month
    FROM months
    WHERE month >= (SELECT MIN(month) FROM dummy WHERE a_id = 1)
    AND month <= (SELECT MAX(month) FROM dummy WHERE a_id = 1)
) c
LEFT outer JOIN (
    SELECT *
    FROM dummy
    WHERE a_id = 1
) d ON d.month = c.month
ORDER BY c.month;

And its output:
month | total | a_id
3     | 2     | 1
4     | 0     | 1
5     | 4     | 1
6     | 3     | 1
7     | 0     | 1
8     | 0     | 1
9     | 6     | 1

How can I change this query and get the output for every a_id in the table, without an external program like PHP change the ID every time?

A:

It seems you need
SELECT months.month,
       COALESCE(dummy.total, 0) total,
       a_ids.a_id
FROM months
CROSS JOIN ( SELECT DISTINCT a_id
             FROM dummy ) a_ids
LEFT JOIN dummy ON months.month = dummy.month
               AND a_ids.a_id = dummy.a_id
INNER JOIN ( SELECT MIN(month) min_month,
                    MAX(month) max_month
             FROM dummy ) borders ON months.month BETWEEN borders.min_month
                                                      AND borders.max_month
ORDER BY a_ids.a_id, months.month;

or
SELECT months.month,
       COALESCE(dummy.total, 0) total,
       a_ids.a_id
FROM months
CROSS JOIN ( SELECT DISTINCT a_id
             FROM dummy ) a_ids
LEFT JOIN dummy ON months.month = dummy.month
               AND a_ids.a_id = dummy.a_id
INNER JOIN ( SELECT MIN(month) min_month,
                    MAX(month) max_month,
                    a_id
             FROM dummy
             GROUP BY a_id ) borders ON months.month BETWEEN borders.min_month
                                                         AND borders.max_month
                                    AND a_ids.a_id = borders.a_id
ORDER BY a_ids.a_id, months.month;

fiddle


Q:

Formik + yup: how to validate a location schema where the fields(country, state, city) are not mandatory, but if one is filled, each should be filled?

I am having the below schema
validationSchema={yup.object().shape({
  firstName: yup
    .string()
    .required("Name cannot be empty")
    .matches(NAME_REGEX, "Name can only contain english characters"),
  lastName: yup
    .string()
    .required("Name cannot be empty")
    .matches(NAME_REGEX, "Name can only contain english characters"),
  location: yup
    .object()
    .nullable()
    .shape({
      country: yup.string().required(),
      state: yup.string().required(),
      city: yup.string().required()
    })
})}

The validation for firstName and lastName is working fine but I don't know how to validate the location.
Requirement: location is not at all required to be filled. But if any(country/state,city) of the field is filled, then  all three must be filled. Either all or none.
Though I tried to validate it as above but it's not working.
Another validation requirement is: These values are being selected from the select html element, of which the first <option> is <option key={0}>-select-</option>. So, I don't want my users to select this option as well. As of now, I am handling it in the onSubmit by checking the values and if they contain -select- then these values will not be considered and will be replaced by the existing ones.
update:
location can never be null. If the user has not set any of the location field then also location would be:
location: {
   country: null,
   state: null,
   city: null
}

location can never be null, only its properties can be.
How should I do these validations?

A:

You must set the default of location to null using mixed.default(value) like this:
location: yup
    .object()
    .default(null)
    .nullable()
    .shape({
      country: yup.string().required(),
      state: yup.string().required(),
      city: yup.string().required()
    })

Update:

location can never be null, only its properties can be.

You can do it like this:
location: object()
    .shape({
      country: string().default(null).nullable().test(
        value => value === null || value,
      ),
      state: string().default(null).nullable().test(
        value => value === null || value,
      ),
      city: string().default(null).nullable().test(
        value => value === null || value,
      )
    })


Q:

Getting correct response but data not getting displayed in UI

I have developed a service and its working fine, response is looking exactly same when compared to the data from database, But when the service is being consumed, the UI is breaking, I am getting the error "An error occured while retrieving data from database, Is Visible Changed. Object reference not set to an instance of an object." But in fiddler I have found the correct response. I have the checked the order of the data contract, every thing is in same order. Can someone suggest what might be the issue?

A:

In your service code, you should have this statement:
using System.Runtime.Serialization;

and the data that your service is returning should be defined like this:
[DataContract]
public class YourOutPutClassName
{
    [DataMember]
    public string property1 {get; set;}
    [DataMember]
    public int property2 { get; set; }
}


Q:

Delay php script without occupying connection

I want to ask if anyone knows a way I can delay a php script without actually occupying a connection slot all the time. I am not completely aware of this but I was told that apache has a limit of connections or a limit of scripts running at the same time I can't exactly recall and this script of mine needs to run for about 1 to 3 hours and it doesn't really do anything heavy, it actually sleeps like 90% of the time.

A:

If you're running a script and not expecting any response you can either run it in the terminal of the server computer with php "dir/to/php/script.php".
If the initialization of the script happens remotely then you could have the script exit so the script continues running but does not keep the connection alive. header('Connection: Close');
Example:
<?php

echo "The server is now doing some complex actions in the background..."; //even maybe a redirect instead
header('Connection: Close');
file_put_contents(file_get_contents("largest_file_in_the_world.txt"),"/tmp/test.txt");

?>


Q:

Add a shortcut in ribon of task list

I've a task list and in the ribbon under Items I've a blue buton "Assign to me"
Do you know how I can add this to my other lists? And how is it working?

A:

I come with the solution.
In sharepoint designer, on the task list, in the bottom right you have custom actions.
With this, you can add an action in the ribbon of the list


Q:

Cannot get ngMessages to validate

I have installed angular-messages via npm and passed ngMessages to my application.
I added the directive to my partial html, but the %error blank
template:

    <form>

                <input type='text' name='fname' ng-model='newFriend.fname' required/>
                First Name

                <input type='text' name='lname' ng-model='newFriend.lname' required/>
                Last Name

                <input type='date' name='bday' ng-model='newFriend.bday' required/>
                Birthday

                <input type='submit' value='Create' ng-click='addFriend()'/>

friendForm.fname.$error = {{ friendForm.fname.$error.required | json }}

First Name is Required

Last Name is Required

Birthdate is Required

    </form>

A:

You need to give your <form> a name attribute of friendForm because you are trying to reference the form i.e. friendForm.fname.$error.
Taken from the forms documentation:

A form is an instance of FormController. The form instance can
  optionally be published into the scope using the name attribute.
Similarly, an input control that has the ngModel directive holds an
  instance of NgModelController. Such a control instance can be
  published as a property of the form instance using the name attribute
  on the input control. The name attribute specifies the name of the
  property on the form instance.
This implies that the internal state of both the form and the control
  is available for binding in the view using the standard binding
  primitives.

Here is your code working with the name attribute.

// app.js
(function() {

  'use strict';

  angular.module('app', ['ngMessages']);

})();

// main.controller.js
(function() {

  'use strict';

  angular.module('app').controller('friendsController', friendsController);

  friendsController.$inject = [];

  function friendsController() {

  }

})();

  <form name="friendForm">

        <input type='text' name='fname' ng-model='newFriend.fname' required/>
        First Name

        <input type='text' name='lname' ng-model='newFriend.lname' required/>
        Last Name

        <input type='date' name='bday' ng-model='newFriend.bday' required/>
        Birthday

        <input type='submit' value='Create' ng-click='addFriend()' />

friendForm.fname.$error = {{ friendForm.fname.$error.required | json }}

First Name is Required

Last Name is Required

Birthdate is Required

  </form>


Q:

Calling chrome chooseEntry inside XmlHttpRequest readyState 4

I'm trying to save an image in fileSystem from my blob response but the file dialog is not showing, this is my script:
var xhr2 = new XMLHttpRequest();
xhr2.open("GET", "http://website.org?url=http://www.google.com");
xhr2.responseType = "blob";
xhr2.onreadystatechange = function() {
    if (xhr2.readyState == 4) {
        console.log(xhr2.response); //Blob {type: "text/xml", size: 17830, slice: function}
        $('img')[0].src=window.URL.createObjectURL(xhr2.response); //response image is showing fine

        console.log($('#mydiv').attr('id')+'.jpg'); //suggestedName is 'web:file.html.jpg'
        chrome.fileSystem.chooseEntry({ type:'saveFile',suggestedName:$('#mydiv').text()+'.jpg',accepts:[{ extensions:['jpg'] }] },function(fileEntry){
        //chooseEntry is not creating file dialog
            console.log(fileEntry); //undefined
        });
    }
};
xhr2.send(null);

Manifest.json
"permissions": [
    "http://www.website.org",
    "syncFileSystem",
    {"fileSystem": ["write", "directory"]}
],

A:

Ok, I solved it. Apparently the suggestedName value cannot have the character ':'


Q:

UIButton width is 50% of UIView's width iOS

I am new to Storyboard environment.
How to set UIButton's width is to 50% of UIView's width using AutoLayout Constraints in Storyboard in XCode6
Can any one tell me how to implement this?

A:

select you button and superview

make pin

select constraints

Reverse both items and set multiplier to 0.5

select only button and set horizontal align

Done!
I recommend using Masonry/SnapKit libraries from github


Q:

Design pattern to switch a state for a set of functions

I have a series of instance functions in a class. There is also a boolean instance variable that designates an object state. Almost all the instance functions depend on this boolean state. Their body looks like
int f() {

   if (state) {
      //do stuff
   }
   else {
      // do other stuff
   }
}

In addition to that some function are swapped by the state. So if state is true then when user calls f() it actually is run. But when state is false then when user calls f() what happens is that antiF() is run.
So some functions have switches inside them and some functions get swapped completely.
If I was doing this with C++ I would probably use function pointers. How would I do this with Java? A Strategy pattern?

A:

Looks like you want the state pattern. Instead of having each function check for the state, you pull these functions into a state interface and have separate implementations for each state:
public interface State {
  void f();
  void g();
  void h();
}

public class StateA : State {
  public void f() { do something; }
  ...
}

public class StateB : State {
  public void f() { do something else; }
  ...
}

Then instead of a boolean variable, you would maintain a specific State instance:
State currentState = new StateA();
...
currentState = new StateB();


Q:

How to only sell shares(index funds) with long term gains after mid year conversion to vanguard admiral class?

I've never sold in a taxable account before so please bear with me.
I bought VGTSX more than a year ago and then upgraded to admiral class last year(and bought more). Now, I would like to sell some of my shares, while avoiding the short-term cap gain tax.
On vanguard I set my fund to FIFO, but this is confusing to me since I converted VGTSX to VTSAX halfway last year. If I didn't do the conversion, I could easily sell the X number of shares I bought initially. But now, after the conversion I am not sure what to do.
Does Vanguard have an easy way for me to determine how much shares I can safely sell?

A:

Converting share class is not a taxable event, so each lot of your converted shares should still have its original basis and holding period. If you have the records, multiply each purchase quantity by the ratio of (total new shares / total old shares) at the conversion (and round, apparently to 3 decimals; maybe sell slightly less than you compute in case your arithmetic differs from theirs). IIRC under MyAccounts/CostBasis it has an option to show the individual lots, but I no longer have an open holding to verify this.
FYI if you choose to use the average method for basis for a mutual fund, your holding period is still computed FIFO.


Q:

lxml (xml python parser) go to next element

Has someone know how to jump to the next element in xml? i.e
<xml>
<node></node>
<text number="2">Text number 2</text>
<text number="3">Text number 3</text>
...
<text number="N">Text number N</text>
...
<node></node>
</xml>

I would like to be able to jump to element  with number 3 then iterate few times forward.
element2 = xpath('//text[@number="2"]')
element3 = element2.nextElement()
returns <text number="3">Text number 3</text>
element4 = element3.nextElement() ...

I know that I can find all elements with attribute 'number' then iterate over them but important for me is to be able to go to next element starting from selected (element after) - example is just simplified
Thanks :)

A:

Working examples are a great way to explore. xpath gives you a list of elements that match your query. help on one of those elements tells you what you want to know.
>>> import lxml.etree
>>> root=lxml.etree.fromstring("""<xml>
... <node></node>
... <text number="2">Text number 2</text>
... <text number="3">Text number 3</text>
... ...
... <text number="N">Text number N</text>
... ...
... <node></node>
... </xml>""")
>>> elements=root.xpath('//text[@number="2"]')
>>> elements
[<Element text at 0x7fdd45d04d88>]
>>> help(elements[0])

...

 |  getnext(...)
 |      getnext(self)
 |
 |      Returns the following sibling of this element or None.

...


Q:

how a 32 bit processor process 64 bit double value?

Any body tell me how a 32 bit processor do the operations on 64 bit double  values?
In java double is 64 bit long. Then how a 32 bit processor do arithametic operations(ie. addidion or subtraction) upon 64 bit double variables.

A:

64 bit types and their operations are emulated on 32 bit processors. Upon compilation the compiler maps the 64 bit values to two 32 bit values, and the operations upon these values to a sequence of operations on their 32 bit representations. That means that a simple operation which adds two 64 bit values can be executed natively and atomic on a 64 bit CPU, takes a few clock cycles when being emulated on a 32 bit CPU.
Details and examples: 64-bit types and arithmetic on 32-bit CPUs


Q:

Sum the fetched data

Goodmorning guys! Here i want to do, I want to sum the two columns, units_lab and units_lec but when i run my code below the table became messy. What's the cause of this problem? Is my approach to sum the column is wrong? What is the correct approach for this?

if(isset($_POST['loadsgrade'])){
    $stud = $_POST['stud'];
        $output = '';
    $sql = "SELECT * FROM grades WHERE stud_no ='$stud'";
    $result = mysqli_query($con,$sql);
    $output .= '

                    Subject Code
                    Section
                    Subject Decription
                    Units
                    Prelim
                    Midterm
                    Finals
                    Final Grade

';

      while($row = mysqli_fetch_array($result))
      {
        $output .= '

                    '.$row['subj_cd'].'
                    '.$row['section'].'
                    '.$row['subj_descr'].'
                    '.$row['units_lec'] + $row['units_lab'].'
                    '.$row['prelim_grade'].'
                    '.$row['midterm_grade'].'
                    '.$row['finals_grade'].'
                    '.$row['final_grade'].'

          ';
      }
          $output .= '

';
   echo $output;

}

A:

You should put the sum in () because otherwise PHP is confused about the + for numbers and the . for string concatenation.
'. ($row['units_lec'] + $row['units_lab']) .'


Q:

Virtualenv: can't create virtualenv: IOError: [Errno 2] No such file or directory: 'python'

This happens when attempting to update the python installation in my virtualenv OR when creating a new virtualenv:
[marcintustin@localhost oneclickrep]$ virtualenv --always-copy --clear --python=/usr/bin/python oneclickcosvirt/
Already using interpreter /usr/bin/python
Deleting tree oneclickcosvirt/lib/python2.7
Not deleting oneclickcosvirt/bin
New python executable in oneclickcosvirt/bin/python
Traceback (most recent call last):
  File "/usr/bin/virtualenv", line 9, in <module>
    load_entry_point('virtualenv==1.10.1', 'console_scripts', 'virtualenv')()
  File "/usr/lib/python2.7/site-packages/virtualenv.py", line 821, in main
    symlink=options.symlink)
  File "/usr/lib/python2.7/site-packages/virtualenv.py", line 956, in create_environment
    site_packages=site_packages, clear=clear, symlink=symlink))
  File "/usr/lib/python2.7/site-packages/virtualenv.py", line 1377, in install_python
    shutil.copyfile(py_executable_base, full_pth)
  File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'python'
[marcintustin@localhost oneclickrep]$

The result is consistently the above. /usr/bin/python exists and is working very nicely (it's also the python picked up by which). What's the cause here?
Edit: Using virtualenv version 1.10.1

A:

This is a bug with virtualenv. Using the --always-copy flag triggers copying behaviour, which is broken. There are bug reports and patches already submitted.
The line shutil.copyfile(py_executable_base, full_pth) should be shutil.copyfile(py_executable, full_pth).


Q:

Response is not getting proper as per our requirement

I am using spring boot with security in java restful API. I want a proper response as per my requirement. i will show you the my database table and require response. i will also show you my tried code.
I have tried but the response is not getting proper as per my requirement. anyone have idea ?? how to do that ?

Database Table
I want like this response from above table

"eventColorLegends": [
    {
      "color": "Red",
      "items": [
        "Musician1",
        "Workshop",
        "Seminart"
        ]
    },
    {
      "color": "Black",
      "items": [
        "Product Launches",
        "Incentive Trips"
      ]
    },
    {
      "color": "Green",
      "items": [
        "Dancing",
        "Rotary - Service Club",
        "Historical/Remembrance"
      ]
    },
    {
      "color": "Yellow",
      "items": [
        "Party",
        "Incubator - Accelerator",
        "Leads - Referral"
      ]
    },
    {
      "color": "Orange",
      "items": [
        "Charity",
        "Non-profit",
        "Rotary - Service Club",
        "Historical/Remembrance",

      ]
    },
    {
      "color": "Coffee",
      "items": [
        "Incubator - Accelerator"
      ]
    },
    {
      "color": "Blue",
      "items": [
        "Leads - Referral",
        "Historical/Remembrance",
        "Rotary - Service Club",
        "For-Profit Company",

      ]
    },
]

I have try code in serviceImpl class

public GenericResponse findAllTypeOfEvents() {
        try {
            List<TypesOfEvents> typesOfEventsList = typeOfEventsDao.findAll();
            List<String> listEvents = new ArrayList<String>();
            for (int i = 0; i < typesOfEventsList.size(); i++) {
                for (int j = i + 1; j < typesOfEventsList.size()- 1; j++) {
                    if (typesOfEventsList.get(i).getColor().equalsIgnoreCase(typesOfEventsList.get(j).getColor())) {
                        if (typesOfEventsList.get(j).getType().equalsIgnoreCase(typesOfEventsList.get(j).getType())){
                            listEvents.add(i,typesOfEventsList.get(j).getType());
                            System.out.println(typesOfEventsList.get(i).getColor() + " : " + typesOfEventsList.get(j).getType());
                        }
                    }
                }
            }
            return APIResponseBuilder.build(true, listEvents.toArray(), typesOfEventsList.size() > 0 ? commonMessages.findAllTrue : commonMessages.findAllFalse);
        } catch (Exception e) {
            logger.error(commonMessages.findAllException + "TypesOfEvents " + e.getMessage());
            return APIResponseBuilder.build(false, e.getMessage(), commonMessages.exception);
        }
    }

4.MY Response
"data": [
    "Seminart",
    "For-Profit Company",
    "For-Profit Company",
    "Historical/Remembrance",
    "Leads - Referral",
    "Historical/Remembrance",
    "Historical/Remembrance",
    "Historical/Remembrance",
    "Rotary - Service Club",
    "For-Profit Company",
    "For-Profit Company",
    "For-Profit Company",
    "Historical/Remembrance",
    "Seminart",
    "Seminart",
    "Historical/Remembrance",
    "Workshop",
    "Leads - Referral",
    "Leads - Referral",
    "For-Profit Company",
    "Incubator - Accelerator",
    "Seminart",
    "Historical/Remembrance",
    "Leads - Referral",
    "Leads - Referral",
    "Leads - Referral",
    "Incubator - Accelerator",
    "For-Profit Company",
    "Incubator - Accelerator",
    "Historical/Remembrance",
    "Rotary - Service Club",
    "Incubator - Accelerator",
    "Historical/Remembrance",
    "Rotary - Service Club",
    "Leads - Referral",
    "Workshop",
    "Seminart",
    "Historical/Remembrance",
    "Rotary - Service Club",
    "Non-profit",
    "Incubator - Accelerator",
    "Historical/Remembrance",
    "Rotary - Service Club",
    "Leads - Referral",
    "Incubator - Accelerator",
    "Rotary - Service Club",
    "Historical/Remembrance",
    "Historical/Remembrance",
    "Incentive Trips",
    "Workshop",
    "Seminart",
    "Workshop"
  ]
}

A:

Create a Map<String, List<String>> to map a list of type for each color.
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < typesOfEventsList.size(); i++) {
     if (fruits.containsKey(typesOfEventsList.get(i).getColor())){
          List<String> list = map.get(typesOfEventsList.get(i).getColor());
          list.add(typesOfEventsList.get(i).getType());
          map.put(typesOfEventsList.get(i).getColor(), list);
     } else {
         List<String> list =  new ArrayList<String>();
         list.add(typesOfEventsList.get(i).getType());
         map.put(typesOfEventsList.get(i).getColor(), list);
    }
}

Then create class TypeByColor
class TypeByColor {
    String color;
    List<String> items;
}

Then create list from map
    List<TypeByColor> data = new ArrayList<>();
    for (String name : map.keySet())
    {
        list.add(new TypeByColor(name,map.get(name)));
    }


Q:

How to approach an unknown person via email if I only have a name that sounds like her nickname?

So, I am researching master courses opportunities on a university at a different country (Scotland) and I was talking to the course director via email, asking about the workload of the course and he suggested I talk to a student, and gave me her email.
When the director gave the student email, he just said "Try emailing Jo", followed by her email.
However, it sounds a little awkward to approach that person with an email starting like "Hey Jo" or "Dear Jo", given that "Jo" sounds like some sort of nickname.
"Jo" is, however, all the information I have about that person.
It might also be rude to somehow imply that Jo might be an informal name and it turns out to be an actual name, given that I don't even know where she is from.
How can I start my email?

A:

There are a few different ways you can go about doing this.

Start the email with Hello Jo,. Jo could very well be just their nickname, but that is not for you to assume. The name you were given is Jo. Jo is all you know about the person.
If you feel highly confident that their actual name is something longer than Jo, then you can either mention in the same email (or on your second email, after getting the reply to the first one) that the professor told you that their name was Jo and if it is OK if you call her by that. You could ask her if that is a nickname or the real name. Don't sound like you don't think Jo is a real name. It might very well just be her name and you might just be insulting her. Phrase your sentence like this:

The professor told me to contact Jo, so I went with the assumption that Jo is your name. Is that OK or would you like me to address you as something else?

If you don't want to do either of that, you could just start your email with Hello,. Hello is what you should use if you don't know who this email is supposed to be for. In a workplace environment, when I email a client or a support team or something, I just start my email with Hello. Then when they reply to my email, I get a "real person" attached to that email and I can go with that person for all my corresponding emails. Just start it with Hello and in their reply, watch for their signature or other clues to see how to address them in future emails. I would also take an extra step and mention that the professor told you to contact Jo. Like so:

Hello,
  Blah blah and blah. I spoke to the professor regarding this and he asked me to contact Jo and gave me your email address.
  Blah blah and blah.

This will ensure that Jo knows that you are contacting them KNOWING THAT they are Jo.
Hope this helps.


Q:

Drag and Drop with custom control onto a Grid

I am looking to allow a user to drag a custom control around a Grid control smoothly, and I am not sure exactly what I am missing. All controls have AllowDrop set to true.

On MouseMove I do the following in the control that is being dragged:
DataObject dataObj = new DataObject("PersistentObject",this);
DragDrop.DoDragDrop(this, dataObj, DragDropEffects.Move);

On the Grid's DragEnter, DragOver, and DragDrop events, I set the effects of the DragEventArg to all.

The feedback shows that it the new location on the grid is a valid drop target, but it never seems to move.
Is there a way to do this on a Grid, or I am trying to do this on the wrong control (I am using a grid because the designer started with one)?
Are there other events that I have to fix, and/or are my current ones broken?
Edit: It would also be appreciated if it showed the control being dragged as it was happening. I am not sure if that is supposed to happen with my current approach, but that is the goal.

A:

You can easily do this without using the built-in drag-drop stuff.
Point mouseOffset = new Point();

userControl.PreviewMouseLeftButtonDown += (sender, e) =>
{
    mouseOffset = Mouse.GetPosition(userControl);
    userControl.CaptureMouse();
};

userControl.PreviewMouseMove += (sender, e) =>
{
    if (userControl.IsMouseCaptured)
    {
        Point mouseDelta = Mouse.GetPosition(userControl);
        mouseDelta.Offset(-mouseOffset.X, -mouseOffset.Y);

        userControl.Margin = new Thickness(
            userControl.Margin.Left + mouseDelta.X,
            userControl.Margin.Top + mouseDelta.Y,
            userControl.Margin.Right - mouseDelta.X,
            userControl.Margin.Bottom - mouseDelta.Y);
    }
};

userControl.PreviewMouseLeftButtonUp += (sender, e) =>
{
    userControl.ReleaseMouseCapture();
};

So the demo code I wrote up for this looks something like the following:
<Window x:Class="StackOverflowScratchpad.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="350"
    Width="525">
    <Grid>
        <!-- I am using a Button here just for simplicity. The code
             will function the same no matter what control is used. -->
        <Button x:Name="userControl" Width="75" Height="23" />
    </Grid>
</Window>

public MainWindow()
{
    InitializeComponent();

    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object obj, RoutedEventArgs args)
{
    // Add the above C# here.
}


Q:

Error passing shared_ptr& as shared_ptr& without const

I got compile error when passing shared_ptr<Derived>& as shared_ptr<Base>&, see the below code and detailed question.
Note: this question is similar to "Passing shared_ptr<Derived> as shared_ptr<Base>" but not duplicate.
#include <memory>
class TBase
{
public:
  virtual ~TBase() {}
};
class TDerived : public TBase
{
public:
  virtual ~TDerived() {}
};
void FooRef(std::shared_ptr<TBase>& b)
{
  // Do something
}

void FooConstRef(const std::shared_ptr<TBase>& b)
{
  // Do something
}

void FooSharePtr(std::shared_ptr<TBase> b)
{
  // Do something
}
int main()
{
  std::shared_ptr<TDerived> d;
  FooRef(d);  // *1 Error: invalid initialization of reference of type ‘std::shared_ptr<TBase>&’ from expression of type ‘std::shared_ptr<TDerived>’
  FooConstRef(d); // *2 OK, just pass by const reference
  FooSharePtr(d); // *3 OK, construct a new shared_ptr<>
  return 0;
}

Compiled by g++ -std=c++11 -o shared_ptr_pass_by_ref shared_ptr_pass_by_ref.cpp
Env: Ubuntu 14.04, g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Detailed question:
Why is it OK to pass by const reference (*2), but not OK to pass by reference (*1)?
Note: I know the best practice is to pass by const reference, but just want to know why the compile error occurs.

A:

You seem to expect some kind of template covariance, whereby AnyTemplateClass<Derived> can bind to AnyTemplateClass<Base>&. Templates don't work this way. Generally, AnyTemplateClass<Derived> and AnyTemplateClass<Base> are two distinct, completely unrelated classes.
A specific template class may, or course, provide a relationship in some form. shared_ptr<T> in particular has a templated constructor accepting shared_ptr<U> for any U such that U* is convertible to T*.
FooConstRef(d) call works by constructing a temporary - effectively
shared_ptr<TBase> temp(d);
FooConstRef(temp);

But temporaries can't bind to non-const references, that's why FooRef(d) doesn't work in a similar way.


Q:

Basic Jquery selector traversing

I'm trying to submit a form once a div 'tweet' has been clicked. Simple enough but i can't get it to work. Nothing happens on click. Don't think i'm navigating to the correct selector. The html sample below has many 'tweet' instances but all with different "values" that i want to send via post
html

                <form id="posticon" method="POST" action="">
                <input type="hidden" name="srch_term" id="srch_term" value="John">
                </form>

jquery
$(document).ready(function(){
    $(document).on('click', '#tweet', function(){
    $(this).children("#posticon").submit();
    });
});

A:

Firstly, you can use an id once in a page, so use a .tweet class instead.
Secondly, jQuery's .children() method is used to get direct children (i.e. it doesn't go more than one level deep), so use .find() instead, which goes deeper than one level.

$(document).ready(function() {

  $(".tweet").click(function() {
    $(this).find(".posticon").submit();
  });

  //to check if the form was successfully submitted
  $(".posticon").submit(function() {
    var inputValue = $(this).children("input").val();
    alert(inputValue + "'s form was submitted");
  });

});

  John's Tweet

        <form class="posticon" method="POST" action="">
          <input type="hidden" name="srch_term" id="srch_term" value="John">
        </form>

  Michael's Tweet

        <form class="posticon" method="POST" action="">
          <input type="hidden" name="srch_term" id="srch_term" value="Michael">
        </form>

More info on .children() and .find() on the jQuery website.


Q:

Use a List instead of ArrayList> for list view

I have an object:
private ArrayList<HashMap<String, String>> customerDataList;

Which I populate with data retrieved from a web service call. The below is inside a loop iterating over the retrieved json data:
HashMap<String, String> customer = new HashMap<>();
//snip
customer.put("CustomerName", customerName);
//snip
customerDataList.add(customer);
//rinse and repeat

Then I display this in a list view in my activity with:
ListAdapter adapter = new SimpleAdapter(Activity.this, customerDataList,
                R.layout.list_item, new String[] {"CustomerName"}, new int[] { R.id.customerName });
setListAdapter(adapter);

However I am wondering if there is a way I can use a List instead.
I created my customer class, created a List of it like so:
private List<Customer> customerList;

However when it comes to setting the ListAdapter I am unsure of what to put. I replaced customerDataList with customerList but I receive errors.
Edit: The error is
SimpleAdapter() in SimpleAdapter cannot be applied to:
Expected data: java.util.Map<java.lang.String.?>>
Actual arguments: customerList <Customer>

Edit: my class structure
private class Customer
{
    private int customerID;
    private String customerName;
    private String customerLocation;
    private String runningTime;
    private double distance;
}

A:

If you  want a use a list of custom objects you need to use another adapter e.g. ArrayAdapter:
List<Customer> customerList = null;
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
        R.layout.list_item, customerList);

Now since ArrayAdapter expects strings to come out of your custom objects, override a toString method in your class:
class Customer {
    String customerName;

    @Override
    public String toString() {
        return customerName;
    }
}

If your customer class has multiple fields that will need to be used in your adapter, you will need a custom adapter, something like this:
// Turns out that when the layout is not a TextView, you need to provide the id
// of the TextView the adapter can bind to
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
        R.layout.list_item, R.id.customer_name, customerList) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        TextView name = view.findViewById(R.id.customer_name);
        TextView surname = view.findViewById(R.id.customer_surname);

        name.setText(getItem(position).customerName);
        surname.setText(getItem(position).customerSurname);

        return view;
    }
};

You can google to find some performance adjustments for custom adapters.


Q:

Catch an array of data and outputting a single row

I need to have a single row of data "printed out" through php.
So, take this example from w3schools:
http://www.w3schools.com/PHP/php_mysql_select.asp
There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:

Peter Griffin
  Glenn Quagmire

What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this doesent work, just an example):
echo $row["Name",2];

And get:

Glenn Quagmire

I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.

A:

you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.
$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);

Or during the foreach loop fetch all result into another array.
$result = mysql_query("SELECT * FROM Persons");

$rows = array();
while($row = mysql_fetch_array($result))
{
  $rows[] = $row['FirstName'] . " " . $row['LastName'];
}


Q:

How to use an input type=text field to accept only digits, minus sign and decimals and nothing more with Angular

I'll be brief and to the point: I have two text boxes with angular.
Here it is:
<div data-ng-controller="customValidationAndNbrsCheckController">
     <label class="input">
        <number-only-input  placeholder="Latitude" input-value="wksLat.number" input-name="wksLat.name" />
     </label>
     <label>
        <number-only-input  placeholder="Longitude" input-value="wksLon.number" input-name="wksLon.name" />
     </label>
</div>

Here's my directive:
UPDATE: PROBLEM SOLVED... here's the fiddle that shows the EXACT change that fixes the problem. Thanks for reading but I got it. http://jsfiddle.net/vfsHX/
//Numbers only function
angular
    .module("isNumber", [])
    .directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope) {
            scope.$watch('wksLat.number', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.wksLat.number = oldValue;
                }
            });
            scope.$watch('wksLon.number', function (newValue, oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.wksLon.number = oldValue;
                }
            });
        }
    };
});

Here's my Service:
(function (app) {
debugger;
var customValidationAndNbrsService = function () {

    var customValidationAndNbrsServiceFactory = {};

    customValidationAndNbrsServiceFactory.settings = new mainApp.Models.Settings();

    customValidationAndNbrsServiceFactory.getSettings = function () {
        return customValidationAndNbrsServiceFactory.settings;
    };

    return customValidationAndNbrsServiceFactory;
};

app.factory("customValidationAndNbrsService", customValidationAndNbrsService);

}(angular.module("mainApp")));

This is from an example I found here on Stack.
PROBLEM:  This works GREAT but...

The value in the text box starts out with the number "1"; why?
The text box will 'not' allow dashes, decimals with the numbers but, it does not allow alpha characters. Good.
This is for LAT/LON data restricted to 50 characters which does work as maxlength='50'
What does the "=" sign mean at the end of the inputValue and inputName? Is that a standard? because when I change it to, say a "0", thinking that's why the "1" appears in the text box, the debugger in Chrome shows code failures.

QUESTION: How do I modify the code to "allow" dashes and decimals, since we're entering the LAT LONs as decimal degrees and not DD:MM:SS.
Here's the possible input: 25.2223332 LAT and -45.685464 LON
So I hope the moderators do not delete this question. It's valid and yes, I need a "fix-my-code" help since that's what I believe this site is for.
Thanks, everyone.

A:

1. comes from input-value="wksLon.number"
2. match your value to regex
js
scope.$watch('inputValue', function (newValue, oldValue) {
  var arr = String(newValue).split("");
  if (arr.length === 0) return;
  if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
  if (arr.length === 2 && newValue === '-.') return;
  if (isNaN(newValue)) {
    scope.inputValue = oldValue;
  }
});

this should be changed to your setup, probably with RegEx
something like that
scope.$watch('inputValue', function (newValue, oldValue) {
  var myRegex = /^(-)?\d+(.\d+)$/
  if (!myRegex.test(newValue) || newValue.length > 50) {
    scope.inputValue = oldValue
  }
});

3. extended 2 by 3 with length > 50
4. that's a data binding to same name
<number-only-input  placeholder="Longitude" input-value="wksLon.number" input-name="wksLon.name" />

from above element input-value and input-name are binded with the same name
scope: {
        inputValue: '=',
        inputName: '='
    },

but if you want to use different you can do it like:
scope: {
        Value: '=inputValue',
        Name: '=inputName'
    },


Q:

Getting Data from foreign table by primary key

In this setup, I have one Owner and he has 10 schools. I get the list of Owners in a combo box and select the Owner with its Id using combox.selectedvalue and name using its text value. Now I have a data grid view in which I want to list all the schools which belongs to selected owners with an additional column of owner name that is in the Owner table in data grid view.
I want to do this using Entity Framework.

I have seen many questions here but I didn't find exactly what I need.

A:

Depending on your schema for the database
Try this in event ComboBoxOwner_SelectedIndexChanged()
var selectedOwner = ((Owner)ComboBoxOwner.SelectedItem).Id;

GridViewSchools.DataSource = (from school in DbContext.Schools
                              join owner in DbContext.Owners on school.OwnerId equals owner.Id
                              where school.OwnerId == selectedOwner
                              select new { schoolName= school.Name , OwnerName = owner.Name }).ToList();

you can add all information of school at the same method


Q:

jQuery .get appends an unknown variable to URL

I'm using this code as the starting point to an overhaul of our JavaScript framework:
$("#get").click(function(){
    $("#result").html(ajax_load);
    $.get(
        "http://www.google.com",
        {},
        function(responseText){
            $("#result").html(responseText);
        },
        "html"
    );
});

But when the request is made it includes a variable within the URL that I am unfarmiliar with, here is what Firebug says it's requesting:
http://www.google.com/?_=1268993359215

How do I get rid of this, when we target our internal scripts it's firing a 404 error :-(
Cheers!

A:

That parameter is used to force browser not to use cache.
You can not make $.get work without it explicitly, but you can use $.ajax instead:
$("#get").click(function(){
    $("#result").html(ajax_load);
    $.ajax({
        url: "http://www.google.com",
        data: {},
        success: function(responseText) {
            $("#result").html(responseText);
        },
        cache: true,
        dataType: "html"
    });
});

Note the extra parameter cache: true. More on $.ajax here: http://api.jquery.com/jQuery.ajax/


Q:

Matlab: reshape a vector by permuting?

I have the following vector u:
u=[a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4];

I want to permute the elements of of u to make the following vector, uNew:
uNew=[a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4];

I can think of no way of doing this other than with a for loop:
uNew=[];
for i=1:4
    uNew=[uNew,u(i:4:end)];
end

But I'm hoping that a built-in function exits? Thanks!

A:

Reshape it to a matrix which, read column by column, contains the order you want:
n=3 % number of categories (a,b,c)
u2=reshape(u,[],n).'

then convert it back to a vector:
u2=u2(:);


Q:

How to install ml_finance-master in python 3.6

I download all the files of ml_finance-master from  https://github.com/matplotlib/mpl_finance
Then I extract all the files into D:\Programing\Python\Scripts.
In the CMD I type, C:\Users\84334>D:\Programing\Python\Scripts\pip install mpl_finance.
However, it shows,
Collecting mpl_finance
  Could not find a version that satisfies the requirement mpl_finance (from versions: )
No matching distribution found for mpl_finance
I also tried in CMD, C:\Users\84334>D:\Programing\Python\Scripts\pip install mpl_finance-master
However,it shows,
Could not find a version that satisfies the requirement mpl_finance-master (from versions: )
No matching distribution found for mpl_finance-master
I am totally new to python. Could anyone help me?
Thanks

A:

Github repo for this package contains setup.py file, which based on setuptools. According to documentation you can run terminal (cmd) in directory with setup.py file and write following:
python setup.py install

After that, installation should be performed.


Q:

Reverse engineered code seems to have no point

I am working on reverse engineering some code and am coming across some code that doesn't appear to make sense
For example
push 0x3C2D1C06
mov [esp], ebx
mov[esp], edx
mov dword ptr[esp], 0x7D0B46E7`

Is there logic behind this or is this something that comes from compiler generation.  It occurs to me the this would net the same as
push 0x7D0B46E7
Another example is
pusha
push ecx
pop ecx
pusha
popa
popa
push eax
push edx
rdtsc
pusha
popa
pop edx
pop eax

I dont understand all of the push/pop combinations
EDIT:
I am really intrigued now on the root of this.  I do have to believe that this is one of a few sources:
1.) As mentioned possible that this was done to obscure reverse engineering
2.) Some form of optimization that is over my head(I have a hard time seeing this one)
3.) Some form of compiler action linking possibly multi platform libraries or something
I am convinced that the code is disassembled correctly because the sequences may be odd the do not ever corrupt the stack etc. I am curious about some of the sequences such as
push edi
push eax
push eax
mov eax, 0x577D25CD
mov [esp], eax
push eax
pop edi
and edi, 0x3F7BEBDC
shl edi, 0x3
xor edi, 0x6E778451
sub edi, 0x0D5BE8A31
mov ebx, edi
push [esp]
pop edi

To start with
push edi
push eax
push eax
mov eax, 0x577D25CD
mov [esp], eax
pop eax
pop edi

I believe is the same as writing
push edi
push 0x577D25CD
pop edi

OR even
push edi
mov edi, 0x577D25CD

But even more confusing is what follows,
and edi(0x577D25CD), 0x3F7BEBDC ->edi=0x177921CC
shl edi(0x177921CC), 3 ->edi=0xBBC90E60
xor edi(0xBBC90E0), 0x6e778451 -> edi=0xD5BE8A31
sub edi(0x0D5BE8A31), 0x0D5BE8A31 -> edi=0x0
mov ebx, edi
So that could be replaced with
mov ebx, 0x0 OR xor ebx, ebx
So this leaves me with a few new questions.  Is this point more firmly to a form of reverse engineering protection, are there tools that do this.  Could there be any other logical reasons to execute a stream like this. Is it fair to assume that a compiler would not perform operations to set values below ESP, I have not found indications that any of the values below ESP are used
A couple last points, I have started distilling the code down to just the effective result and so far everything thing works as before and i've removed
over 200bytes of code.  This further points me to the idea that I'm correctly interpreting the code.  I also find it hard to believe incorrectly disassembled code would produce a sequence of xor, and, shl operations that exactly equal 0x00
EDIT 2:
I can assuredly say this is code I am interpreting. I focused in on one section, I posted a portion of it in my first edit and when I sorted through the 86 asm instructions I found the result was simply this
start:
 test ebx, ebx
 jz end
 add [eax], ecx
 add eax, 0x04
 sub ebx, 0x1
 jmp start
end:

The rest was as mentioned before "clobbering" the stack with odd combinations of pushes, pops, xchgs, and arithmetic on the esp.  Sometimes there was something like add esp, 0x4 then mov [esp], eax which is the same as push eax  In the end the section I worked through was offsetting an array of addresses by the Image_Base, a form of relocation I guess. When I peek the relocated addresses they point to code segments and what looks like the start of procedures.  I have a hard time seeing someone writing the thousands of lines of code that appear to do this which makes me wonder..
Does anyone know of a tool that does this.  Has someone created a program that takes code and obscures it with nonsense to prevent reverse engineering.

A:

The most plausible source of these instruction-sequences is that they're hand-crafted as obfuscation, possibly in inline-asm.
As I commented earlier, if that's the case then this code is working exactly as intended: it's confused / puzzled you and caused you to spend significant time on it instead of just reverse-engineering the actual program logic.

The fact that none of these sequences crash or mess up the stack is a clear sign that it's definitely not accidental execution of data as code.
Your test of actually setting breakpoints in this code to see that it was actually executed was useful here, too.  It's not uncommon for disassembly output to include some data stored in code sections.  But seeing that it is executed, we know it's not just data.

2.) Some form of optimization that is over my head(I have a hard time seeing this one)

You are right to be skeptical of this idea, but yes you always need to consider that possibility.
Sometimes sub-optimal code exists because someone thought it would be fast, at least on some specific CPU.  But that's not even plausible here.  I can't believe anyone would think these long convoluted sequences would be faster on any x86 CPU than xor ebx,ebx, push imm32, or mov r32, imm32.  Those instructions are all fast on their own, and the sequence that's equivalent to push imm32 actually uses a push imm32 + some dead stores, so it's clearly not trying to avoid push imm32 for some hypothetical CPU where that instruction is slow.
Especially in the NOP case, zero instructions is always better.  If you need padding, Intel and AMD publish recommended long-NOP sequences that have minimal overhead.  pusha / popa are slow on everything, and it's pretty obvious they do a lot of work, so it doesn't make sense that someone would intentionally use them as padding.

Other than obfuscation, the other plausible purpose is intentional delay.  That's sort of a performance reason, but if timing is part of the correctness of your program, fixed sequences like this are not a reliable way to achieve it across a range of different x86 microarchitectures!
But I could believe that some / all of these were a bad implementation of "waste several cycles here".  Especially pusha / popa takes a lot of time in few instruction bytes.

Does anyone know of a tool that does this. Has someone created a program that takes code and obscures it with nonsense to prevent reverse engineering.

Good question.  Inserting crazy NOPs or turning push imm32 or xor-zeroing into obfuscated sequences is something a tool could maybe do automatically.  But usually you'd want to avoid that inside any loops that are actually important for overall performance, so IDK.


Q:

How to dim the background behind my pop up menu after clicking a button?

How do I get the background behind my pop up menu to dim after I click the button that opens the popup menu? Looked at other code samples but no luck! Would really appreciate any advice!
final Button Bel = (Button) findViewById(R.id.btnBel);
    final ImageView Phone = (ImageView)findViewById(R.id.imgPhone);
    relativeLayout = (RelativeLayout) findViewById(R.id.relative);

    Bel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Bel.setVisibility(View.GONE);
            Phone.setVisibility(View.GONE);

            layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup_menu, null);

            popupWindow = new PopupWindow(container, 1000, 850, true);
            popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 221, 4000);

            btnBelNuCall = (Button) container.findViewById(R.id.btnBelNu);
            btnClosePopUp = (Button) container.findViewById(R.id.btnAnnuleren);

            btnBelNuCall.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:0900-33-44-55-6"));
                    startActivity(callIntent);
                    checkPermission();
                }
            });

            btnClosePopUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    Bel.setVisibility(View.VISIBLE);
                    Phone.setVisibility(View.VISIBLE);
                }
            });

        }
    });

A:

1. Create A Layout That Covers Everything In Your Main Layout
I don't know what your XML File looks like, but put something like this at the top of it:
<LinearLayout android:id="dim_layout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#70000000"
   android:visibility="invisible"/>

Note: Depending on your XML file, you may need to alter this for it to be placed on top of all other components.
This will create a layout covering everything in your main layout with a background of color #70000000 which is black with an alpha level of 70. Changing the 70 at the beginning of the hex code will allow you to modify how transparent you want it to be.
2. Show Layout When Popup Is Activated
LinearLayout dim_layout = (LinearLayout) findViewById(R.id.dim_layout);
popupWindow = new PopupWindow(container, 1000, 850, true);
dim_layout.setVisibility(View.VISIBLE);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 221, 4000);

3. Hide Layout When Popup Is Deactivated
btnClosePopUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        popupWindow.dismiss();
        Bel.setVisibility(View.VISIBLE);
        Phone.setVisibility(View.VISIBLE);
        dim_layout.setVisibility(View.INVISIBLE);
    }
});


Q:

android keyboard with different language

How to print urdu font in editbox while user press any button of the softkeyboard?
I want to create urdu keyboard. I have made lots of research on that. I found the solutions. but I couldn't found the way that how to print urdu fonts in editbox when user type? I know about keyboard.xml and other things.
Thanks.

A:

It's very simple. Just need to add unicode as android:codes and it will print that particular char in edittext.
        android:codes="0x0AE7"
        android:keyLabel="2"


Q:

Pandas - looping through columns of a dataframe and join this column with other dataframe

I have a DataFrame (df1)
index abc bcd def
20150101 0.5 0.3 0.2
20150102 0.7 0.9 1.6
20150103 1.7 2.9 4.6
.................

second dataframe (df2)
index a b c ...(about 100 columns)
0 0 1 8 ...
1 9 5 3 ...
2 2 3 7 ..

I would like to loop through each column in 2nd dataframe and need to form a dataframe in every loop like
 index abc bcd def col
 20150101 0.5 0.3 0.2 0
 20150102 0.7 0.9 1.6 9
 20150103 1.7 2.9 4.6 2

and need to work on this new dataframe for other calculations
I am running this,
    for col in df2.iteritems():
        df1['new_col'] = col

with error: ValueError: Length of values does not match length of index
If I form a series from col as in
    for col in df2.iteritems():
        c = col[1].astype(float)
        s = pd.Series(c)
         dfb['col'] = s

gives
index abc bcd def col
20150101 0.5 0.3 0.2 NaN
20150102 0.7 0.9 1.6 NaN
20150103 1.7 2.9 4.6 NaN

please suggest a solution. Thanks in Advance!

A:

I think you can try concat:
for col in df2.columns:
    print pd.concat([df1.reset_index(),df2[col]], axis=1)

      index  abc  bcd  def  a
0  20150101  0.5  0.3  0.2  0
1  20150102  0.7  0.9  1.6  9
2  20150103  1.7  2.9  4.6  2
      index  abc  bcd  def  b
0  20150101  0.5  0.3  0.2  1
1  20150102  0.7  0.9  1.6  5
2  20150103  1.7  2.9  4.6  3
      index  abc  bcd  def  c
0  20150101  0.5  0.3  0.2  8
1  20150102  0.7  0.9  1.6  3
2  20150103  1.7  2.9  4.6  7

EDIT:
IIUC you need select only DataFrames, where in last column is at least one value 1, use any:
dfs = {}

for col in df2.columns:
    df = pd.concat([df1.reset_index(),df2[col]], axis=1)
    #print df
    if (df2[col] == 1).any():
        print df
        #storing in dictionary of dataframes
        dfs[col] = df
      index  abc  bcd  def  b
0  20150101  0.5  0.3  0.2  1
1  20150102  0.7  0.9  1.6  5
2  20150103  1.7  2.9  4.6  3

print dfs['b']
      index  abc  bcd  def  b
0  20150101  0.5  0.3  0.2  1
1  20150102  0.7  0.9  1.6  5
2  20150103  1.7  2.9  4.6  3


Q:

How does the typedef struct work syntactically?

I am new to this, so I apologize if I'm being dense. I'm having trouble understanding how to use typedef. Let's say I have the following command:
typedef struct {
    char pseudo[MAX_SIZE] ;
    int nb_mar ;
    } player ;

This creates a type called player which comprises of a chain of characters, and an int, correct?
Now, if we have this line of code:
struct set_of_players {
    player T[NB_MAX_JOUEURS] ;
    int nb ;
    };

I don't understand what this does? I would assume it creates a variable of type struct set_of_players, but what is it called? Usually when I see this kind of command, there's a word after the closed amplesand representing the variables name, but here it has nothing; I don't get it. Would this even work if I haven't done a typedef struct for set_of_players?
Finally, I have this line of code that I don't understand:
typedef struct set_of_players players;

I quite honestly have no idea what this even means. I'm assuming this is the typedef that I need to make the previous command make sense, but I don't even know what it does.
Again, I'm sorry if I'm looking at this the wrong way, and for the poor formatting. Any help would be greatly appreciated, thank you.

A:

The typedef statement allows you to make an alias for the given type.  You can then use either the alias or the original type name to declare a variable of that type.
typedef int number;

This creates an alias for int called number.  So the following two statements declare variables of the same type:
int num1;
number num2;

Now using your example:
typedef struct {
    char pseudo[MAX_SIZE] ;
    int nb_mar ;
} player ;

This creates an anonymous struct and gives it the alias player.  Because the struct doesn't have name, you can only use the alias to create a variable of that type.
struct set_of_players {
    player T[NB_MAX_JOUEURS] ;
    int nb ;
};

This creates a struct named struct set_of_players, but does not declare a typedef nor does it declare a variable of that type.  Also notice that one of the fields is an array of type player, which we defined earlier.  You can later declare a variable of this type as follows:
struct set_of_players my_set_var;

This line:
typedef struct set_of_players players;

Creates an alias for struct set_of_players called players.  In this case the struct is not defined at the same time as the typedef but is defined elsewhere.  So now you can declare a variable of this type like this:
players my_set_var;

Which is the same as the version using the full struct name.


Q:

How to insert empty_clob() from java to Oracle

I am having an NCLOB column in oracle. When I create a row, I need to insert an empty_clob() using normal java insert query.
Does anyone know how this is done? I am looking for something like the one below from java.
INSERT INTO MY_TABLE VALUES(1,'Abraham','empty_clob');
Thanks and Regards,
Abraham Menacherry

A:

You should correct your insert statement:
INSERT INTO MY_TABLE VALUES(1,'Abraham',empty_clob());

You should also take a look here.
The empty_clob function is also useful as default value for the clob column.


Q:

How to validate a signature in Java if the public key's algorithm is EC?

Given an X509 certificate object of a person. (The object's type is sun.security.x509.X509CertImpl). This person signed a String with his private key. Given the signature that was made by this person, when he signed the above mentioned String object.
My task is to verify this signature, but have difficulties with it.
When I try to verify the signature with the below code:
    ...
    X509Certificate x509Certificate = getCertificate(certificate);

    Signature signature = Signature.getInstance("SHA256withECDSA");

    signature.initVerify(x509Certificate.getPublicKey());

    signature.update(unsignedData);
    boolean bool = signature.verify(signatureToVerify);
    System.out.println("The signature is " + (bool ? "" : "NOT") + " valid");

I get java.security.SignatureException: Could not verify signature
Do you have an idea, how can I make it working?
Edited:
At the end, I managed to make it working, but do not understand the reason yet:
Before passing the signature to the verify method, i needed to do the following modification on it:
    byte[] rBytes = Arrays.copyOfRange(signatureHash, 0, 32);
    byte[] sBytes = Arrays.copyOfRange(signatureHash, 32, 64);

    BigInteger r = new BigInteger(1, rBytes);
    BigInteger s = new BigInteger(1, sBytes);

    ASN1Integer asn1R = new ASN1Integer(r);
    ASN1Integer asn1S = new ASN1Integer(s);

    DERSequence seq = new DERSequence(new ASN1Integer[]{asn1R, asn1S});
    byte[] signatureToVerify2 = seq.getEncoded();
    // verifying the signatureToVerify2 instead of the original brings success
    boolean bool = signature.verify(signatureToVerify2);

A:

Here is a (semi)working app for further reference that verifies a signature, when ECDSA is involved in the story:
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequence;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;

public class SignatureTest {

    public static void main(String[] args) throws CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
        byte[] certificateAsByteArray = ...;
        byte[] dataToVerifyAsByteArray = ...;
        byte[] signatureHashAsByteArray = ...;

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(certificateBytes);
        X509Certificate x509Certificate = (X509Certificate) certFactory.generateCertificate(in);

        Signature signature = Signature.getInstance("SHA256withECDSA");

        signature.initVerify(x509Certificate.getPublicKey());

        signature.update(dataToVerifyAsHexaString);

        byte[] rBytes = Arrays.copyOfRange(signatureHash, 0, 32);
        byte[] sBytes = Arrays.copyOfRange(signatureHash, 32, 64);

        ASN1Integer asn1R = new ASN1Integer(rBytes);
        ASN1Integer asn1S = new ASN1Integer(sBytes);

        DERSequence seq = new DERSequence(new ASN1Integer[] {asn1R, asn1S});

        boolean isSignatureOK = signature.verify(seq.getEncoded());

        System.out.println("The signature is " + (isSignatureOK ? "" : "NOT ") + "VALID");
    }
}