Programs & Examples On #Multicore

Multicore programming covers techniques for making programs run in parallel, by exploiting hardware with multiple processing cores.

Compiling with g++ using multiple cores

If using make, issue with -j. From man make:

  -j [jobs], --jobs[=jobs]
       Specifies the number of jobs (commands) to run simultaneously.  
       If there is more than one -j option, the last one is effective.
       If the -j option is given without an argument, make will not limit the
       number of jobs that can run simultaneously.

And most notably, if you want to script or identify the number of cores you have available (depending on your environment, and if you run in many environments, this can change a lot) you may use ubiquitous Python function cpu_count():

https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count

Like this:

make -j $(python3 -c 'import multiprocessing as mp; print(int(mp.cpu_count() * 1.5))')

If you're asking why 1.5 I'll quote user artless-noise in a comment above:

The 1.5 number is because of the noted I/O bound problem. It is a rule of thumb. About 1/3 of the jobs will be waiting for I/O, so the remaining jobs will be using the available cores. A number greater than the cores is better and you could even go as high as 2x.

How do I measure separate CPU core usage for a process?

htop gives a nice overview of individual core usage

Android activity life cycle - what are all these methods for?

Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):

Source: developer.android.com

enter image description here

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.

onPostCreate(Bundle savedInstanceState)

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).

onPostResume()

Called when activity resume is complete (after onResume() has been called).

onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

onRestoreInstanceState(Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

My application code using all these methods:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(R.id.username);
        txtPassword=(EditText) findViewById(R.id.password);
        loginButton =  (Button)  findViewById(R.id.login);
        loginButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName",txtUserName.getText().toString());
        bundle.putString("password",txtPassword.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
       // IntentFilter
    }
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(R.id.txtView);
        txtView.setText(result);

        Intent sendIntent = new Intent();
        //sendIntent.setPackage("com.whatsapp");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Ravi","Main Start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Ravi","Main ReStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Ravi","Main Pause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Ravi","Main Resume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Ravi","Main Stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Ravi","Main OnDestroy");
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("Ravi","Main PostResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

Login Activity:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        txtView = (TextView) findViewById(R.id.Result);
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
        intent.putExtra("result","Success");
        setResult(1,intent);
       // finish();
    }
}

output: ( Before pause)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

output: ( After resume from pause)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

Note that onPostResume() is invoked even though it's not quoted as life cycle method.

Where to get this Java.exe file for a SQL Developer installation

you should browse to where java installed, then go to bin directory which contains the java.exe file.

example - C:\Program Files\Java\jdk1.6.0_03\bin\java.exe

but you should run your SQL Developer as Administrator

How do I create a folder in VB if it doesn't exist?

Try the System.IO.DirectoryInfo class.

The sample from MSDN:

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

How can I validate google reCAPTCHA v2 using javascript/jQuery?

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.

 let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
    'callback': function(response) {
        recaptchVerified = true;
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        // ...
    },
    'expired-callback': function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
    }
});

Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.

So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

I had to add the following i386 and x86_64 to Valid Architectures. I'm running Xcode 7.2 and targeting iOS 8+. I already had armv7, armv7s and arm64 in there and that was working in Xcode 6.4.

How can I clear previous output in Terminal in Mac OS X?

To delete the last output only:

? + L

To clear the terminal completely:

? + K

python: how to identify if a variable is an array or a scalar

Since the general guideline in Python is to ask for forgiveness rather than permission, I think the most pythonic way to detect a string/scalar from a sequence is to check if it contains an integer:

try:
    1 in a
    print('{} is a sequence'.format(a))
except TypeError:
    print('{} is a scalar or string'.format(a))

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JVM does not find java.exe. It doesn't even call it. java.exe is called by the operating system (Windows in this case).

JAVA_HOME is just a convention, usually used by Tomcat, other Java EE app servers and build tools such as Gradle to find where Java lives.

The important thing from your point of view is that the Java /bin directory be on your PATH so Windows can find the .exe tools that ship with the JDK: javac.exe, java.exe, jar.exe, etc.

.htaccess not working on localhost with XAMPP

For windows user, make sure to closely look at this section.

RewriteRule ^properties$ /property_available.php/$1 [NC,QSA]

As said in Apache documentation :

The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly.

So ^properties$ means Apache will only look for URL that has exact match with properties. You might want to try this code.

RewriteRule properties /property_available.php/$1 [NC,QSA]

So Apache will see the URL that has properties and rewrite it to /property_available.php/

Build and Install unsigned apk on device without the development server?

After you follow the first response, you can run your app using

react-native run-android --variant=debug

And your app will run without need for the packager

Causes of getting a java.lang.VerifyError

Well in my case, my project A had a dependency on another, say X(A was using some of the classes defined in X). So when I added X as a reference project in the build path of A , I got this error. However when I removed X as the referenced project and included X's jar as one of the libraries, the problem was solved.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Follow the steps below in Oracle VM VirtualBox Manager:

  1. Select the Virtual device and choose Settings
  2. Navigate to System and click the Processor tab
  3. Tick the check-box, Enable PAE/NX
  4. Click OK and you are done

To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.

Close this device and open it from Genymotion.

Code for a simple JavaScript countdown timer?

_x000D_
_x000D_
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Nov 13 2017 22:05:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
  now = new Date();_x000D_
  seconds = (theevent - now) / 1000;_x000D_
  seconds = Math.round(seconds);_x000D_
  minutes = seconds / 60;_x000D_
  minutes = Math.round(minutes);_x000D_
  hours = minutes / 60;_x000D_
  hours = Math.round(hours);_x000D_
  days = hours / 24;_x000D_
  days = Math.round(days);_x000D_
  document.form1.days.value = days;_x000D_
  document.form1.hours.value = hours;_x000D_
  document.form1.minutes.value = minutes;_x000D_
  document.form1.seconds.value = seconds;_x000D_
  ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
  <p>Days_x000D_
    <input type="text" name="days" value="0" size="3">Hours_x000D_
    <input type="text" name="hours" value="0" size="4">Minutes_x000D_
    <input type="text" name="minutes" value="0" size="7">Seconds_x000D_
    <input type="text" name="seconds" value="0" size="7">_x000D_
  </p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Connect to Amazon EC2 file directory using Filezilla and SFTP

Just one minor note to the well explained accepted answer of Yasitha Chinthaka:

Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

In my case I already had other 5 ppks from other instances that I was using in the past (with the ppk of the new instance being at the bottom of that list). I added the new ppk of my new instance, and it wouldn't let me connect to it. The error message: too many tries / attempts.

After I deleted the unused ppks, I was finally able to login to the instance.

So no, Filezilla is not that smart ;-)

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

ProgressDialog in AsyncTask

Fixed by moving the view modifiers to onPostExecute so the fixed code is :

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        new ProgressTask(Soirees.this).execute();


   }


    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        List<Message> titles;
        private ListActivity activity;
        //private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }



        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

            @Override
        protected void onPostExecute(final Boolean success) {
                List<Message> titles = new ArrayList<Message>(messages.size());
                for (Message msg : messages){
                    titles.add(msg);
                }
                MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                activity.setListAdapter(adapter);
                adapter.notifyDataSetChanged();

                if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try{    
                BaseFeedParser parser = new BaseFeedParser();
                messages = parser.parse();


                return true;
             } catch (Exception e){
                Log.e("tag", "error", e);
                return false;
             }
          }


    }

}

@Vladimir, thx your code was very helpful.

How to vertically center a <span> inside a div?

To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.

MySQL Removing Some Foreign keys

Check what's the CONSTRAINT name and the FOREIGN KEY name:

SHOW CREATE TABLE table_name;

Remove both the CONSTRAINT name and the FOREIGN KEY name:

ALTER TABLE table_name
  DROP FOREIGN KEY the_name_after_CONSTRAINT,
  DROP KEY the_name_after_FOREIGN_KEY;

Hope this helps!

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

You can use bootstrap 3 classes and build a table using the ng-repeat directive

Example:

_x000D_
_x000D_
angular.module('App', []);_x000D_
_x000D_
function ctrl($scope) {_x000D_
    $scope.items = [_x000D_
        ['A', 'B', 'C'],_x000D_
        ['item1', 'item2', 'item3'],_x000D_
        ['item4', 'item5', 'item6']_x000D_
    ];_x000D_
}
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="App">_x000D_
  <div ng-controller="ctrl">_x000D_
    _x000D_
    _x000D_
    <table class="table table-bordered">_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th ng-repeat="itemA in items[0]">{{itemA}}</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemB in items[1]">{{itemB}}</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemC in items[2]">{{itemC}}</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
    _x000D_
    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

live example: http://jsfiddle.net/choroshin/5YDJW/5/

Update:

or you can always try the popular ng-grid , ng-grid is good for sorting, searching, grouping etc, but I haven't tested it yet on a large scale data.

Scala Doubles, and Precision

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).

If Browser is Internet Explorer: run an alternative script instead

var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { document.write("Your html for IE") }

How does one target IE7 and IE8 with valid CSS?

The actual problem is not IE8, but the hacks that you use for earlier versions of IE.

IE8 is pretty close to be standards compliant, so you shouldn't need any hacks at all for it, perhaps only some tweaks. The problem is if you are using some hacks for IE6 and IE7; you will have to make sure that they only apply to those versions and not IE8.

I made the web site of our company compatible with IE8 a while ago. The only thing that I actually changed was adding the meta tag that tells IE that the pages are IE8 compliant...

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

adding noise to a signal in python

AWGN Similar to Matlab Function

def awgn(sinal):
    regsnr=54
    sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
    sigpower=sigpower/len(sinal)
    noisepower=sigpower/(math.pow(10,regsnr/10))
    noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
    return noise

How to use the 'og' (Open Graph) meta tag for Facebook share

I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com

To answer the question a bit more, OG tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

How do you UDP multicast in Python?

This works for me:

Receive

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
IS_ALL_GROUPS = True

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
    # on this port, receives ALL multicast groups
    sock.bind(('', MCAST_PORT))
else:
    # on this port, listen ONLY to MCAST_GRP
    sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"
  print sock.recv(10240)

Send

import socket

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
# regarding socket.IP_MULTICAST_TTL
# ---------------------------------
# for all packets sent, after two hops on the network the packet will not 
# be re-sent/broadcast (see https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html)
MULTICAST_TTL = 2

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)

# For Python 3, change next line to 'sock.sendto(b"robot", ...' to avoid the
# "bytes-like object is required" msg (https://stackoverflow.com/a/42612820)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

It is based off the examples from http://wiki.python.org/moin/UdpCommunication which didn't work.

My system is... Linux 2.6.31-15-generic #50-Ubuntu SMP Tue Nov 10 14:54:29 UTC 2009 i686 GNU/Linux Python 2.6.4

From inside of a Docker container, how do I connect to the localhost of the machine?

For macOS and Windows

Docker v 18.03 and above (since March 21st 2018)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

Linux support pending https://github.com/docker/for-linux/issues/264

MacOS with earlier versions of Docker

Docker for Mac v 17.12 to v 18.02

Same as above but use docker.for.mac.host.internal instead.

Docker for Mac v 17.06 to v 17.11

Same as above but use docker.for.mac.localhost instead.

Docker for Mac 17.05 and below

To access host machine from the docker container you must attach an IP alias to your network interface. You can bind whichever IP you want, just make sure you're not using it to anything else.

sudo ifconfig lo0 alias 123.123.123.123/24

Then make sure that you server is listening to the IP mentioned above or 0.0.0.0. If it's listening on localhost 127.0.0.1 it will not accept the connection.

Then just point your docker container to this IP and you can access the host machine!

To test you can run something like curl -X GET 123.123.123.123:3000 inside the container.

The alias will reset on every reboot so create a start-up script if necessary.

Solution and more documentation here: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

Load an image from a url into a PictureBox

yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

Django, creating a custom 500/404 error page

Add these lines in urls.py

urls.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

and implement our custom views in views.py.

views.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

Hive cast string to date dd-MM-yyyy

try:

from_unixtime(unix_timestamp('12-03-2010' , 'dd-MM-yyyy'))

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.

Callback functions in Java

I found the idea of implementing using the reflect library interesting and came up with this which I think works quite well. The only down side is losing the compile time check that you are passing valid parameters.

public class CallBack {
    private String methodName;
    private Object scope;

    public CallBack(Object scope, String methodName) {
        this.methodName = methodName;
        this.scope = scope;
    }

    public Object invoke(Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Method method = scope.getClass().getMethod(methodName, getParameterClasses(parameters));
        return method.invoke(scope, parameters);
    }

    private Class[] getParameterClasses(Object... parameters) {
        Class[] classes = new Class[parameters.length];
        for (int i=0; i < classes.length; i++) {
            classes[i] = parameters[i].getClass();
        }
        return classes;
    }
}

You use it like this

public class CallBackTest {
    @Test
    public void testCallBack() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        TestClass testClass = new TestClass();
        CallBack callBack = new CallBack(testClass, "hello");
        callBack.invoke();
        callBack.invoke("Fred");
    }

    public class TestClass {
        public void hello() {
            System.out.println("Hello World");
        }

        public void hello(String name) {
            System.out.println("Hello " + name);
        }
    }
}

How to implement a Keyword Search in MySQL?

You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches

This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.

Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching

In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:

SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance  FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;

I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.

Depending in your criterias you can use either options.

Flexbox not giving equal width to elements

There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

From the spec:

If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

li {
    flex-grow: 1;
    flex-basis: 0;
    /* ... */
}

This diagram from the spec does a pretty good job of illustrating the point.

And here is a working example with your fiddle.

Using custom std::set comparator

You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

struct lex_compare {
    bool operator() (const int64_t& lhs, const int64_t& rhs) const {
        stringstream s1, s2;
        s1 << lhs;
        s2 << rhs;
        return s1.str() < s2.str();
    }
};

You then use the class name as the type parameter

set<int64_t, lex_compare> s;

If you want to avoid the functor boilerplate code you can also use a function pointer (assuming lex_compare is a function).

set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);

Proper way to use **kwargs in Python

Here's another approach:

def my_func(arg1, arg2, arg3):
    ... so something ...

kwargs = {'arg1': 'Value One', 'arg2': 'Value Two', 'arg3': 'Value Three'}
# Now you can call the function with kwargs like this:

my_func(**kwargs)

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

Using an integer as a key in an associative array in JavaScript

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

Add jars to a Spark Job - spark-submit

Another approach in spark 2.1.0 is to use --conf spark.driver.userClassPathFirst=true during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars option.

Including a groovy script in another groovy

Groovy doesn't have an import keyword like typical scripting languages that will do a literal include of another file's contents (alluded to here: Does groovy provide an include mechanism?).
Because of its object/class oriented nature, you have to "play games" to make things like this work. One possibility is to make all your utility functions static (since you said they don't use objects) and then perform a static import in the context of your executing shell. Then you can call these methods like "global functions".
Another possibility would be using a Binding object (http://groovy.codehaus.org/api/groovy/lang/Binding.html) while creating your Shell and binding all the functions you want to the methods (the downside here would be having to enumerate all methods in the binding but you could perhaps use reflection). Yet another solution would be to override methodMissing(...) in the delegate object assigned to your shell which allows you to basically do dynamic dispatch using a map or whatever method you'd like.

Several of these methods are demonstrated here: http://www.nextinstruction.com/blog/2012/01/08/creating-dsls-with-groovy/. Let me know if you want to see an example of a particular technique.

How to set an iframe src attribute from a variable in AngularJS

It is the $sce service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.

You can disable it completely, but it's not recommended

angular.module('myAppWithSceDisabledmyApp', [])
   .config(function($sceProvider) {
       $sceProvider.enabled(false);
   });

for more info https://docs.angularjs.org/api/ng/service/$sce

How do I add a submodule to a sub-directory?

I had a similar issue, but had painted myself into a corner with GUI tools.

I had a subproject with a few files in it that I had so far just copied around instead of checking into their own git repo. I created a repo in the subfolder, was able to commit, push, etc just fine. But in the parent repo the subfolder wasn't treated as a submodule, and its files were still being tracked by the parent repo - no good.

To get out of this mess I had to tell Git to stop tracking the subfolder (without deleting the files):

proj> git rm -r --cached ./ui/jslib

Then I had to tell it there was a submodule there (which you can't do if anything there is currently being tracked by git):

proj> git submodule add ./ui/jslib

Update

The ideal way to handle this involves a couple more steps. Ideally, the existing repo is moved out to its own directory, free of any parent git modules, committed and pushed, and then added as a submodule like:

proj> git submodule add [email protected]:user/jslib.git ui/jslib

That will clone the git repo in as a submodule - which involves the standard cloning steps, but also several other more obscure config steps that git takes on your behalf to get that submodule to work. The most important difference is that it places a simple .git file there, instead of a .git directory, which contains a path reference to where the real git dir lives - generally at parent project root .git/modules/jslib.

If you don't do things this way they'll work fine for you, but as soon as you commit and push the parent, and another dev goes to pull that parent, you just made their life a lot harder. It will be very difficult for them to replicate the structure you have on your machine so long as you have a full .git dir in a subfolder of a dir that contains its own .git dir.

So, move, push, git add submodule, is the cleanest option.

Right align and left align text in same HTML table cell

Tor Valamo's answer with a little contribution form my side: use the attribute "nowrap" in the "td" element, and you can remove the "width" specification. Hope it helps.

<td nowrap>
  <div style="float:left;">this is left</div>
  <div style="float:right;">this is right</div>
</td>

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

__proto__ VS. prototype in JavaScript

Prototype or Object.prototype is a property of an object literal. It represents the Object prototype object which you can override to add more properties or methods further along the prototype chain.

__proto__ is an accessor property (get and set function) that exposes the internal prototype of an object thru which it is accessed.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
  2. http://www.w3schools.com/js/js_object_prototypes.asp

  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

make a header full screen (width) css

Live Demo

You can achieve the effect using a container element, then just set the containing elements margin to 0 auto and it will be centered.

Markup

<div id="header">
    <div id="headerContent">
        Header text
    </div>
</div>

CSS

#header{
    width:100%; 
    background: url(yourimage);
}
#headerContent{
    margin: 0 auto; width: 960px;
}

How do I convert a datetime to date?

Answer updated to Python 3.7 and more

Here is how you can turn a date-and-time object

(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)

into a date object (aka datetime.date object):

from datetime import datetime

#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)

# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)

# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()

And just to be clear, if you print those elements, here is the output :

print(datetime_element)

2020-07-10 12:56:54.324893


print(date_element)

2020-07-10

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

Is there a way to use PhantomJS in Python?

PhantomJS recently dropped Python support altogether. However, PhantomJS now embeds Ghost Driver.

A new project has since stepped up to fill the void: ghost.py. You probably want to use that instead:

from ghost import Ghost
ghost = Ghost()

with ghost.start() as session:
    page, extra_resources = ghost.open("http://jeanphi.me")
    assert page.http_status==200 and 'jeanphix' in ghost.content

How to use makefiles in Visual Studio?

A UNIX guy probably told you that. :)

You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.

Implement Validation for WPF TextBoxes

There a 3 ways to implement validation:

  1. Validation Rule
  2. Implementation of INotifyDataErrorInfo
  3. Implementation of IDataErrorInfo

Validation rule example:

public class NumericValidationRule : ValidationRule
{
    public Type ValidationType { get; set; }
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string strValue = Convert.ToString(value);

        if (string.IsNullOrEmpty(strValue))
            return new ValidationResult(false, $"Value cannot be coverted to string.");
        bool canConvert = false;
        switch (ValidationType.Name)
        {

            case "Boolean":
                bool boolVal = false;
                canConvert = bool.TryParse(strValue, out boolVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean");
            case "Int32":
                int intVal = 0;
                canConvert = int.TryParse(strValue, out intVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32");
            case "Double":
                double doubleVal = 0;
                canConvert = double.TryParse(strValue, out doubleVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double");
            case "Int64":
                long longVal = 0;
                canConvert = long.TryParse(strValue, out longVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64");
            default:
                throw new InvalidCastException($"{ValidationType.Name} is not supported");
        }
    }
}

XAML:

Very important: don't forget to set ValidatesOnTargetUpdated="True" it won't work without this definition.

 <TextBox x:Name="Int32Holder"
         IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}"
         Style="{StaticResource ValidationAwareTextBoxStyle}"
         VerticalAlignment="Center">
    <!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"-->
    <TextBox.Text>
        <Binding Path="Name"
                 Mode="TwoWay"
                 UpdateSourceTrigger="PropertyChanged"
                 Converter="{cnv:TypeConverter}"
                 ConverterParameter="Int32"
                 ValidatesOnNotifyDataErrors="True"
                 ValidatesOnDataErrors="True"
                 NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}"
                                                       ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <!--NumericValidationRule-->
</TextBox>

INotifyDataErrorInfo example:

public abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        ValidateAsync();
    }
    #endregion


    public virtual void OnLoaded()
    {
    }

    #region INotifyDataErrorInfo
    private ConcurrentDictionary<string, List<string>> _errors = new ConcurrentDictionary<string, List<string>>();

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public void OnErrorsChanged(string propertyName)
    {
        var handler = ErrorsChanged;
        if (handler != null)
            handler(this, new DataErrorsChangedEventArgs(propertyName));
    }

    public IEnumerable GetErrors(string propertyName)
    {
        List<string> errorsForName;
        _errors.TryGetValue(propertyName, out errorsForName);
        return errorsForName;
    }

    public bool HasErrors
    {
        get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
    }

    public Task ValidateAsync()
    {
        return Task.Run(() => Validate());
    }

    private object _lock = new object();
    public void Validate()
    {
        lock (_lock)
        {
            var validationContext = new ValidationContext(this, null, null);
            var validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(this, validationContext, validationResults, true);

            foreach (var kv in _errors.ToList())
            {
                if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
                {
                    List<string> outLi;
                    _errors.TryRemove(kv.Key, out outLi);
                    OnErrorsChanged(kv.Key);
                }
            }

            var q = from r in validationResults
                    from m in r.MemberNames
                    group r by m into g
                    select g;

            foreach (var prop in q)
            {
                var messages = prop.Select(r => r.ErrorMessage).ToList();

                if (_errors.ContainsKey(prop.Key))
                {
                    List<string> outLi;
                    _errors.TryRemove(prop.Key, out outLi);
                }
                _errors.TryAdd(prop.Key, messages);
                OnErrorsChanged(prop.Key);
            }
        }
    }
    #endregion

}

View Model Implementation:

public class MainFeedViewModel : BaseViewModel//, IDataErrorInfo
{
    private ObservableCollection<FeedItemViewModel> _feedItems;
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FeedItems
    {
        get
        {
            return _feedItems;
        }
        set
        {
            _feedItems = value;
            OnPropertyChanged("FeedItems");
        }
    }
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FilteredFeedItems
    {
        get
        {
            if (SearchText == null) return _feedItems;

            return new ObservableCollection<FeedItemViewModel>(_feedItems.Where(x => x.Title.ToUpper().Contains(SearchText.ToUpper())));
        }
    }

    private string _title;
    [Required]
    [StringLength(20)]
    //[CustomNameValidationRegularExpression(5, 20)]
    [CustomNameValidationAttribute(3, 20)]
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            OnPropertyChanged("Title");
        }
    }
    private string _url;
    [Required]
    [StringLength(200)]
    [Url]
    //[CustomValidation(typeof(MainFeedViewModel), "UrlValidation")]
    /// <summary>
    /// Validation of URL should be with custom method like the one that implemented below, or with 
    /// </summary>
    public string Url
    {
        get { return _url; }
        set
        {
            _url = value;
            OnPropertyChanged("Url");
        }
    }

    public MainFeedViewModel(string url, string title)
    {
        Title = title;
        Url = url;
    }
    /// <summary>
    /// 
    /// </summary>
    public MainFeedViewModel()
    {

    }
    public MainFeedViewModel(ObservableCollection<FeedItemViewModel> feeds)
    {
        _feedItems = feeds;
    }


    private string _searchText;
    [XmlIgnore]
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value;

            OnPropertyChanged("SearchText");
            OnPropertyChanged("FilteredFeedItems");
        }
    }

    #region Data validation local
    /// <summary>
    /// Custom URL validation method
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ValidationResult UrlValidation(object obj, ValidationContext context)
    {
        var vm = (MainFeedViewModel)context.ObjectInstance;
        if (!Uri.IsWellFormedUriString(vm.Url, UriKind.Absolute))
        {
            return new ValidationResult("URL should be in valid format", new List<string> { "Url" });
        }
        return ValidationResult.Success;
    }

    #endregion
}

XAML:

<UserControl x:Class="RssReaderTool.Views.AddNewFeedDialogView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300"
             d:DesignWidth="300">
    <FrameworkElement.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate x:Name="TextErrorTemplate">
                        <DockPanel LastChildFill="True">
                            <AdornedElementPlaceholder>
                                <Border BorderBrush="Red"
                                        BorderThickness="2" />
                            </AdornedElementPlaceholder>
                            <TextBlock FontSize="20"
                                       Foreground="Red">*?*</TextBlock>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="True">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource=
            {x:Static RelativeSource.Self},
            Path=(Validation.Errors)[0].ErrorContent}"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
        <!--<Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>-->
    </FrameworkElement.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock Text="Feed Name"
                   ToolTip="Display" />
        <TextBox Text="{Binding MainFeedViewModel.Title,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2" />

        <TextBlock Text="Feed Url"
                   Grid.Row="2" />
        <TextBox Text="{Binding MainFeedViewModel.Url,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2"
                 Grid.Row="2" />
    </Grid>
</UserControl>

IDataErrorInfo:

View Model:

public class OperationViewModel : ViewModelBase, IDataErrorInfo
{
    private const int ConstCodeMinValue = 1;
    private readonly IEventAggregator _eventAggregator;
    private OperationInfoDefinition _operation;
    private readonly IEntityFilterer _contextFilterer;
    private OperationDescriptionViewModel _description;

    public long Code
    {
        get { return _operation.Code; }
        set
        {
            if (SetProperty(value, _operation.Code, o => _operation.Code = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Description
    {
        get { return _operation.Description; }
        set
        {
            if (SetProperty(value, _operation.Description, o => _operation.Description = o))
            {
                UpdateDescription();
            }
        }
    }

    public string FriendlyName
    {
        get { return _operation.FriendlyName; }
        set
        {
            if (SetProperty(value, _operation.FriendlyName, o => _operation.FriendlyName = o))
            {
                UpdateDescription();
            }
        }
    }

    public int Timeout
    {
        get { return _operation.Timeout; }
        set
        {
            if (SetProperty(value, _operation.Timeout, o => _operation.Timeout = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Category
    {
        get { return _operation.Category; }
        set
        {
            if (SetProperty(value, _operation.Category, o => _operation.Category = o))
            {
                UpdateDescription();
            }
        }
    }

    public bool IsManual
    {
        get { return _operation.IsManual; }
        set
        {
            if (SetProperty(value, _operation.IsManual, o => _operation.IsManual = o))
            {
                UpdateDescription();
            }
        }
    }


    void UpdateDescription()
    {
        //some code
    }




    #region Validation




    #region IDataErrorInfo

    public ValidationResult Validate()
    {
        return ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
    }

    public string this[string columnName]
    {
        get
        {
            var validation = ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);

            return validation.IsValid ? null : validation.ErrorContent.ToString();
        }
    }

    public string Error
    {
        get
        {
            var result = Validate();
            return result.IsValid ? null : result.ErrorContent.ToString();
        }
    }
    #endregion

    #endregion
}

XAML:

<controls:NewDefinitionControl x:Class="DiagnosticsDashboard.EntityData.Operations.Views.NewOperationView"
                               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                               xmlns:views="clr-namespace:DiagnosticsDashboard.EntityData.Operations.Views"
                               xmlns:controls="clr-namespace:DiagnosticsDashboard.Core.Controls;assembly=DiagnosticsDashboard.Core"
                               xmlns:c="clr-namespace:DiagnosticsDashboard.Core.Validation;assembly=DiagnosticsDashboard.Core"
                               mc:Ignorable="d">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Label Grid.Column="0"
               Grid.Row="0"
               Margin="5">Code:</Label>
        <Label Grid.Column="0"
               Grid.Row="1"
               Margin="5">Description:</Label>
        <Label Grid.Column="0"
               Grid.Row="2"
               Margin="5">Category:</Label>
        <Label Grid.Column="0"
               Grid.Row="3"
               Margin="5">Friendly Name:</Label>
        <Label Grid.Column="0"
               Grid.Row="4"
               Margin="5">Timeout:</Label>
        <Label Grid.Column="0"
               Grid.Row="5"
               Margin="5">Is Manual:</Label>
        <TextBox Grid.Column="1"
                 Text="{Binding Code,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                 Grid.Row="0"
                 Margin="5"/>
        <TextBox Grid.Column="1"
                 Grid.Row="1"
                 Margin="5"
                 Text="{Binding Description}" />
        <TextBox Grid.Column="1"
                 Grid.Row="2"
                 Margin="5"
                 Text="{Binding Category}" />
        <TextBox Grid.Column="1"
                 Grid.Row="3"
                 Margin="5"
                 Text="{Binding FriendlyName}" />
        <TextBox Grid.Column="1"
                 Grid.Row="4"
                 Margin="5"
                 Text="{Binding Timeout}" />
        <CheckBox Grid.Column="1"
                  Grid.Row="5"
                  Margin="5"
                  IsChecked="{Binding IsManual}"
                  VerticalAlignment="Center" />


    </Grid>
</controls:NewDefinitionControl>

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

In my case, creating canvas every time worked for me, even though it's not memory-friendly

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
imageBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
canvas = new Canvas(imageBitmap);
canvas.drawBitmap(bm, 0, 0, null);

Number of lines in a file in Java

It seems that there are a few different approaches you can take with LineNumberReader.

I did this:

int lines = 0;

FileReader input = new FileReader(fileLocation);
LineNumberReader count = new LineNumberReader(input);

String line = count.readLine();

if(count.ready())
{
    while(line != null) {
        lines = count.getLineNumber();
        line = count.readLine();
    }
    
    lines+=1;
}
    
count.close();

System.out.println(lines);

Even more simply, you can use the Java BufferedReader lines() Method to return a stream of the elements, and then use the Stream count() method to count all of the elements. Then simply add one to the output to get the number of rows in the text file.

As example:

FileReader input = new FileReader(fileLocation);
LineNumberReader count = new LineNumberReader(input);

int lines = (int)count.lines().count() + 1;
    
count.close();

System.out.println(lines);

Check whether an array is empty

hi array is one object so it null type or blank

   <?php
        if($error!=null)
            echo "array is blank or null or not array";
    //OR
       if(!empty($error))
           echo "array is blank or null or not array";
    //OR
     if(is_array($error))
           echo "array is blank or null or not array";
   ?>

Detect if string contains any spaces

var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

How to declare and add items to an array in Python?

Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.

If you actually want an array (list), use:

array = []
array.append(valueToBeInserted)

Hibernate dialect for Oracle Database 11g?

Add org.hibernate.dialect.OracleDialect for Oracle11g database. It will resolve this error.

How do I output lists as a table in Jupyter notebook?

There is a nice trick: wrap the data with pandas DataFrame.

import pandas as pd
data = [[1, 2], [3, 4]]
pd.DataFrame(data, columns=["Foo", "Bar"])

It displays data like:

  | Foo | Bar |
0 | 1   | 2   |
1 | 3   | 4   |

All com.android.support libraries must use the exact same version specification

If you are facing problem after implementing all below mentioned new libraries. I was facing the above mentioned same problem on this 'com.android.support:appcompat-v7:27.1.0' compatible verions.

implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:mediarouter-v7:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
implementation 'com.android.support:cardview-v7:27.1.0'
implementation 'com.android.support:support-v13:27.1.0'
implementation 'com.android.support:support-v4:27.1.0'

I just replace this

'com.android.support:appcompat-v7:27.1.0'

to this

'com.android.support:appcompat-v7:27.0.1'

Can't connect to localhost on SQL Server Express 2012 / 2016

According to Aaron Bertand:

  1. You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services, and checking that the service SQL Server (SQLEXPRESS) is running. If not, start it.

  2. While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.

  3. You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools (or SQL Server Configuration Manager), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.

    SQL Server Configuration Manager

  4. Verify your SQL Server connection authentication mode matches your connection string:

    • If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":

      -- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
      USE [master]
      GO
      DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
      EXEC xp_instance_regwrite
        N'HKEY_LOCAL_MACHINE',
        N'Software\Microsoft\MSSQLServer\MSSQLServer',
        N'LoginMode',
        REG_DWORD,
        @SqlServerAndWindowsAuthenticationMode;
      GO
      
    • If you're connecting using "Integrated Security=true" (Windows Mode), and this error only comes up when debugging in web applications, then you need to add the ApplicationPoolIdentity as a SQL Server login:
  5. otherwise, run Start -> Run -> Services.msc If so, is it running?

If it's not running then

It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.

What is a "web service" in plain English?

Web services are almost like normal a web page. The difference is that they are formatted to make it very easy for a program to pull data from the page, to the point of probably not using any HTML. They generally also are more reliable as to the consistency of the format, may use a different formal process to define the content such soap or raw xml, and there is often also a descriptor document that formally defines the structure for the data.

How to create a self-signed certificate with OpenSSL

this worked for me

openssl req -x509 -nodes -subj '/CN=localhost'  -newkey rsa:4096 -keyout ./sslcert/key.pem -out ./sslcert/cert.pem -days 365

server.js

var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var compression = require('compression');
var express = require('express');
var app = express();

app.use(compression());
app.use(express.static(__dirname + '/www'));    

app.get('/*', function(req,res) {
  res.sendFile(path.join(__dirname+'/www/index.html'));
});

// your express configuration here

var httpServer = http.createServer(app);
var credentials = {
    key: fs.readFileSync('./sslcert/key.pem', 'utf8'),
    cert: fs.readFileSync('./sslcert/cert.pem', 'utf8')
};
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

console.log(`RUNNING ON  http://127.0.0.1:8080`);
console.log(`RUNNING ON  http://127.0.0.1:8443`);

How can I set / change DNS using the command-prompt at windows 8

Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp)

You can set your DNS servers statically even if you use DHCP to obtain your IP address.

Example under Windows 7 to add two DN servers, the command is as follows:

netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=1 netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=2

Returning string from C function

Your pointer is pointing to local variable of the function. So as soon as you return from the function, memory gets deallocated. You have to assign memory on heap in order to use it in other functions.

Instead char *rtnPtr = word;

do this char *rtnPtr = malloc(length);

So that it is available in the main function. After it is used free the memory.

How to make RatingBar to show five stars

To show a simple star rating in round figure just use this code

public static String getIntToStar(int starCount) {
        String fillStar = "\u2605";
        String blankStar = "\u2606";
        String star = "";

        for (int i = 0; i < starCount; i++) {
            star = star.concat(" " + fillStar);
        }
        for (int j = (5 - starCount); j > 0; j--) {
            star = star.concat(" " + blankStar);
        }
        return star;
    }

And use it like this

button.setText(getIntToStar(4));

Focus Next Element In Tab Index

As mentioned in a comment above, I don't think that any browsers expose tab order information. Here a simplified approximation of what the browser does to get the next element in tab order:

var allowedTags = {input: true, textarea: true, button: true};

var walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode: function(node)
    {
      if (node.localName in allowedTags)
        return NodeFilter.FILTER_ACCEPT;
      else
        NodeFilter.FILTER_SKIP;
    }
  },
  false
);
walker.currentNode = currentElement;
if (!walker.nextNode())
{
  // Restart search from the start of the document
  walker.currentNode = walker.root;
  walker.nextNode();
}
if (walker.currentNode && walker.currentNode != walker.root)
  walker.currentNode.focus();

This only considers some tags and ignores tabindex attribute but might be enough depending on what you are trying to achieve.

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

Using Jquery Datatable with AngularJs

I know it's tempting to use drag and drop angular modules created by other devs - but actually, unless you are doing something non-standard like dynamically adding / removing rows from the ng-repeated data set by calling $http services chance are you really don't need a directive based solution, so if you do go this direction you probably just created extra watchers you don't actually need.

What this implementation provides:

  • Pagination is always correct
  • Filtering is always correct (even if you add custom filters but of course they just need to be in the same closure)

The implementation is easy. Just use angular's version of jQuery dom ready from your view's controller:

Inside your controller:

'use strict';

var yourApp = angular.module('yourApp.yourController.controller', []);

yourApp.controller('yourController', ['$scope', '$http', '$q', '$timeout', function ($scope, $http, $q, $timeout) {

    $scope.users = [
        {
            email: '[email protected]',
            name: {
                first: 'User',
                last: 'Last Name'
            },
            phone: '(416) 555-5555',
            permissions: 'Admin'
        },
        {
            email: '[email protected]',
            name: {
                first: 'First',
                last: 'Last'
            },
            phone: '(514) 222-1111',
            permissions: 'User'
        }
    ];

    angular.element(document).ready( function () {
         dTable = $('#user_table')
         dTable.DataTable();
     });

}]);

Now in your html view can do:

<div class="table table-data clear-both" data-ng-show="viewState === possibleStates[0]">
        <table id="user_table" class="users list dtable">
            <thead>
                <tr>
                    <th>E-mail</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                    <th>Permissions</th>
                    <th class="blank-cell"></th>
                </tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="user in users track by $index">
                    <td>{{ user.email }}</td>
                    <td>{{ user.name.first }}</td>
                    <td>{{ user.name.last }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.permissions }}</td>
                    <td class="users controls blank-cell">
                        <a class="btn pointer" data-ng-click="showEditUser( $index )">Edit</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

(HTML) Download a PDF file instead of opening them in browser when clicked

This is only possible with setting a http response header by the server side code. Namely;

Content-Disposition: attachment; filename=fname.ext

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Stack smashing detected

Please look at the following situation:

ab@cd-x:$ cat test_overflow.c 
#include <stdio.h>
#include <string.h>

int check_password(char *password){
    int flag = 0;
    char buffer[20];
    strcpy(buffer, password);

    if(strcmp(buffer, "mypass") == 0){
        flag = 1;
    }
    if(strcmp(buffer, "yourpass") == 0){
        flag = 1;
    }
    return flag;
}

int main(int argc, char *argv[]){
    if(argc >= 2){
        if(check_password(argv[1])){
            printf("%s", "Access granted\n");
        }else{
            printf("%s", "Access denied\n");
        }
    }else{
        printf("%s", "Please enter password!\n");
    }
}
ab@cd-x:$ gcc -g -fno-stack-protector test_overflow.c 
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out wepassssssssssssssssss
Access granted

ab@cd-x:$ gcc -g -fstack-protector test_overflow.c 
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepassssssssssssssssss
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0xce0ed8]
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x0)[0xce0e90]
./a.out[0x8048524]
./a.out[0x8048545]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc16b56]
./a.out[0x8048411]
======= Memory map: ========
007d9000-007f5000 r-xp 00000000 08:06 5776       /lib/libgcc_s.so.1
007f5000-007f6000 r--p 0001b000 08:06 5776       /lib/libgcc_s.so.1
007f6000-007f7000 rw-p 0001c000 08:06 5776       /lib/libgcc_s.so.1
0090a000-0090b000 r-xp 00000000 00:00 0          [vdso]
00c00000-00d3e000 r-xp 00000000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3e000-00d3f000 ---p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3f000-00d41000 r--p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d41000-00d42000 rw-p 00140000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d42000-00d45000 rw-p 00000000 00:00 0 
00e0c000-00e27000 r-xp 00000000 08:06 4213       /lib/ld-2.10.1.so
00e27000-00e28000 r--p 0001a000 08:06 4213       /lib/ld-2.10.1.so
00e28000-00e29000 rw-p 0001b000 08:06 4213       /lib/ld-2.10.1.so
08048000-08049000 r-xp 00000000 08:05 1056811    /dos/hacking/test/a.out
08049000-0804a000 r--p 00000000 08:05 1056811    /dos/hacking/test/a.out
0804a000-0804b000 rw-p 00001000 08:05 1056811    /dos/hacking/test/a.out
08675000-08696000 rw-p 00000000 00:00 0          [heap]
b76fe000-b76ff000 rw-p 00000000 00:00 0 
b7717000-b7719000 rw-p 00000000 00:00 0 
bfc1c000-bfc31000 rw-p 00000000 00:00 0          [stack]
Aborted
ab@cd-x:$ 

When I disabled the stack smashing protector no errors were detected, which should have happened when I used "./a.out wepassssssssssssssssss"

So to answer your question above, the message "** stack smashing detected : xxx" was displayed because your stack smashing protector was active and found that there is stack overflow in your program.

Just find out where that occurs, and fix it.

SQLite: How do I save the result of a query as a CSV file?

In addition to the above answers you can also use .once in a similar way to .output. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout.

So in the above example

.mode csv
.headers on
.once test.csv
select * from tbl1;

How can I invert color using CSS?

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
  color: white;_x000D_
  mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Storing a file in a database as opposed to the file system?

I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.

Serializing PHP object to JSON

Try using this, this worked fine for me.

json_encode(unserialize(serialize($array)));

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

Error occurred during initialization of boot layer FindException: Module not found

I solved this issue by going into Properties -> Java Build Path and reordering my source folder so it was above the JRE System Library.

Android - Activity vs FragmentActivity?

FragmentActivity gives you all of the functionality of Activity plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.

If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity and use the native Fragments introduced in v11 without issue. FragmentActivity was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.

I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Variables have a type and a value.

  • $var = "test" is a string that contain "test"
  • $var2 = 24 is an integer vhose value is 24.

When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do

if ($var == 1) {... do something ...}

PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.

When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.

This is useful, for example, when you have a function that can return false (on error) and 0 (result) :

if(myFunction() == false) { ... error on myFunction ... }

This code is wrong as if myFunction() returns 0, it is casted to false and you seem to have an error. The correct code is :

if(myFunction() === false) { ... error on myFunction ... }

because the test is that the return value "is a boolean and is false" and not "can be casted to false".

How to set a hidden value in Razor

How about like this

public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
    {
        return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
    {
        return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
    }

Use it like this

 @Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How do I make a Git commit in the past?

The following is what I use to commit changes on foo to N=1 days in the past:

git add foo
git commit -m "Update foo"
git commit --amend --date="$(date -v-1d)"

If you want to commit to a even older date, say 3 days back, just change the date argument: date -v-3d.

That's really useful when you forget to commit something yesterday, for instance.

UPDATE: --date also accepts expressions like --date "3 days ago" or even --date "yesterday". So we can reduce it to one line command:

git add foo ; git commit --date "yesterday" -m "Update"

How to use sha256 in php5.3.0

Could this be a typo? (two Ps in ppasscode, intended?)

$_POST['ppasscode'];

I would make sure and do:

print_r($_POST);

and make sure the data is accurate there, and then echo out what it should look like:

echo hash('sha256', $_POST['ppasscode']);

Compare this output to what you have in the database (manually). By doing this you're exploring your possible points of failure:

  1. Getting password from form
  2. hashing the password
  3. stored password
  4. comparison of the two.

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

Delete item from state array in react

Here is a minor variation on Aleksandr Petrov's response using ES6

removePeople(e) {
    let filteredArray = this.state.people.filter(item => item !== e.target.value)
    this.setState({people: filteredArray});
}

jQuery click event not working after adding class

I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

Like this:

<script>
  $(function(){
    //your click code
    $("a.tabclick").on('click',function() {
      //do something
    });
  });
</script>

Counting array elements in Python

Or,

myArray.__len__()

if you want to be oopy; "len(myArray)" is a lot easier to type! :)

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

You don't need Xvfb

It is failing to start due to a mismatch between the chrome version and the chromedriver version. Downloading and installing the same versions or latest versions would solve the issue.

T-SQL How to select only Second row from a table?

I have a much easier way than the above ones.

DECLARE @FirstId int, @SecondId int

    SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
    SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 

SELECT @SecondId 

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Database directory read-write permission also a problem i found. Just make sure your application is able to rw files on db location. Try chmod 777 for testing.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

How to write PNG image to string with the PIL?

sth's solution didn't work for me
because in ...

Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension

It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case

You can bypass the format detection by setting the format yourself in a parameter

import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()

Disable Copy or Paste action for text box?

you can try this:

   <input type="textbox" id="confirmEmail" onselectstart="return false" onpaste="return false;" oncopy="return false" oncut="return false" ondrag="return false" ondrop="return false" autocomplete="off">

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

How do I trap ctrl-c (SIGINT) in a C# console app

This question is very similar to:

Capture console exit C#

Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.

namespace CancelSample
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;

    internal class Program
    {
        /// <summary>
        /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
        /// </summary>
        /// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
        /// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);

        /// <summary>
        /// The console close handler delegate.
        /// </summary>
        /// <param name="closeReason">
        /// The close reason.
        /// </param>
        /// <returns>
        /// True if cleanup is complete, false to run other registered close handlers.
        /// </returns>
        private delegate bool ConsoleCloseHandler(int closeReason);

        /// <summary>
        ///  Event set when the process is terminated.
        /// </summary>
        private static readonly ManualResetEvent TerminationRequestedEvent;

        /// <summary>
        /// Event set when the process terminates.
        /// </summary>
        private static readonly ManualResetEvent TerminationCompletedEvent;

        /// <summary>
        /// Static constructor
        /// </summary>
        static Program()
        {
            // Do this initialization here to avoid polluting Main() with it
            // also this is a great place to initialize multiple static
            // variables.
            TerminationRequestedEvent = new ManualResetEvent(false);
            TerminationCompletedEvent = new ManualResetEvent(false);
            SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
        }

        /// <summary>
        /// The main console entry point.
        /// </summary>
        /// <param name="args">The commandline arguments.</param>
        private static void Main(string[] args)
        {
            // Wait for the termination event
            while (!TerminationRequestedEvent.WaitOne(0))
            {
                // Something to do while waiting
                Console.WriteLine("Work");
            }

            // Sleep until termination
            TerminationRequestedEvent.WaitOne();

            // Print a message which represents the operation
            Console.WriteLine("Cleanup");

            // Set this to terminate immediately (if not set, the OS will
            // eventually kill the process)
            TerminationCompletedEvent.Set();
        }

        /// <summary>
        /// Method called when the user presses Ctrl-C
        /// </summary>
        /// <param name="reason">The close reason</param>
        private static bool OnConsoleCloseEvent(int reason)
        {
            // Signal termination
            TerminationRequestedEvent.Set();

            // Wait for cleanup
            TerminationCompletedEvent.WaitOne();

            // Don't run other handlers, just exit.
            return true;
        }
    }
}

importing go files in same folder

./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)

in this case:
main.go import "./a"

It can call the function in the a.go and b.go,that with first letter caps on.

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to loop through all enum values in C#?

foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
   Console.WriteLine(val);
}

Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Load local HTML file in a C# WebBrowser

  1. Do a right click->properties on the file in Visual Studio.
  2. Set the Copy to Output Directory to Copy always.

Then you will be able to reference your files by using a path such as @".\my_html.html"

Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.

If you use a sub folder, that too will be copied in to the bin folder so your path would then be @".\my_subfolder\my_html.html"

In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.

This is what you need:

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));

You'll have to change the variables and names of course.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Considering the following code:

import java.util.Optional;

// one class needs to have a main() method
public class Test
{
  public String orelesMethod() {
    System.out.println("in the Method");
    return "hello";
  }

  public void test() {
    String value;
    value = Optional.<String>ofNullable("test").orElseGet(this::orelesMethod);
    System.out.println(value); 

    value = Optional.<String>ofNullable("test").orElse(orelesMethod());
    System.out.println(value); 
  }

  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    Test test = new Test();

    test.test();
  }
}

if we get value in this way: Optional.<String>ofNullable(null), there is no difference between orElseGet() and orElse(), but if we get value in this way: Optional.<String>ofNullable("test"), orelesMethod() in orElseGet() will not be called but in orElse() it will be called

CodeIgniter -> Get current URL relative to base url

 //if you want to get parameter from url use:
 parse_str($_SERVER['QUERY_STRING'], $_GET);
 //then you can use:
 if(isset($_GET["par"])){
      echo $_GET["par"];
 }
 //if you want to get current page url use:
 $current_url = current_url();

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

This is what I've used:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

How to find all occurrences of an element in a list

While not a solution for lists directly, numpy really shines for this sort of thing:

import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]

returns:

ii ==>array([2, 8])

This can be significantly faster for lists (arrays) with a large number of elements vs some of the other solutions.

SQL command to display history of queries

(Linux) Open your Terminal ctrl+alt+t run the command

 cat ~/.mysql_history

you will get all the previous mysql query history enjoy :)

After installing SQL Server 2014 Express can't find local db

I faced the same issue. Just download and install the SQL Server suite from the following link :http://www.microsoft.com/en-US/download/details.aspx?id=42299

restart your SSMS and you should be able to "Register Local Servers" via right-click on "Local Servers Groups", select "tasks", click "register local servers"

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The problem in my case is that the Gemfile.lock file had a BUNDLED_WITH version of 1.16.1 and gem install bundler installed version 2.0.1, so there was a version mismatch when looking to right the folder

gem install bundler -v 1.16.1 fixed it

Of course, you can also change your Gemfile.lock's BUNDLED_WITH with last bundler version and use recent software, as Sam3000 suggests

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});

Json.net serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Animal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}

Ant: How to execute a command for each file in directory?

Short Answer

Use <foreach> with a nested <FileSet>

Foreach requires ant-contrib.

Updated Example for recent ant-contrib:

<target name="foo">
  <foreach target="bar" param="theFile">
    <fileset dir="${server.src}" casesensitive="yes">
      <include name="**/*.java"/>
      <exclude name="**/*Test*"/>
    </fileset>
  </foreach>
</target>

<target name="bar">
  <echo message="${theFile}"/>
</target>

This will antcall the target "bar" with the ${theFile} resulting in the current file.

What is the most "pythonic" way to iterate over a list in chunks?

import itertools
def chunks(iterable,size):
    it = iter(iterable)
    chunk = tuple(itertools.islice(it,size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# though this will throw ValueError if the length of ints
# isn't a multiple of four:
for x1,x2,x3,x4 in chunks(ints,4):
    foo += x1 + x2 + x3 + x4

for chunk in chunks(ints,4):
    foo += sum(chunk)

Another way:

import itertools
def chunks2(iterable,size,filler=None):
    it = itertools.chain(iterable,itertools.repeat(filler,size-1))
    chunk = tuple(itertools.islice(it,size))
    while len(chunk) == size:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# x2, x3 and x4 could get the value 0 if the length is not
# a multiple of 4.
for x1,x2,x3,x4 in chunks2(ints,4,0):
    foo += x1 + x2 + x3 + x4

What to do on TransactionTooLargeException

With so many places where TransactionTooLargeException can happen-- here's one more new to Android 8--a crash when someone merely starts to type into an EditText if the content is too big.

It's related to the AutoFillManager (new in API 26) and the following code in StartSessionLocked():

    mSessionId = mService.startSession(mContext.getActivityToken(),
            mServiceClient.asBinder(), id, bounds, value, mContext.getUserId(),
            mCallback != null, flags, mContext.getOpPackageName());

If I understand correctly, this calls the autofill service-- passing the AutofillManagerClient within the binder. And when the EditText has a lot of content, it seems to cause the TTLE.

A few things may mitigate it (or did as I was testing anyway): Add android:importantForAutofill="noExcludeDescendants" in the EditText's xml layout declaration. Or in code:

EditText et = myView.findViewById(R.id.scriptEditTextView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    et.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
}

A 2nd awful, terrible workaround might also be to override the performClick() and onWindowFocusChanged() methods to catch the error in a TextEdit subclass itself. But I don't think that's wise really...

UTF-8 all the way through

Data Storage:

  • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).

  • In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

Data Access:

  • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

    • If you're using the PDO abstraction layer with PHP = 5.3.6, you can specify charset in the DSN:

       $dbh = new PDO('mysql:charset=utf8mb4');
      
    • If you're using mysqli, you can call set_charset():

        $mysqli->set_charset('utf8mb4');       // object oriented style
        mysqli_set_charset($link, 'utf8mb4');  // procedural style
      
    • If you're stuck with plain mysql but happen to be running PHP = 5.2.3, you can call mysql_set_charset.

  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

  • The same consideration regarding utf8mb4/utf8 applies as above.

Output:

  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).

  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.

  • When encoding the output using json_encode(), add JSON_UNESCAPED_UNICODE as a second parameter.

Input:

  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding() does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.

  • From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:

    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.

Other Code Considerations:

  • Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.

  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring extension.

  • PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.

  • To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

Generating CSV file for Excel, how to have a newline inside a value

You could use keyboard shortcut ALT+Enter.

  1. Select the cell you wish to edit
  2. enter edit mode either by double clicking it or pressing F2 3.Press Alt+enter. This will create a new line in cell

XSD - how to allow elements in any order any number of times?

This is what finally worked for me:

<xsd:element name="bar">
  <xsd:complexType>
    <xsd:sequence>
      <!--  Permit any of these tags in any order in any number     -->
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element name="child1" type="xsd:string" />
        <xsd:element name="child2" type="xsd:string" />
        <xsd:element name="child3" type="xsd:string" />
      </xsd:choice>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

What's the difference between JavaScript and JScript?

Wikipedia has this to say about the differences.

In general JScript is an ActiveX scripting language that is probably interpreted as JavaScript by non-IE browsers.

Why does .NET foreach loop throw NullRefException when collection is null?

A foreach loop calls the GetEnumerator method.
If the collection is null, this method call results in a NullReferenceException.

It is bad practice to return a null collection; your methods should return an empty collection instead.

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

Can we have multiple "WITH AS" in single sql - Oracle SQL

the correct syntax is -

with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;

Check variable equality against a list of values

You could use an array and indexOf:

if ([1,3,12].indexOf(foo) > -1)

What is the difference between exit and return?

  • return returns from the current function; it's a language keyword like for or break.
  • exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);. The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

Example with return:

#include <stdio.h>

void f(){
    printf("Executing f\n");
    return;
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f
Back from f

Another example for exit():

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

void f(){
    printf("Executing f\n");
    exit(0);
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f

You never get "Back from f". Also notice the #include <stdlib.h> necessary to call the library function exit().

Also notice that the parameter of exit() is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).

The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.

Last point, exit() come in two flavors _exit() and exit(). The difference between the forms is that exit() (and return from main) calls functions registered using atexit() or on_exit() before really terminating the process while _exit() (from #include <unistd.h>, or its synonymous _Exit from #include <stdlib.h>) terminates the process immediately.

Now there are also issues that are specific to C++.

C++ performs much more work than C when it is exiting from functions (return-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

This won't happen if you are using the good old C FILE* streams. These will be flushed on exit(). Actually, the rule is the same that for registered exit functions, FILE* will be flushed on all normal terminations, which includes exit(), but not calls to _exit() or abort().

You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.

Destructors of static C++ objects (globals) will be called if you call either return from main() or exit() anywhere in your program. They wont be called if the program is terminated using _exit() or abort(). abort() is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert() macro only active in debug mode.

When is exit() useful ?

exit() means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).

Direct calls to exit() are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit() from a library is bad, it leads for instance people to ask this question.

There is an undisputed legitimate use of exit() as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.

How can I truncate a double to only two decimal places in Java?

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Which maven dependencies to include for spring 3.0?

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

How to list the certificates stored in a PKCS12 keystore with keytool?

You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.

keytool -list -v -keystore cert.p12 -storepass <password>

 Keystore type: PKCS12
 Keystore provider: SunJSSE

 Your keystore contains 1 entry
 Alias name: 1
 Creation date: Jul 11, 2020
 Entry type: PrivateKeyEntry
 Certificate chain length: 2

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

Unix ls command: show full path when using options

Use this command:

ls -ltr /mig/mthome/09/log/*

instead of:

ls -ltr /mig/mthome/09/log

to get the full path in the listing.

Increase heap size in Java

It is possible to increase heap size allocated by the JVM by using command line options Here we have 3 options

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

java -Xms16m -Xmx64m ClassName

In the above line we can set minimum heap to 16mb and maximum heap 64mb

Is it possible to use Java 8 for Android development?

java 8

Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version.

To check which features of java 8 are supported

Use Java 8 language features

We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you.

Future of Java 8 Language Feature Support on Android

Eclipse Users:

For old developers who prefer Eclipse, google stops support Eclipse Android Developer tools

if you installed Java 8 JDK, then give it a try, if any problems appears try to set the compiler as 1.6 in Eclipse from window menu ? Preferences ? Java ? Compiler. Java 7 will works too:

Eclipse Preferences -> Java -> Compiler

Java 7 or higher is required if you are targeting Android 5.0 and higher.

install multiple JDK and try.

Get top n records for each group of grouped results

I wanted to share this because I spent a long time searching for an easy way to implement this in a java program I'm working on. This doesn't quite give the output you're looking for but its close. The function in mysql called GROUP_CONCAT() worked really well for specifying how many results to return in each group. Using LIMIT or any of the other fancy ways of trying to do this with COUNT didn't work for me. So if you're willing to accept a modified output, its a great solution. Lets say I have a table called 'student' with student ids, their gender, and gpa. Lets say I want to top 5 gpas for each gender. Then I can write the query like this

SELECT sex, SUBSTRING_INDEX(GROUP_CONCAT(cast(gpa AS char ) ORDER BY gpa desc), ',',5) 
AS subcategories FROM student GROUP BY sex;

Note that the parameter '5' tells it how many entries to concatenate into each row

And the output would look something like

+--------+----------------+
| Male   | 4,4,4,4,3.9    |
| Female | 4,4,3.9,3.9,3.8|
+--------+----------------+

You can also change the ORDER BY variable and order them a different way. So if I had the student's age I could replace the 'gpa desc' with 'age desc' and it will work! You can also add variables to the group by statement to get more columns in the output. So this is just a way I found that is pretty flexible and works good if you are ok with just listing results.

Python append() vs. + operator on lists, why do these give different results?

See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.

How to compare only date components from DateTime in EF?

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.


You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Deploying Java webapp to Tomcat 8 running in Docker container

Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

You might need to access the url as below unless you have specified the webroot

http://192.168.59.103:8888/myapp/getData

Change Tomcat Server's timeout in Eclipse

I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:

  • increasing timeout seconds
  • deleting various .metadata files in workspace directory
  • deleting the server instance in Eclipse along with the Run Config

Nothing worked until I read Rohitdev's comment and realized that I had, in fact added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up.

Set textarea width to 100% in bootstrap modal

You can also just simply add the attribute row="number of rows" and cols="number of columns" like

<div class="modal-body">
    <textarea class="form-control col-xs-12" rows="7" cols="50"></textarea>
</div>

This will increase the number of rows in the textarea that is much similar to style="min-height: 100%" 100% or 80% and min-width: 50% for width etc. Also row=7 changes the height and cols=50 changes the width of textarea.

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked />

HTML5 does not require attributes to have values

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

I've searched around, and only this solution helped me:

mysql -u root -p

set global net_buffer_length=1000000; --Set network buffer length to a large byte number

set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number

SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays,errors and unwanted behaviour

source file.sql --Import your sql dump file

SET foreign_key_checks = 1; --Remember to enable foreign key checks when procedure is complete!

The answer is found here.

How to invert a grep expression

Add the -v option to your grep command to invert the results.

Invalid shorthand property initializer

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that's solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

How to TryParse for Enum value?

The only way to avoid exception handling is to use the GetNames() method, and we all know that exceptions shouldn't be abused for common application logic :)

How to add some non-standard font to a website?

Typeface.js and Cufon are two other interesting options. They are JavaScript components that render special font data in JSON format (which you can convert from TrueType or OpenType formats on their web sites) via the new <canvas> element in all newer browsers except Internet Explorer and via VML in Internet Explorer.

The main problem with both (as of now) is that selecting text does not work or at least works only quite awkwardly.

Still, it is very nice for headlines. Body text... I don't know.

And it's surprisingly fast.

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

how to create a list of lists

First of all do not use list as a variable name- that is a builtin function.

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-

my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.

The first can be referenced with my_list[0] and the second with my_list[1]

How do I turn a C# object into a JSON string in .NET?

Since we all love one-liners

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON

Using NotNull Annotation in method argument

As mentioned above @NotNull does nothing on its own. A good way of using @NotNull would be using it with Objects.requireNonNull

public class Foo {
    private final Bar bar;

    public Foo(@NotNull Bar bar) {
        this.bar = Objects.requireNonNull(bar, "bar must not be null");
    }
}

Read all worksheets in an Excel workbook into an R list with data.frames

Adding to Paul's answer. The sheets can also be concatenated using something like this:

data = path %>% 
excel_sheets() %>% 
set_names() %>% 
map_df(~ read_excel(path = path, sheet = .x), .id = "Sheet")

Libraries needed:

if(!require(pacman))install.packages("pacman")
pacman::p_load("tidyverse","readxl","purrr")

How to print the value of a Tensor object in TensorFlow?

Question: How to print the value of a Tensor object in TensorFlow?

Answer:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)

How can I align YouTube embedded video in the center in bootstrap

For a fully responsive IFramed YouTube video, try this:

<div class="blogwidevideo">
<iframe width="854" height="480" style="margin: auto;" src="https://www.youtube-nocookie.com/embed/h5ag-3nnenc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

.blogwidevideo {    
    overflow:hidden;
    padding-bottom:56.25%;
    position:relative;
    height:0;    
}

.blogwidevideo iframe {   
    left:10%; //centers for the 80% width - not needed if width is 100%
    top:0;
    height:80%; //change to 100% if going full width
    width:80%;
    position:absolute;
}

Running a cron job at 2:30 AM everyday

  1. To edit:

    crontab -e
    
  2. Add this command line:

    30 2 * * * /your/command
    
    • Crontab Format:

      MIN HOUR DOM MON DOW CMD

    • Format Meanings and Allowed Value:
    • MIN Minute field 0 to 59
    • HOUR Hour field 0 to 23
    • DOM Day of Month 1-31
    • MON Month field 1-12
    • DOW Day Of Week 0-6
    • CMD Command Any command to be executed.
  3. Restart cron with latest data:

    service crond restart
    

Python Pandas: Get index of rows which column matches certain value

df.iloc[i] returns the ith row of df. i does not refer to the index label, i is a 0-based index.

In contrast, the attribute index returns actual index labels, not numeric row-indices:

df.index[df['BoolCol'] == True].tolist()

or equivalently,

df.index[df['BoolCol']].tolist()

You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:

df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
       index=[10,20,30,40,50])

In [53]: df
Out[53]: 
   BoolCol
10    True
20   False
30   False
40    True
50    True

[5 rows x 1 columns]

In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]

If you want to use the index,

In [56]: idx = df.index[df['BoolCol']]

In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')

then you can select the rows using loc instead of iloc:

In [58]: df.loc[idx]
Out[58]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

Note that loc can also accept boolean arrays:

In [55]: df.loc[df['BoolCol']]
Out[55]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

If you have a boolean array, mask, and need ordinal index values, you can compute them using np.flatnonzero:

In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])

Use df.iloc to select rows by ordinal index:

In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]: 
   BoolCol
10    True
40    True
50    True

Sorting Directory.GetFiles()

The MSDN Documentation states that there is no guarantee of any order on the return values. You have to use the Sort() method.

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Is using 'var' to declare variables optional?

They are not the same.

Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)

Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)

Update: ECMAScript 2015

let was introduced in ECMAScript 2015 to have block scope.

How to join two tables by multiple columns in SQL?

You would basically want something along the lines of:

SELECT e.*, v.Score
  FROM Evaluation e
LEFT JOIN Value v
ON v.CaseNum = e.CaseNum AND
v.FileNum = e.FileNum AND
v.ActivityNum = e.ActivityNum;

Git removing upstream from local repository

Using git version 1.7.9.5 there is no "remove" command for remote. Use "rm" instead.

$ git remote rm upstream
$ git remote add upstream https://github.com/Foo/repos.git

or, as noted in the previous answer, set-url works.

I don't know when the command changed, but Ubuntu 12.04 shipped with 1.7.9.5.

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How to view changes made to files on a certain revision in Subversion

The equivalent command in svn is:

svn log --diff -r revision

Highlight label if checkbox is checked

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

How to write a confusion matrix in Python?

If you don't want scikit-learn to do the work for you...

    import numpy
    actual = numpy.array(actual)
    predicted = numpy.array(predicted)

    # calculate the confusion matrix; labels is numpy array of classification labels
    cm = numpy.zeros((len(labels), len(labels)))
    for a, p in zip(actual, predicted):
        cm[a][p] += 1

    # also get the accuracy easily with numpy
    accuracy = (actual == predicted).sum() / float(len(actual))

Or take a look at a more complete implementation here in NLTK.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Convert python long/int to fixed size byte array

With Python 3.2 and later, you can use int.to_bytes and int.from_bytes: https://docs.python.org/3/library/stdtypes.html#int.to_bytes

pip install access denied on Windows

Running cmd as administrator solved for me. You can also try --user. If you do not want to repeat the steps you need to give full access to anaconda folder.

How to use ESLint with Jest

You can also set the test env in your test file as follows:

/* eslint-env jest */

describe(() => {
  /* ... */
})

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once

Using ChildActionOnly in MVC

FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here

Difference between npx and npm?

Simple Definition:

npm - Javascript package manager

npx - Execute npm package binaries

How to read existing text files without defining path

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

How to calculate growth with a positive and negative number?

Use this formula:

=100% + (Year 2/Year 1)

The logic is that you recover 100% of the negative in year 1 (hence the initial 100%) plus any excess will be a ratio against year 1.

Java error: Implicit super constructor is undefined for default constructor

I had this error and fixed it by removing a thrown exception from beside the method to a try/catch block

For example: FROM:

public static HashMap<String, String> getMap() throws SQLException
{

}

TO:

public static Hashmap<String,String> getMap()
{
  try{

  }catch(SQLException)
  { 
  }
}

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

How to get value of selected radio button?

Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):

myForm.elements.namedItem("my-radio-button-group-name").value

The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.

See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.

I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications.

Is there a difference between using a dict literal and a dict constructor?

Literal is much faster, since it uses optimized BUILD_MAP and STORE_MAP opcodes rather than generic CALL_FUNCTION:

> python2.7 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.958 usec per loop

> python2.7 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.479 usec per loop

> python3.2 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.975 usec per loop

> python3.2 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.409 usec per loop

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error