Programs & Examples On #Packed

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Yes, there is awesome simple bash script I found, which allows you to update the Postman Linux app, straight from the terminal, called postman-updater-linux.

Just install it using NPM:

npm install -g postman-updater-linux

Then check for updates:

sudo postman-updater check

Then install:

sudo postman-updater install

Or update:

sudo postman-updater update

All three last commands can be used with custom location by adding -l /your/custom/path to end of this command.

How to unpack an .asar file?

It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/

Thanks @MayaPosch for mentioning that in this comment.

How to get images in Bootstrap's card to be the same height/width?

you can fix this problem with style like this.

<div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/butterPecan.jpg" style="width: 18rem; height: 20rem;" />

Error message: "'chromedriver' executable needs to be available in the path"

Add the webdriver(chromedriver.exe or geckodriver.exe) here C:\Windows. This worked in my case

Error in installation a R package

In my case, the installation of nlme package is in trouble:

mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme' 
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme': 
Permission denied

Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:

sudo R
install.packages('nlme')
q()

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

How do I get the Back Button to work with an AngularJS ui-router state machine?

The Back button wasn't working for me as well, but I figured out that the problem was that I had html content inside my main page, in the ui-view element.

i.e.

<div ui-view>
     <h1> Hey Kids! </h1>
     <!-- More content -->
</div>

So I moved the content into a new .html file, and marked it as a template in the .js file with the routes.

i.e.

   .state("parent.mystuff", {
        url: "/mystuff",
        controller: 'myStuffCtrl',
        templateUrl: "myStuff.html"
    })

Error during installing HAXM, VT-X not working

Even if you have enabled the Virtualization(VT) in BIOS settings, some antivirus options prevent HAXM installation.

For example: In Avast antivirus under Settings (parametres) tab > Troubleshooting (depannage), you should uncheck "Enable Hardware-assisted Virtualization" ("activer l'assistance a la virtualisation").

Now restart your computer and re-install the Intel's HAXM which can be found under ~SDK_LOCATION\extras\intel\Hardware_Accelerated_Execution_Manager. You can also manually download the standalone HAXM installer from Intel's website.

Problems installing the devtools package

I'm on windows and had the same issue.

I used the below code :

install.packages("devtools", type = "win.binary")

Then library(devtools) worked for me.

What does set -e mean in a bash script?

As per bash - The Set Builtin manual, if -e/errexit is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.

By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (it's disabled by default).

If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

If you'd like to execute something on exit, try defining trap, for example:

trap onexit EXIT

where onexit is your function to do something on exit, like below which is printing the simple stack trace:

onexit(){ while caller $((n++)); do :; done; }

There is similar option -E/errtrace which would trap on ERR instead, e.g.:

trap onerr ERR

Examples

Zero status example:

$ true; echo $?
0

Non-zero status example:

$ false; echo $?
1

Negating status examples:

$ ! false; echo $?
0
$ false || true; echo $?
0

Test with pipefail being disabled:

$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1

Test with pipefail being enabled:

$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

The universal adb driver installer worked for me. I went from an HTC to a Samsung to a LG Nexus. The drivers are all over the place for me.

http://adbdriver.com/

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

How to fix corrupted git repository?

Remove the index and do reset

rm -f .git/index
git reset

Offline Speech Recognition In Android (JellyBean)

Working example is given below,

MyService.class

public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {

  public static SpeechDelegate delegate;

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    //TODO do something useful
    try {
      if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        ((AudioManager) Objects.requireNonNull(
          getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    Speech.init(this);
    delegate = this;
    Speech.getInstance().setListener(this);

    if (Speech.getInstance().isListening()) {
      Speech.getInstance().stopListening();
    } else {
      System.setProperty("rx.unsafe-disable", "True");
      RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
        if (granted) { // Always true pre-M
          try {
            Speech.getInstance().stopTextToSpeech();
            Speech.getInstance().startListening(null, this);
          } catch (SpeechRecognitionNotAvailable exc) {
            //showSpeechNotSupportedDialog();

          } catch (GoogleVoiceTypingDisabledException exc) {
            //showEnableGoogleVoiceTyping();
          }
        } else {
          Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
        }
      });
    }
    return Service.START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
    //TODO for communication return IBinder implementation
    return null;
  }

  @Override
  public void onStartOfSpeech() {
  }

  @Override
  public void onSpeechRmsChanged(float value) {

  }

  @Override
  public void onSpeechPartialResults(List<String> results) {
    for (String partial : results) {
      Log.d("Result", partial+"");
    }
  }

  @Override
  public void onSpeechResult(String result) {
    Log.d("Result", result+"");
    if (!TextUtils.isEmpty(result)) {
      Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }
  }

  @Override
  public void onSpecifiedCommandPronounced(String event) {
    try {
      if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        ((AudioManager) Objects.requireNonNull(
          getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (Speech.getInstance().isListening()) {
      Speech.getInstance().stopListening();
    } else {
      RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
        if (granted) { // Always true pre-M
          try {
            Speech.getInstance().stopTextToSpeech();
            Speech.getInstance().startListening(null, this);
          } catch (SpeechRecognitionNotAvailable exc) {
            //showSpeechNotSupportedDialog();

          } catch (GoogleVoiceTypingDisabledException exc) {
            //showEnableGoogleVoiceTyping();
          }
        } else {
          Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
        }
      });
    }
  }


  @Override
  public void onTaskRemoved(Intent rootIntent) {
    //Restarting the service if it is removed.
    PendingIntent service =
      PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
        new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    assert alarmManager != null;
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
    super.onTaskRemoved(rootIntent);
  }
}

For more details,

https://github.com/sachinvarma/Speech-Recognizer

Hope this will help someone in future.

setting JAVA_HOME & CLASSPATH in CentOS 6

Instructions:

  1. Click on the Terminal icon in the desktop panel to open a terminal window and access the command prompt.
  2. Type the command which java to find the path to the Java executable file.
  3. Type the command su - to become the root user.
  4. Type the command vi /root/.bash_profile to open the system bash_profile file in the Vi text editor. You can replace vi with your preferred text editor.
  5. Type export JAVA_HOME=/usr/local/java/ at the bottom of the file. Replace /usr/local/java with the location found in step two.
  6. Save and close the bash_profile file.
  7. Type the command exit to close the root session.
  8. Log out of the system and log back in.
  9. Type the command echo $JAVA_HOME to ensure that the path was set correctly.

set java_home in centos

Where does Chrome store extensions?

For older versions of windows (2k, 2k3, xp)

"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions" 

printf not printing on console

Try setting this before you print:

setvbuf (stdout, NULL, _IONBF, 0);

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Using this attribute is definitely unsafe.

One particular thing it breaks is the ability of a union which contains two or more structs to write one member and read another if the structs have a common initial sequence of members. Section 6.5.2.3 of the C11 standard states:

6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Tw o structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

...

9 EXAMPLE 3 The following is a valid fragment:

union {
    struct {
        int    alltypes;
    }n;
    struct {
        int    type;
        int    intnode;
    } ni;
    struct {
        int    type;
        double doublenode;
    } nf;
}u;
u.nf.type = 1;
u.nf.doublenode = 3.14;
/*
...
*/
if (u.n.alltypes == 1)
if (sin(u.nf.doublenode) == 0.0)
/*
...
*/

When __attribute__((packed)) is introduced it breaks this. The following example was run on Ubuntu 16.04 x64 using gcc 5.4.0 with optimizations disabled:

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

struct s1
{
    short a;
    int b;
} __attribute__((packed));

struct s2
{
    short a;
    int b;
};

union su {
    struct s1 x;
    struct s2 y;
};

int main()
{
    union su s;
    s.x.a = 0x1234;
    s.x.b = 0x56789abc;

    printf("sizeof s1 = %zu, sizeof s2 = %zu\n", sizeof(struct s1), sizeof(struct s2));
    printf("s.y.a=%hx, s.y.b=%x\n", s.y.a, s.y.b);
    return 0;
}

Output:

sizeof s1 = 6, sizeof s2 = 8
s.y.a=1234, s.y.b=5678

Even though struct s1 and struct s2 have a "common initial sequence", the packing applied to the former means that the corresponding members don't live at the same byte offset. The result is the value written to member x.b is not the same as the value read from member y.b, even though the standard says they should be the same.

Spring application context external properties?

This blog can help you. The trick is to use SpEL (spring expression language) to read the system properties like user.home, to read user home directory using SpEL you could use
#{ systemProperties['user.home']} expression inside your bean elements. For example to access your properties file stored in your home directory you could use the following in your PropertyPlaceholderConfigurer, it worked for me.

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:#{ systemProperties['user.home']}/ur_folder/settings.properties</value>
    </property>
</bean>

Using the rJava package on Win7 64 bit with R

The last question has an easy answer:

> .Machine$sizeof.pointer
[1] 8

Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.

EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/... On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)

Structure padding and packing

Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively. Don't do that though. It's not portable and makes compilers generate much slower (and sometimes even buggy) code.

Which maven dependencies to include for spring 3.0?

What classes are missing? The class name itself should be a good clue to the missing module.

FYI, I know its really convenient to include the uber spring jar but this really causes issues when integrating with other projects. One of the benefits behind the dependency system is that it will resolve version conflicts among the dependencies.

If my library depends on spring-core:2.5 and you depend on my library and uber-spring:3.0, you now have 2 versions of spring on your classpath.

You can get around this with exclusions but its much easier to list the dependencies correctly and not have to worry about it.

List columns with indexes in PostgreSQL

Combined with others code and created a view:

CREATE OR REPLACE VIEW view_index AS 
SELECT
     n.nspname  as "schema"
    ,t.relname  as "table"
    ,c.relname  as "index"
    ,pg_get_indexdef(indexrelid) as "def"
FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON n.oid        = c.relnamespace
    JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid
    JOIN pg_catalog.pg_class t ON i.indrelid   = t.oid
WHERE c.relkind = 'i'
    and n.nspname not in ('pg_catalog', 'pg_toast')
    and pg_catalog.pg_table_is_visible(c.oid)
ORDER BY
     n.nspname
    ,t.relname
    ,c.relname;

How to convert an object to a byte array in C#

Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.

Where to place JavaScript in an HTML file?

The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

Getters \ setters for dummies

Although often we are used to seeing objects with public properties without any access control, JavaScript allows us to accurately describe properties. In fact, we can use descriptors in order to control how a property can be accessed and which logic we can apply to it. Consider the following example:

var employee = {
    first: "Boris",
    last: "Sergeev",
    get fullName() {
        return this.first + " " + this.last;
    },
    set fullName(value) {
        var parts = value.toString().split(" ");
        this.first = parts[0] || "";
        this.last = parts[1] || "";
    },
    email: "[email protected]"
};

The final result:

console.log(employee.fullName); //Boris Sergeev
employee.fullName = "Alex Makarenko";

console.log(employee.first);//Alex
console.log(employee.last);//Makarenko
console.log(employee.fullName);//Alex Makarenko

Why I get 411 Length required error?

Google search

2nd result

System.Net.WebException: The remote server returned an error: (411) Length Required.

This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.

This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.

var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";

To fix this error, add an explicit content length to your request before making the API call.

request.ContentLength = 0;

MySQL selecting yesterday's date

You can use:

SELECT SUBDATE(NOW(), 1);

or

SELECT SUBDATE(NOW(), INTERVAL 1 DAY);

or

SELECT NOW() - INTERVAL 1 DAY;

or

SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);

Eclipse fonts and background color

If you are having trouble with Eclipse 2019 and using a dark theme and setting the background and having it not change: There seems to be a recent Eclipse bug. I suggest you look here or here for workarounds.

How to round each item in a list of floats to 2 decimal places?

If you really want an iterator-free solution, you can use numpy and its array round function.

import numpy as np
myList = list(np.around(np.array(myList),2))

How do you see recent SVN log entries?

I like to use -v for verbose mode.
It'll give you the commit id, comments and all affected files.

svn log -v --limit 4

Example of output:

I added some migrations and deleted a test xml file
------------------------------------------------------------------------
r58687 | mr_x | 2012-04-02 15:31:31 +0200 (Mon, 02 Apr 2012) | 1 line Changed
paths: 
A /trunk/java/App/src/database/support    
A /trunk/java/App/src/database/support/MIGRATE    
A /trunk/java/App/src/database/support/MIGRATE/remove_device.sql
D /trunk/java/App/src/code/test.xml

MySQL order by before group by

What you are going to read is rather hacky, so don't try this at home!

In SQL in general the answer to your question is NO, but because of the relaxed mode of the GROUP BY (mentioned by @bluefeet), the answer is YES in MySQL.

Suppose, you have a BTREE index on (post_status, post_type, post_author, post_date). How does the index look like under the hood?

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01')

That is data is sorted by all those fields in ascending order.

When you are doing a GROUP BY by default it sorts data by the grouping field (post_author, in our case; post_status, post_type are required by the WHERE clause) and if there is a matching index, it takes data for each first record in ascending order. That is the query will fetch the following (the first post for each user):

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01')

But GROUP BY in MySQL allows you to specify the order explicitly. And when you request post_user in descending order, it will walk through our index in the opposite order, still taking the first record for each group which is actually last.

That is

...
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC

will give us

(post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31')

Now, when you order the results of the grouping by post_date, you get the data you wanted.

SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC
ORDER BY wp_posts.post_date DESC;

NB:

This is not what I would recommend for this particular query. In this case, I would use a slightly modified version of what @bluefeet suggests. But this technique might be very useful. Take a look at my answer here: Retrieving the last record in each group

Pitfalls: The disadvantages of the approach is that

  • the result of the query depends on the index, which is against the spirit of the SQL (indexes should only speed up queries);
  • index does not know anything about its influence on the query (you or someone else in future might find the index too resource-consuming and change it somehow, breaking the query results, not only its performance)
  • if you do not understand how the query works, most probably you'll forget the explanation in a month and the query will confuse you and your colleagues.

The advantage is performance in hard cases. In this case, the performance of the query should be the same as in @bluefeet's query, because of amount of data involved in sorting (all data is loaded into a temporary table and then sorted; btw, his query requires the (post_status, post_type, post_author, post_date) index as well).

What I would suggest:

As I said, those queries make MySQL waste time sorting potentially huge amounts of data in a temporary table. In case you need paging (that is LIMIT is involved) most of the data is even thrown off. What I would do is minimize the amount of sorted data: that is sort and limit a minimum of data in the subquery and then join back to the whole table.

SELECT * 
FROM wp_posts
INNER JOIN
(
  SELECT max(post_date) post_date, post_author
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author
  ORDER BY post_date DESC
  -- LIMIT GOES HERE
) p2 USING (post_author, post_date)
WHERE post_status='publish' AND post_type='post';

The same query using the approach described above:

SELECT *
FROM (
  SELECT post_id
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author DESC
  ORDER BY post_date DESC
  -- LIMIT GOES HERE
) as ids
JOIN wp_posts USING (post_id);

All those queries with their execution plans on SQLFiddle.

Get current NSDate in timestamp format

To get timestamp from NSDate Swift 3

func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
    let objDateformat: DateFormatter = DateFormatter()
    objDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let strTime: String = objDateformat.string(from: dateToConvert as Date)
    let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
    let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
    let strTimeStamp: String = "\(milliseconds)"
    return strTimeStamp
}

To use

let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)

Can I automatically increment the file build version when using Visual Studio?

There is a visual studio extension Automatic Versions which supports Visual Studio (2012, 2013, 2015) 2017 & 2019.

Screen Shots enter image description here

enter image description here

How to get a certain element in a list, given the position?

Maybe not the most efficient way. But you could convert the list into a vector.

#include <list>
#include <vector>

list<Object> myList;

vector<Object> myVector(myList.begin(), myList.end());

Then access the vector using the [x] operator.

auto x = MyVector[0];

You could put that in a helper function:

#include <memory>
#include <vector>
#include <list>

template<class T>
shared_ptr<vector<T>> 
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
        new vector<string>(List.begin(), List.end()) }
return Vector;
}

Then use the helper funciton like this:

auto MyVector = ListToVector(Object);
auto x = MyVector[0];

How to hide the keyboard when I press return key in a UITextField?

Try this,

[textField setDelegate: self];

Then, in textField delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

How to export non-exportable private key from store

Unfortunately, the tool mentioned above is blocked by several antivirus vendors. If this is the case for you then take a look at the following.

Open the non-exportable cert in the cert store and locate the Thumbprint value.

Next, open regedit to the path below and locate the registry key matching the thumbprint value.

An export of the registry key will contain the complete certificate including the private key. Once exported, copy the export to the other server and import it into the registry.

The cert will appear in the certificate manager with the private key included.

Machine Store: HKLM\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates User Store: HKCU\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates

In a pinch, you could save the export as a backup of the certificate.

How to make a rest post call from ReactJS code?

I think this way also a normal way. But sorry, I can't describe in English ((

_x000D_
_x000D_
    submitHandler = e => {_x000D_
    e.preventDefault()_x000D_
    console.log(this.state)_x000D_
    fetch('http://localhost:5000/questions',{_x000D_
        method: 'POST',_x000D_
        headers: {_x000D_
            Accept: 'application/json',_x000D_
                    'Content-Type': 'application/json',_x000D_
        },_x000D_
        body: JSON.stringify(this.state)_x000D_
    }).then(response => {_x000D_
            console.log(response)_x000D_
        })_x000D_
        .catch(error =>{_x000D_
            console.log(error)_x000D_
        })_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })

List all indexes on ElasticSearch server?

One of the best way to list indices + to display its status together with list : is by simply executing below query.

Note: preferably use Sense to get the proper output.

curl -XGET 'http://localhost:9200/_cat/shards'

The sample output is as below. The main advantage is, it basically shows index name and the shards it saved into, index size and shards ip etc

index1     0 p STARTED     173650  457.1mb 192.168.0.1 ip-192.168.0.1 
index1     0 r UNASSIGNED                                                 
index2     1 p STARTED     173435  456.6mb 192.168.0.1 ip-192.168.0.1 
index2     1 r UNASSIGNED                                                 
...
...
...

Change Git repository directory location.

This did not work for me. I moved a repo from (e.g.) c:\project1\ to c:\repo\project1\ and Git for windows does not show any changes.

git status shows an error because one of the submodules "is not a git repository" and shows the old path. e.g. (names changed to protect IP)

fatal: Not a git repository: C:/project1/.git/modules/subproject/subproject2 fatal: 'git status --porcelain' failed in submodule subproject

I had to manually edit the .git files in the submodules to point to the correct relative path to the submodule's repo (in the main repo's .git/modules directory)

Printing prime numbers from 1 through 100

Just try this. It's easy without any extra builtin functions.

#include <iostream>

int prime(int n,int r){

  for(int i=2;n<=r;i++){
    if(i==2 || i==3 || i==5 || i==7){
      std::cout<<i<<" ";
      n++;
    } else if(i%2==0 || i%3==0 || i%5==0 || i%7==0)
      continue;
    else {
      std::cout<<i<<" ";
      n++;
    }
  }

}

main(){

  prime(1,25);
}

Testing by 2,3,5,7 is good enough for up to 120, so 100 is OK.

There are 25 primes below 100, an 30 below 121 = 11*11.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This exception could point to the LINQ parameter that is named source:

 System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)

As the source parameter in your LINQ query (var nCounts = from sale in sal) is 'sal', I suppose the list named 'sal' might be null.

find without recursion

I believe you are looking for -maxdepth 1.

How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

Updating to latest version of CocoaPods?

This is a really quick & detailed solution

Open the Terminal and execute the following to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

Incase any error occured

Try uninstall and install again:

sudo gem uninstall cocoapods
sudo gem install cocoapods

Run after updating CocoaPods

sudo gem clean cocoapods

After updating CocoaPods, also need to update Podfile.lock file in your project.

Go to your project directory

pod install

How can I change all input values to uppercase using Jquery?

Use css text-transform to display text in all input type text. In Jquery you can then transform the value to uppercase on blur event.

Css:

input[type=text] {
    text-transform: uppercase;
}

Jquery:

$(document).on('blur', "input[type=text]", function () {
    $(this).val(function (_, val) {
        return val.toUpperCase();
    });
});

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Access an arbitrary element in a dictionary in Python

No external libraries, works on both Python 2.7 and 3.x:

>>> list(set({"a":1, "b": 2}.values()))[0]
1

For aribtrary key just leave out .values()

>>> list(set({"a":1, "b": 2}))[0]
'a'

How to fix curl: (60) SSL certificate: Invalid certificate chain

After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

When I initiate a brew update, I was getting the following error:

fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

git config --global http.sslVerify false

I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

I tried rvm osx-ssl-certs update all which stated Already are up to date.

In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

How to get elements with multiple classes

It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName

Callback to a Fragment from a DialogFragment

Activity involved is completely unaware of the DialogFragment.

Fragment class:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mStackLevel = savedInstanceState.getInt("level");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

    mStackLevel++;

    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    switch (type) {

        case DIALOG_FRAGMENT:

            DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
            dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
            dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DIALOG_FRAGMENT:

                if (resultCode == Activity.RESULT_OK) {
                    // After Ok code.
                } else if (resultCode == Activity.RESULT_CANCELED){
                    // After Cancel code.
                }

                break;
        }
    }
}

}

DialogFragment class:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

    MyDialogFragment dialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("num", num);
    dialogFragment.setArguments(bundle);

    return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.ERROR)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton(R.string.ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                        }
                    }
            )
            .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                }
            })
            .create();
}
}

Refused to load the script because it violates the following Content Security Policy directive

To elaborate some more on this, adding

script-src 'self' http://somedomain 'unsafe-inline' 'unsafe-eval';

to the meta tag like so,

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; script-src 'self' https://somedomain.com/ 'unsafe-inline' 'unsafe-eval';  media-src *">

fixes the error.

ASP.NET Web API application gives 404 when deployed at IIS 7

I you are using Visual Studio 2012, download and install Update 2 that Microsoft released recently (as of 4/2013).

Visual Studio 2012 Update 2

There are some bug fixes in that update related to the issue.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Docker - a way to give access to a host USB or serial device?

Adding to the answers above, for those who want a quick way to use an external USB device (HDD, flash drive) working inside docker, and not using priviledged mode:

Find the devpath to your device on the host:

sudo fdisk -l

You can recognize your drive by it's capacity quite easily from the list. Copy this path (for the following example it is /dev/sda2).

Disque /dev/sda2 : 554,5 Go, 57151488 octets, 111624 secteurs
Unités : secteur de 1 × 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets

Mount this devpath (preferable to /media):

sudo mount <drive path> /media/<mount folder name>

You can then use this either as a param to docker run like:

docker run -it -v /media/<mount folder name>:/media/<mount folder name>

or in docker compose under volumes:

services:
  whatevermyserviceis:
    volumes:
      - /media/<mount folder name>:/media/<mount folder name>

And now when you run and enter your container, you should be able to access the drive inside the container at /media/<mount folder name>

DISCLAIMER:

  1. This will probably not work for serial devices such as webcams etc. I have only tested this for USB storage drives.
  2. If you need to reconnect and disconnect devices regularly, this method would be annoying, and also would not work unless you reset the mount path and restart the container.
  3. I used docker 17.06 + as prescribed in the docs

Android difference between Two Dates

I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

Read a file one line at a time in node.js?

require('fs').readFileSync('file.txt', 'utf-8').split(/\r?\n/).forEach(function(line){
  console.log(line);
})

What's the difference between .NET Core, .NET Framework, and Xamarin?

You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.

1. Cross-Platform needs

Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.

Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.

When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.

2. Microservices

When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.

The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.

Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.

3. Best performant and scalable systems

When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.

The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.

As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.

4. Command line style development for Mac, Linux or Windows.

This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.

5. Need side by side of .NET versions per application level.

If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.

6. Windows 10 UWP .NET apps.

In addition, you may also want to read:

  1. When should I NOT use .NET Core?
  2. When should I still use .NET Framework 4.x, instead of .NET Core?
  3. When should I use Xamarin, instead of .NET Core?

Play audio with Python

Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:

> pip install simpleaudio

Then:

import simpleaudio as sa

wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()

Make sure to use uncompressed 16 bit PCM files.

Display a message in Visual Studio's output window when not debug mode?

The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.

How to determine whether a substring is in a different string

enter image description here

Instead Of using find(), One of the easy way is the Use of 'in' as above.

if 'substring' is present in 'str' then if part will execute otherwise else part will execute.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

node.js require all files in a folder?

When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails.

It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that.

yourfile.js

var routes = require("./routes");

index.js

exports.something = require("./routes/something.js");
exports.others = require("./routes/others.js");

If you don't know the filenames you should write some kind of loader.

Working example of a loader:

var normalizedPath = require("path").join(__dirname, "routes");

require("fs").readdirSync(normalizedPath).forEach(function(file) {
  require("./routes/" + file);
});

// Continue application logic here

jQuery: read text file from file system

this one is working

        $.get('1.txt', function(data) {
            //var fileDom = $(data);

            var lines = data.split("\n");

            $.each(lines, function(n, elem) {
                $('#myContainer').append('<div>' + elem + '</div>');
            });
        });

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

min and max value of data type in C

I wrote some macros that return the min and max of any type, regardless of signedness:

#define MAX_OF(type) \
    (((type)(~0LLU) > (type)((1LLU<<((sizeof(type)<<3)-1))-1LLU)) ? (long long unsigned int)(type)(~0LLU) : (long long unsigned int)(type)((1LLU<<((sizeof(type)<<3)-1))-1LLU))
#define MIN_OF(type) \
    (((type)(1LLU<<((sizeof(type)<<3)-1)) < (type)1) ? (long long int)((~0LLU)-((1LLU<<((sizeof(type)<<3)-1))-1LLU)) : 0LL)

Example code:

#include <stdio.h>
#include <sys/types.h>
#include <inttypes.h>

#define MAX_OF(type) \
    (((type)(~0LLU) > (type)((1LLU<<((sizeof(type)<<3)-1))-1LLU)) ? (long long unsigned int)(type)(~0LLU) : (long long unsigned int)(type)((1LLU<<((sizeof(type)<<3)-1))-1LLU))
#define MIN_OF(type) \
    (((type)(1LLU<<((sizeof(type)<<3)-1)) < (type)1) ? (long long int)((~0LLU)-((1LLU<<((sizeof(type)<<3)-1))-1LLU)) : 0LL)

int main(void)
{
    printf("uint32_t = %lld..%llu\n", MIN_OF(uint32_t), MAX_OF(uint32_t));
    printf("int32_t = %lld..%llu\n", MIN_OF(int32_t), MAX_OF(int32_t));
    printf("uint64_t = %lld..%llu\n", MIN_OF(uint64_t), MAX_OF(uint64_t));
    printf("int64_t = %lld..%llu\n", MIN_OF(int64_t), MAX_OF(int64_t));
    printf("size_t = %lld..%llu\n", MIN_OF(size_t), MAX_OF(size_t));
    printf("ssize_t = %lld..%llu\n", MIN_OF(ssize_t), MAX_OF(ssize_t));
    printf("pid_t = %lld..%llu\n", MIN_OF(pid_t), MAX_OF(pid_t));
    printf("time_t = %lld..%llu\n", MIN_OF(time_t), MAX_OF(time_t));
    printf("intptr_t = %lld..%llu\n", MIN_OF(intptr_t), MAX_OF(intptr_t));
    printf("unsigned char = %lld..%llu\n", MIN_OF(unsigned char), MAX_OF(unsigned char));
    printf("char = %lld..%llu\n", MIN_OF(char), MAX_OF(char));
    printf("uint8_t = %lld..%llu\n", MIN_OF(uint8_t), MAX_OF(uint8_t));
    printf("int8_t = %lld..%llu\n", MIN_OF(int8_t), MAX_OF(int8_t));
    printf("uint16_t = %lld..%llu\n", MIN_OF(uint16_t), MAX_OF(uint16_t));
    printf("int16_t = %lld..%llu\n", MIN_OF(int16_t), MAX_OF(int16_t));
    printf("int = %lld..%llu\n", MIN_OF(int), MAX_OF(int));
    printf("long int = %lld..%llu\n", MIN_OF(long int), MAX_OF(long int));
    printf("long long int = %lld..%llu\n", MIN_OF(long long int), MAX_OF(long long int));
    printf("off_t = %lld..%llu\n", MIN_OF(off_t), MAX_OF(off_t));

    return 0;
}

How to use Bootstrap in an Angular project?

  1. npm install --save bootstrap
  2. go to -> angular-cli.json file, find styles properties and just add next sting: "../node_modules/bootstrap/dist/css/bootstrap.min.css", It might be looks like this:

    "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
    ],
    

Foreach value from POST from form

If your post keys have to be parsed and the keys are sequences with data, you can try this:

Post data example: Storeitem|14=data14

foreach($_POST as $key => $value){
    $key=Filterdata($key); $value=Filterdata($value);
    echo($key."=".$value."<br>");
}

then you can use strpos to isolate the end of the key separating the number from the key.

What is the most accurate way to retrieve a user's correct IP address in PHP?

I know this is too late to answer. But you may try these options:

Option 1: (Using curl)

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://ifconfig.me/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// grab URL and pass it to the browser
$ip = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

return $ip;

Option 2: (Works good on mac)

return trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

Option 3: (Just used a trick)

return str_replace('Current IP CheckCurrent IP Address: ', '', strip_tags(file_get_contents('http://checkip.dyndns.com')));

Might be a reference: https://www.tecmint.com/find-linux-server-public-ip-address/

iOS / Android cross platform development

MonoTouch and MonoDroid but what will happen to that part of Attachmate now is anybody's guess. Of course even with the mono solutions you're still creating non cross platform views but the idea being the reuse of business logic.

Keep an eye on http://www.xamarin.com/ it will be interesting to see what they come up with.

Inversion of Control vs Dependency Injection

IoC concept was initially heard during the procedural programming era. Therefore from a historical context IoC talked about inversion of the ownership of control-flow i.e. who owns the responsibility to invoke the functions in the desired order - whether it's the functions themselves or should you invert it to some external entity.

However once the OOP emerged, people began to talk about IoC in OOP context where applications are concerned with object creation and their relationships as well, apart from the control-flow. Such applications wanted to invert the ownership of object-creation (rather than control-flow) and required a container which is responsible for object creation, object life-cycle & injecting dependencies of the application objects thereby eliminating application objects from creating other concrete object.

In that sense DI is not the same as IoC, since it's not about control-flow, however it's a kind of Io*, i.e. Inversion of ownership of object-creation.

What is wrong in my way of explainning DI and IoC?

How to configure Spring Security to allow Swagger URL to be accessed without authentication

For those who using a newer swagger 3 version org.springdoc:springdoc-openapi-ui

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
    }
}

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)

Just put decimal(precision, scale), replacing the precision and scale with your desired values.

I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

how to evenly distribute elements in a div next to each other?

In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.

If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.

<div class="demo">
    <span>Span 1</span>
    <span>Span 2</span>
    <span>Span 3</span>
</div>

CSS:

div.demo {
    display: table;
    width: 100%;
    table-layout: fixed;    /* For cells of equal size */
}
div.demo span {
    display: table-cell;
    text-align: center;
}

Without having to adjust for the number of items.

Example without table-layout:fixed - the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.

Example with table-layout:fixed - the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)

If you want the first and last menu elements to be left and right justified, then you can add the following CSS:

div.demo span:first-child {
    text-align: left;
}
div.demo span:last-child {
    text-align: right;
}

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Simulating Button click in javascript

To simulate an event, you could to use trigger JQuery functionnality.

$('#foo').on('click', function() {
      alert($(this).text());
    });
$('#foo').trigger('click');

Altering column size in SQL Server

alter table Employee alter column salary numeric(22,5)

How to sort an ArrayList in Java

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);

Pygame Drawing a Rectangle

Have you tried this:

PyGame Drawing Basics

Taken from the site:

pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

C# elegant way to check if a property's property is null

The way you're doing it is correct.

You could use a trick like the one described here, using Linq expressions :

int value = ObjectA.NullSafeEval(x => x.PropertyA.PropertyB.PropertyC, 0);

But it's much slower that manually checking each property...

How to open a file / browse dialog using javascript?

Unfortunately, there isn't a good way to browse for files with a JavaScript API. Fortunately, it's easy to create a file input in JavaScript, bind an event handler to its change event, and simulate a user clicking on it. We can do this without modifications to the page itself:

$('<input type="file" multiple>').on('change', function () {
  console.log(this.files);
}).click();

this.files on the second line is an array that contains filename, timestamps, size, and type.

Using Alert in Response.Write Function in ASP.NET

Concatenate the string separating the slash and the word script in this way.

Response.Write("<script language='javascript'>alert('Especifique Usuario y Contraseña');</" + "script>");

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

How to generate .json file with PHP?

Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.

$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT));   // here it will print the array pretty
fclose($fp);

Hope it will works for you....

Git adding files to repo

my problem (git on macOS) was solved by using sudo git instead of just git in all add and commit commands

Visual Studio Expand/Collapse keyboard shortcuts

For collapse, you can try CTRL + M + O and expand using CTRL + M + P. This works in VS2008.

Why does a base64 encoded string have an = sign at the end

Its defined in RFC 2045 as a special padding character if fewer than 24 bits are available at the end of the encoded data.

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

After execute the thread, add these two line of code, and that will solve the issue.

Looper.loop();
Looper.myLooper().quit();

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

What is an NP-complete in computer science?

Honestly, Wikipedia might be the best place to look for an answer to this.

If NP = P, then we can solve very hard problems much faster than we thought we could before. If we solve only one NP-Complete problem in P (polynomial) time, then it can be applied to all other problems in the NP-Complete category.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

how to rename an index in a cluster?

As such there is no direct method to copy or rename index in ES (I did search extensively for my own project)

However a very easy option is to use a popular migration tool [Elastic-Exporter].

http://www.retailmenot.com/corp/eng/posts/2014/12/02/elasticsearch-cluster-migration/

[PS: this is not my blog, just stumbled upon and found it good]

Thereby you can copy index/type and then delete the old one.

How to delete from a text file, all lines that contain a specific string?

Delete lines from all files that match the match

grep -rl 'text_to_search' . | xargs sed -i '/text_to_search/d'

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

You can directly go to http://127.0.0.1:8080/apex/f?p=4950 and you will get Home Page Of your Oracle Database.

Right click on the shortcut > choose properties > go to security tab > Choose Authenticated Users > and give permission to do everything

and now try to change the URL you will be able to do it.

Hope this help

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

'dict' object has no attribute 'has_key'

In python3, has_key(key) is replaced by __contains__(key)

Tested in python3.7:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))

What's the difference between session.persist() and session.save() in Hibernate?

From this forum post

persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

Set multiple system properties Java command line

You may be able to use the JAVA_TOOL_OPTIONS environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:

In many environments, the command line is not readily accessible to start the application with the necessary command-line options.

This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.

When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.

However this environment variable use may be disabled for security reasons.

In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.

See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS environment variable.

screenshot showing use of JAVA_TOOL_OPTIONS environment variable

Safe navigation operator (?.) or (!.) and null property paths

Building on @Pvl's answer, you can include type safety on your returned value as well if you use overrides:

function dig<
  T,
  K1 extends keyof T
  >(obj: T, key1: K1): T[K1];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1]
  >(obj: T, key1: K1, key2: K2): T[K1][K2];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2]
  >(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4): T[K1][K2][K3][K4];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): T[K1][K2][K3][K4][K5];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5):
  T[K1] |
  T[K1][K2] |
  T[K1][K2][K3] |
  T[K1][K2][K3][K4] |
  T[K1][K2][K3][K4][K5] {
    let value: any = obj && obj[key1];

    if (key2) {
      value = value && value[key2];
    }

    if (key3) {
      value = value && value[key3];
    }

    if (key4) {
      value = value && value[key4];
    }

    if (key5) {
      value = value && value[key5];
    }

    return value;
}

Example on playground.

git push rejected

First, attempt to pull from the same refspec that you are trying to push to.

If this does not work, you can force a git push by using git push -f <repo> <refspec>, but use caution: this method can cause references to be deleted on the remote repository.

Does bootstrap have builtin padding and margin classes?

This is taken from the docs and it works very well. Here is the link

  • m - for classes that set margin
  • p - for classes that set padding

Where sides are one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • l - for classes that set margin-left or padding-left
  • r - for classes that set margin-right or padding-right

if you want to give margin to the left use mt-x where x stands for [1,2,3,4,5]

same for padding

example be like

<div class = "mt-5"></div>
<div class = "pt-5"></div>

Use only p-x or m-x for getting padding and margin of x from all sides.

How to display activity indicator in middle of the iphone screen?

Hope this will work:

// create activity indicator 
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] 
    initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];

...
 [self.view addSubview:activityIndicator];
// release it
[activityIndicator release];

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
            ...
            .antMatchers(PUBLIC_AUTH).permitAll()
            .and().httpBasic()
//    https://www.baeldung.com/spring-security-basic-authentication
            .authenticationEntryPoint(authBasicAuthenticationEntryPoint())
            ...

@Bean
public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
    return new BasicAuthenticationEntryPoint() {
        {
            setRealmName("pirsApp");
        }

        @Override
        public void commence
                (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
                throws IOException, ServletException {
            if (request.getRequestURI().equals(PUBLIC_AUTH)) {
                response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
            } else {
                super.commence(request, response, authEx);
            }
        }
    };
}

How to convert a color integer to a hex String in Android?

Integer value of ARGB color to hexadecimal string:

String hex = Integer.toHexString(color); // example for green color FF00FF00

Hexadecimal string to integer value of ARGB color:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);

How can I get dictionary key as variable directly in Python (not by searching from value)?

This code below is to create map to manager players point. The goal is to concatenate the word "player" with a sequential number.

players_numbers = int(input('How many girls will play? ')) #First - input receive a input about how many people will play

players = {}  
counter = 1

for _ in range(players_numbers): #sum one, for the loop reach the correct number
    player_dict = {f'player{counter}': 0} #concatenate the word player with the player number. the initial point is 0.
    players.update(player_dict) #update the dictionary with every player
    counter = counter + 1
    print(players)

Output >>> {'player1': 0, 'player2': 0, 'player3': 0}...

how to change language for DataTable

It is indeed

language: {
 url: '//URL_TO_CDN'
}

The problem is not all of the DataTables (As of this writing) are valid JSON. The Traditional Chinese file for instance is one of them.

To get around this I wrote the following code in JavaScript:

  var dataTableLanguages = {
    'es': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json',
    'fr': '//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json',
    'ar': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Arabic.json',
    'zh-TW': {
      "processing": "???...",
      "loadingRecords": "???...",
      "lengthMenu": "?? _MENU_ ???",
      "zeroRecords": "???????",
      "info": "??? _START_ ? _END_ ???,? _TOTAL_ ?",
      "infoEmpty": "??? 0 ? 0 ???,? 0 ?",
      "infoFiltered": "(? _MAX_ ??????)",
      "infoPostFix": "",
      "search": "??:",
      "paginate": {
        "first": "???",
        "previous": "???",
        "next": "???",
        "last": "????"
      },
      "aria": {
        "sortAscending": ": ????",
        "sortDescending": ": ????"
      }
    }
  };
  var language = dataTableLanguages[$('html').attr('lang')];

  var opts = {...};
  
  if (language) {
    if (typeof language === 'string') {
       opts.language = {
         url: language
       };
    } else {
       opts.language = language;
    }
  }

Now use the opts as option object for data table like

$('#list-table').DataTable(opts)

Javascript, viewing [object HTMLInputElement]

Say your variable is myNode, you can do myNode.value to retrieve the value of input elements.

Firebug has a "DOM" tab which shows useful DOM attributes.

Also see the mozilla page for a reference: https://developer.mozilla.org/en-US/docs/DOM/HTMLInputElement

How to ignore SSL certificate errors in Apache HttpClient 4.0

Tested on 4.5.4:

            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();

            CloseableHttpClient httpClient = HttpClients
                    .custom()
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .setSSLContext(sslContext)
                    .build();

.htaccess 301 redirect of single page

You could also use a RewriteRule if you wanted the ability to template match and redirect urls.

How to initialize an array of objects in Java

If you are unsure of the size of the array or if it can change you can do this to have a static array.

ArrayList<Player> thePlayersList = new ArrayList<Player>(); 

thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g

Players[] thePlayers = thePlayersList.toArray();

Splitting words into letters in Java

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

How to revert a merge commit that's already pushed to remote branch?

If you want to revert a merge commit, here is what you have to do.

  1. First, check the git log to find your merge commit's id. You'll also find multiple parent ids associated with the merge (see image below).

enter image description here

Note down the merge commit id shown in yellow. The parent IDs are the ones written in the next line as Merge: parent1 parent2. Now...

Short Story:

  1. Switch to branch on which the merge was made. Then Just do the git revert <merge commit id> -m 1 which will open a vi console for entering commit message. Write, save, exit, done!

Long story:

  1. Switch to branch on which the merge was made. In my case, it is the test branch and I'm trying to remove the feature/analytics-v3 branch from it.

  2. git revert is the command which reverts any commit. But there is a nasty trick when reverting a merge commit. You need to enter the -m flag otherwise it will fail. From here on, you need to decide whether you want to revert your branch and make it look like exactly it was on parent1 or parent2 via:

git revert <merge commit id> -m 1 (reverts to parent2)

git revert <merge commit id> -m 2 (reverts to parent1)

You can git log these parents to figure out which way you want to go and that's the root of all the confusion.

In CSS what is the difference between "." and "#" when declaring a set of styles?

Here is my aproach of explaining te rules .style and #style are part of a matrix. that if not in the right order, they can override each other, or cause conflicts.

Here is the line up.

Matrix

#style 0,0,1,0 id

.style 0,1,0,0 class

if you want override these two you can use <style></style> witch has a matrix level or 1,0,0,0. And @media query's will override everything above... I am not sure about this but i think the ID selector # can only be used once in a page.

Hibernate Query By Example and Projections

The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:

http://opensource.atlassian.com/projects/hibernate/browse/HHH-817

Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/

Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.

Best Practices for securing a REST API / web service

As @Nathan ended up with which is a simple HTTP Header, and some had said OAuth2 and client side SSL certificates. The gist of it is this... your REST API shouldn't have to handle security as that should really be outside the scope of the API.

Instead a security layer should be put on top of it, whether it is an HTTP Header behind a web proxy (a common approach like SiteMinder, Zermatt or even Apache HTTPd), or as complicated as OAuth 2.

The key thing is the requests should work without any end-user interaction. All that is needed is to ensure that the connection to the REST API is authenticated. In Java EE we have the notion of a userPrincipal that can be obtained on an HttpServletRequest. It is also managed in the deployment descriptor that a URL pattern can be secure so the REST API code does not need to check anymore.

In the WCF world, I would use ServiceSecurityContext.Current to get the current security context. You need to configure you application to require authentication.

There is one exception to the statement I had above and that's the use of a nonce to prevent replays (which can be attacks or someone just submitting the same data twice). That part can only be handled in the application layer.

The request failed or the service did not respond in a timely fashion?

If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.

Bash script to run php script

You just need to set :

/usr/bin/php path_to_your_php_file

in your crontab.

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

How to grep Git commit diffs or contents for a certain word?

You can try the following command:

git log --patch --color=always | less +/searching_string

or using grep in the following way:

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

Run this command in the parent directory where you would like to search.

Namespace for [DataContract]

[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .

System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

you need to specify the min and target sdk version in the manifest file.
If not the android.permission.READ_PHONE_STATE will be added automaticly while exporting your apk file.

<uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />

How can I add an empty directory to a Git repository?

You can't. This is an intentional design decision by the Git maintainers. Basically, the purpose of a Source Code Management System like Git is managing source code and empty directories aren't source code. Git is also often described as a content tracker, and again, empty directories aren't content (quite the opposite, actually), so they are not tracked.

Changing image on hover with CSS/HTML

Another option is to use JS:

<img src='LibraryTransparent.png' onmouseover="this.src='LibraryHoverTrans.png';" onmouseout="this.src='LibraryTransparent.png';" />

Listing files in a specific "folder" of a AWS S3 bucket

S3 does not have directories, while you can list files in a pseudo directory manner like you demonstrated, there is no directory "file" per-se.
You may of inadvertently created a data file called users/<user-id>/contacts/<contact-id>/.

initializing a boolean array in java

The main difference is that Boolean is an object and boolean is an primitive.

  • Object default value is null;
  • boolean default value is false;

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Using cut command to remove multiple columns

Sometimes it's easier to think in terms of which fields to exclude.

If the number of fields not being cut (not being retained in the output) is small, it may be easier to use the --complement flag, e.g. to include all fields 1-20 except not 3, 7, and 12 -- do this:

cut -d, --complement -f3,7,12 <inputfile

Rather than

cut -d, -f-2,4-6,8-11,13-

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Mocking member variables of a class using Mockito

If you can't change the member variable, then the other way around this is to use powerMockit and call

Second second = mock(Second.class)
when(second.doSecond()).thenReturn("Stubbed Second");
whenNew(Second.class).withAnyArguments.thenReturn(second);

Now the problem is that ANY call to new Second will return the same mocked instance. But in your simple case this will work.

How do I run two commands in one line in Windows CMD?

No, cd / && tree && echo %time%. The time echoed is at when the first command is executed.

The piping has some issue, but it is not critical as long as people know how it works.

ADB.exe is obsolete and has serious performance problems

None of the top-voted answers worked for me, except when I unchecked "Use detected ADB location" as mentioned above by @???. Fortunately, in my case though, the message didn't show up, even when I turned it back on. In other words, the problem might be resolved by restarting "Use detected ADB location" :)

Bootstrap button - remove outline on Chrome OS X

If someone is using bootstrap sass note the code is on the _reboot.scss file like this:

button:focus {
  outline: 1px dotted;
  outline: 5px auto -webkit-focus-ring-color;
}

So if you want to keep the _reboot file I guess feel free to override with plain css instead of trying to look for a variable to change.

Docker is installed but Docker Compose is not ? why?

first of all please check if docker-compose is installed,

$ docker-compose -v

If it is not installed, please refer to the installation guide https://docs.docker.com/compose/install/ If installed give executable permission to the binary.

$ chmod +x /usr/local/bin/docker-compose

check if this works.

Parse XLSX with Node and create json

I found a better way of doing this

  function genrateJSONEngine() {
    var XLSX = require('xlsx');
    var workbook = XLSX.readFile('test.xlsx');
    var sheet_name_list = workbook.SheetNames;
    sheet_name_list.forEach(function (y) {
      var array = workbook.Sheets[y];

      var first = array[0].join()
      var headers = first.split(',');

      var jsonData = [];
      for (var i = 1, length = array.length; i < length; i++) {

        var myRow = array[i].join();
        var row = myRow.split(',');

        var data = {};
        for (var x = 0; x < row.length; x++) {
          data[headers[x]] = row[x];
        }
        jsonData.push(data);

      }

Access event to call preventdefault from custom function originating from onclick attribute of tag

I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

A quick example.

_x000D_
_x000D_
function sayHi(e) {_x000D_
   e.preventDefault();_x000D_
   alert("hi");_x000D_
}
_x000D_
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>
_x000D_
_x000D_
_x000D_

  1. Run it as is and notice that the link does no redirect to Google after the alert.
  2. Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).

How to view an HTML file in the browser with Visual Studio Code

If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don't have to press F5 every time on your page:

Here is how to do it:

  • Open command prompt (cmd) and type

    npm install --save-dev gulp-webserver

  • Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code

tasks.json

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": [
        {
            "taskName": "webserver",
            "isBuildCommand": true,
            "showOutput": "always"
        }
    ]
}
  • In the root directory of your project add gulpfile.js and enter following code:

gulpfile.js

var gulp = require('gulp'),
    webserver = require('gulp-webserver');

gulp.task('webserver', function () {
    gulp.src('app')
        .pipe(webserver({
            livereload: true,
            open: true
        }));
});
  • Now in VS Code enter Ctrl+Shift+P and type "Run Task" when you enter it you will see your task "webserver" selected and press enter.

Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.

Here is an information on how to configure 'gulp-webserver' for instance port, and what page to load, ...

You can also run your task just by entering Ctrl+P and type task webserver

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

Can I change the name of `nohup.out`?

my start.sh file:

#/bin/bash

nohup forever -c php artisan your:command >>storage/logs/yourcommand.log 2>&1 &

There is one important thing only. FIRST COMMAND MUST BE "nohup", second command must be "forever" and "-c" parameter is forever's param, "2>&1 &" area is for "nohup". After running this line then you can logout from your terminal, relogin and run "forever restartall" voilaa... You can restart and you can be sure that if script halts then forever will restart it.

I <3 forever

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

Generate random int value from 3 to 6

Simply:

DECLARE @MIN INT=3; --We define minimum value, it can be generated.
DECLARE @MAX INT=6; --We define maximum value, it can be generated.

SELECT @MIN+FLOOR((@MAX-@MIN+1)*RAND(CONVERT(VARBINARY,NEWID()))); --And then this T-SQL snippet generates an integer between minimum and maximum integer values.

You can change and edit this code for your needs.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Hi this is due to new version of the jQuery => 1.9.0

you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/

jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js

replace :

<script src="http://code.jquery.com/jquery-latest.js"></script>

by :

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

in your page and its working.

When is it acceptable to call GC.Collect?

Scott Holden's blog entry on when to (and when not to) call GC.Collect is specific to the .NET Compact Framework, but the rules generally apply to all managed development.

How to parse date string to Date?

The pattern is wrong. You have a 3-letter day abbreviation, so it must be EEE. You have a 3-letter month abbreviation, so it must be MMM. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the SimpleDateFormat locale to English as well, otherwise it will use the platform default locale which may not be English per se.

public static void main(String[] args) throws Exception {
    String target = "Thu Sep 28 20:29:30 JST 2000";
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    Date result =  df.parse(target);  
    System.out.println(result);
}

This prints here

Thu Sep 28 07:29:30 BOT 2000

which is correct as per my timezone.

I would also reconsider if you wouldn't rather like to use HH instead of kk. Read the javadoc for details about valid patterns.

How can I selectively merge or pick changes from another branch in Git?

This is my workflow for merging selective files.

# Make a new branch (this will be temporary)
git checkout -b newbranch

# Grab the changes
git merge --no-commit  featurebranch

# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)

# Now you can chose which files are to be merged.
git add -p

# Remember to "git add" any new files you wish to keep
git commit

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

10

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

How do I get this javascript to run every second?

You can use setInterval:

var timer = setInterval( myFunction, 1000);

Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.

Validate a username and password against Active Directory?

If you are stuck with .NET 2.0 and managed code, here is another way that works whith local and domain accounts:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Diagnostics;

static public bool Validate(string domain, string username, string password)
{
    try
    {
        Process proc = new Process();
        proc.StartInfo = new ProcessStartInfo()
        {
            FileName = "no_matter.xyz",
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            LoadUserProfile = true,
            Domain = String.IsNullOrEmpty(domain) ? "" : domain,
            UserName = username,
            Password = Credentials.ToSecureString(password)
        };
        proc.Start();
        proc.WaitForExit();
    }
    catch (System.ComponentModel.Win32Exception ex)
    {
        switch (ex.NativeErrorCode)
        {
            case 1326: return false;
            case 2: return true;
            default: throw ex;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return false;
}   

Error while installing json gem 'mkmf.rb can't find header files for ruby'

For Ubuntu 18, after checking log file mentioned while install

Results logged to /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

with

less /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

I noticed that make is not found. So installed make by

sudo apt-get install make

everything worked.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

How to convert C++ Code to C

Maybe good ol' cfront will do?

Changing variable names with Python for loops

You could access your class's __dict__ attribute:

for i in range(3)
     self.__dict__['group%d' % i]=self.getGroup(selected, header+i)

But why can't you just use an array named group?

shell script to remove a file if it already exist

Something like this would work

#!/bin/sh

if [ -fe FILE ]
then 
    rm FILE
fi 

-f checks if it's a regular file

-e checks if the file exist

Introduction to if for more information

EDIT : -e used with -f is redundant, fo using -f alone should work too

Where to find Application Loader app in Mac?

I didn't find application loader anywhere, even in spotlight. You can open it through xcode.

Go to Xcode > Open Developer Tools > Application Loader

How to retry image pull in a kubernetes Pods?

$ kubectl replace --force -f <resource-file>

if all goes well, you should see something like:

<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced

details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

How do I create a new line in Javascript?

you can also pyramid of stars like this

for (var i = 5; i >= 1; i--) {
     var py = "";
     for (var j = i; j >= 1; j--) {
         py += j;

     }
     console.log(py);
 }

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

How to set URL query params in Vue with Vue-Router

Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.

const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });

windows batch file rename

I am assuming you know the length of the part before the _ and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.

cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)

I just came up with this script, and I did not test it. Check out this and that for more info.

IF you want to assume you don't know the positions of the _ and the lengths and the extension, I think you could do something with for loops to check the index of the _, then the last index of the ., wrap it in a goto thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.

"google is not defined" when using Google Maps V3 in Firefox remotely

Try using this:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 

Is there a "null coalescing" operator in JavaScript?

It will hopefully be available soon in Javascript, as it is in proposal phase as of Apr, 2020. You can monitor the status here for compatibility and support - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

For people using Typescript, you can use the nullish coalescing operator from Typescript 3.7

From the docs -

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined. When we write code like

let x = foo ?? bar();

this is a new way to say that the value foo will be used when it’s “present”; but when it’s null or undefined, calculate bar() in its place.

PDF Parsing Using Python - extracting formatted and plain texts

That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.

I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.

Specify JDK for Maven to use

For Java 9 :

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>9</source>
                <target>9</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Images can't contain alpha channels or transparencies

Faced same issue, Try using JPG format !! What worked for me here was using a jpg file instead of PNG as jpg files don't use alpha or transparency features. I did it via online image converter or you can also open the image in preview and then File->Export and uncheck alpha as option to save the image and use this image.

How to select rows that have current day's timestamp?

Or you could use the CURRENT_DATE alternative, with the same result:

SELECT * FROM yourtable WHERE created >= CURRENT_DATE

Examples from database.guide

How do I run all Python unit tests in a directory?

Because Test discovery seems to be a complete subject, there is some dedicated framework to test discovery :

More reading here : https://wiki.python.org/moin/PythonTestingToolsTaxonomy

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Modify tick label text

If you do not work with fig and ax and you want to modify all labels (e.g. for normalization) you can do this:

labels, locations = plt.yticks()
plt.yticks(labels, labels/max(labels))

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I connected to a VPN and the connection accomplished. I was using school's WiFi which has some restrictions apparently.

Is there a simple way to use button to navigate page as a link does in angularjs

If you're OK with littering your markup a bit, you could do it the easy way and just wrap your <button> with an anchor (<a>) link.

<a href="#/new-page.html"><button>New Page<button></a>

Also, there is nothing stopping you from styling an anchor link to look like a <button>


as pointed out in the comments by @tronman, this is not technically valid html5, but it should not cause any problems in practice

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

Swift - How to hide back button in navigation item?

You may try with the below code

override func viewDidAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

iOS how to set app icon and launch images

I found App called Iconizer. You can find repository on github. Iconizer can generate app icons for OS X, iPad, iPhone, CarPlay and Apple Watch with just one image.

Simply Drag and Drop your icon onto Iconizer, select the platforms you need and whether or not you want all platforms generated into one asset catalog, then hit export.

After that just replace (delete and import) your AppIcon in the Assets.xcassets

How to extract the substring between two markers?

Using regular expressions - documentation for further reference

import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

or:

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

Python variables as keys to dict

The globals() function returns a dictionary containing all your global variables.

>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}

There is also a similar function called locals().

I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.

Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:

fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3

Multiple Cursors in Sublime Text 2 Windows

I find using vintage mode works really well with sublime multiselect.

My most used keys would be "w" for jumping a word, "^" and "$" to move to first/last character of the line. Combinations like "2dw" (delete the next two words after the cursor) make using multiselect really powerful.

This sounds obvious but has really sped up my workflow, especially when editing HTML.

What's the difference between the Window.Loaded and Window.ContentRendered events

I think there is little difference between the two events. To understand this, I created a simple example to manipulation:

XAML

<Window x:Class="LoadedAndContentRendered.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="MyWindow"
        Title="MainWindow" Height="1000" Width="525"
        WindowStartupLocation="CenterScreen"
        ContentRendered="Window_ContentRendered"     
        Loaded="Window_Loaded">

    <Grid Name="RootGrid">        
    </Grid>
</Window>

Code behind

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered");
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded");
}   

In this case the message Loaded appears the first after the message ContentRendered. This confirms the information in the documentation.

In general, in WPF the Loaded event fires if the element:

is laid out, rendered, and ready for interaction.

Since in WPF the Window is the same element, but it should be generally content that is arranged in a root panel (for example: Grid). Therefore, to monitor the content of the Window and created an ContentRendered event. Remarks from MSDN:

If the window has no content, this event is not raised.

That is, if we create a Window:

<Window x:Class="LoadedAndContentRendered.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Name="MyWindow"        
    ContentRendered="Window_ContentRendered" 
    Loaded="Window_Loaded" />

It will only works Loaded event.

With regard to access to the elements in the Window, they work the same way. Let's create a Label in the main Grid of Window. In both cases we have successfully received access to Width:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}   

As for the Styles and Templates, at this stage they are successfully applied, and in these events we will be able to access them.

For example, we want to add a Button:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "ContentRendered Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Right;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "Loaded Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Left;
}

In the case of Loaded event, Button to add to Grid immediately at the appearance of the Window. In the case of ContentRendered event, Button to add to Grid after all its content will appear.

Therefore, if you want to add items or changes before load Window you must use the Loaded event. If you want to do the operations associated with the content of Window such as taking screenshots you will need to use an event ContentRendered.

How to convert an entire MySQL database characterset and collation to UTF-8?

You can also DB tool Navicat, which does it more easier.

  • Siva.

Right Click Your Database & select DB Properties & Change as you desired in Drop Down

enter image description here

How to check if $? is not equal to zero in unix shell scripting?

function assert_exit_code {
    rc=$?; if [[ $rc != 0 ]]; then echo "$1" 1>&2; fi
}

...

execute.sh

assert_exit_code "execute.sh has failed"

dereferencing pointer to incomplete type

I saw a question the other day where someone inadvertently used an incomplete type by specifying something like

struct a {
    int q; 
}; 
struct A *x; 
x->q = 3;

The compiler knew that struct A was a struct, despite A being totally undefined, by virtue of the struct keyword.

That was in C++, where such usage of struct is atypical (and, it turns out, can lead to foot-shooting). In C if you do

typedef struct a {
    ...
} a;

then you can use a as the typename and omit the struct later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.

How to dynamically change a web page's title?

I want to say hello from the future :) Things that happened recently:

  1. Google now runs javascript that is on your website1
  2. People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google1
  3. you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that1

So to answer your question you can safely change title and other meta tags from javascript (you can also add something like https://prerender.io if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple:

if (document.title != newTitle) {
    document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);

Just make sure that css and javascript is not blocked in robots.txt, you can use Fetch as Google service in Google Webmaster Tools.

1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.

Simple way to compare 2 ArrayLists

As far as I understand it correctly, I think it's easiest to work with 4 lists: - Your sourceList - Your destinationList - A removedItemsList - A newlyAddedItemsList

How do I check if a column is empty or null in MySQL?

In my case, space was entered in the column during the data import and though it looked like an empty column its length was 1. So first of all I checked the length of the empty looking column using length(column) then based on this we can write search query

SELECT * FROM TABLE WHERE LENGHT(COLUMN)= 0;

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

Make content horizontally scroll inside a div

The problem is that your imgs will always bump down to the next line because of the containing div.

In order to get around this, you need to place the imgs in their own div with a width wide enough to hold all of them. Then you can use your styles as is.

So, when I set the imgs to 120px each and place them inside a

div#insideDiv{
    width:800px;
}

it all works.

Adjust width as necessary.

See http://jsfiddle.net/jasongennaro/8YfRe/

How to sort in mongoose?

Mongoose v5.x.x

sort by ascending order

Post.find({}).sort('field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });

Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });

sort by descending order

Post.find({}).sort('-field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });


Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });

For Details: https://mongoosejs.com/docs/api.html#query_Query-sort

Message Queue vs. Web Services?

When you use a web service you have a client and a server:

  1. If the server fails the client must take responsibility to handle the error.
  2. When the server is working again the client is responsible of resending it.
  3. If the server gives a response to the call and the client fails the operation is lost.
  4. You don't have contention, that is: if million of clients call a web service on one server in a second, most probably your server will go down.
  5. You can expect an immediate response from the server, but you can handle asynchronous calls too.

When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:

  1. If the server fails, the queue persist the message (optionally, even if the machine shutdown).
  2. When the server is working again, it receives the pending message.
  3. If the server gives a response to the call and the client fails, if the client didn't acknowledge the response the message is persisted.
  4. You have contention, you can decide how many requests are handled by the server (call it worker instead).
  5. You don't expect an immediate synchronous response, but you can implement/simulate synchronous calls.

Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.

How to create a temporary directory/folder in Java?

Just for completion, this is the code from google guava library. It is not my code, but I think it is valueable to show it here in this thread.

  /** Maximum loop count when creating temp directories. */
  private static final int TEMP_DIR_ATTEMPTS = 10000;

  /**
   * Atomically creates a new directory somewhere beneath the system's temporary directory (as
   * defined by the {@code java.io.tmpdir} system property), and returns its name.
   *
   * <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
   * create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
   * delete the file and create a directory in its place, but this leads a race condition which can
   * be exploited to create security vulnerabilities, especially when executable files are to be
   * written into the directory.
   *
   * <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
   * and that it will not be called thousands of times per second.
   *
   * @return the newly-created directory
   * @throws IllegalStateException if the directory could not be created
   */
  public static File createTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    String baseName = System.currentTimeMillis() + "-";

    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
      File tempDir = new File(baseDir, baseName + counter);
      if (tempDir.mkdir()) {
        return tempDir;
      }
    }
    throw new IllegalStateException(
        "Failed to create directory within "
            + TEMP_DIR_ATTEMPTS
            + " attempts (tried "
            + baseName
            + "0 to "
            + baseName
            + (TEMP_DIR_ATTEMPTS - 1)
            + ')');
  }

Array String Declaration

I think the beginning to the resolution to this issue is the fact that the use of the for loop or any other function or action can not be done in the class definition but needs to be included in a method/constructor/block definition inside of a class.

How can I count the number of children?

What if you are using this to determine the current selector to find its children so this holds: <ol> then there is <li>s under how to write a selector var count = $(this+"> li").length; wont work..

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

Functional programming vs Object Oriented programming

You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.

Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.

Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.

Many modern languages are multi-paradigm.

Recommended readings

As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated:

How to generate different random numbers in a loop in C++?

Try moving the seed srand outside the loop like so:

srand ( time(NULL) );
for (int t=0;t<10;t++)
{
    int random_x;
    random_x = rand() % 100;
    cout<< "\nRandom X = "<<random_x;
} 

As Mark Ransom says in the comment, moving the seed outside the loop will only help if the loop is not residing in a function you are calling several times.

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

How to parse XML to R data frame

Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:

library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()

# Start time
data %>% 
  xml_find_all("//start-valid-time") %>% 
  xml_text()

# Temperature
data %>% 
  xml_find_all("//temperature[@type='hourly']/value") %>% 
  xml_text() %>% 
  as.integer()

Selenium -- How to wait until page is completely loaded

You can do this in many ways before clicking on add items:

WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.


or

wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));

You can also wait like this. If you want to wait until invisible of previous page element:

wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));

Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait and its documentation.

https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

How to reduce the image size without losing quality in PHP

You can resize and then use imagejpeg()

Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.

imagejpeg($tn, $save, 75);

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

This is what I do on debian - I suspect it should work on ubuntu (amend the version as required + adapt the folder where you want to copy the JDK files as you wish, I'm using /opt/jdk):

wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u71-b15/jdk-8u71-linux-x64.tar.gz
sudo mkdir /opt/jdk
sudo tar -zxf jdk-8u71-linux-x64.tar.gz -C /opt/jdk/
rm jdk-8u71-linux-x64.tar.gz

Then update-alternatives:

sudo update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_71/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_71/bin/javac 1

Select the number corresponding to the /opt/jdk/jdk1.8.0_71/bin/java when running the following commands:

sudo update-alternatives --config java
sudo update-alternatives --config javac

Finally, verify that the correct version is selected:

java -version
javac -version

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

enter image description here

  1. Go to tools->options.
  2. Make sure the above check boxes are checked.

MongoDB "root" user

While out of the box, MongoDb has no authentication, you can create the equivalent of a root/superuser by using the "any" roles to a specific user to the admin database.

Something like this:

use admin
db.addUser( { user: "<username>",
          pwd: "<password>",
          roles: [ "userAdminAnyDatabase",
                   "dbAdminAnyDatabase",
                   "readWriteAnyDatabase"

] } )

Update for 2.6+

While there is a new root user in 2.6, you may find that it doesn't meet your needs, as it still has a few limitations:

Provides access to the operations and all the resources of the readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and clusterAdmin roles combined.

root does not include any access to collections that begin with the system. prefix.

Update for 3.0+

Use db.createUser as db.addUser was removed.

Update for 3.0.7+

root no longer has the limitations stated above.

The root has the validate privilege action on system. collections. Previously, root does not include any access to collections that begin with the system. prefix other than system.indexes and system.namespaces.

Function to Calculate a CRC16 Checksum

Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.

unsigned short crc16(const unsigned char* data_p, unsigned char length){
    unsigned char x;
    unsigned short crc = 0xFFFF;

    while (length--){
        x = crc >> 8 ^ *data_p++;
        x ^= x>>4;
        crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
    }
    return crc;
}

How do you make an element "flash" in jQuery

You could use the highlight effect in jQuery UI to achieve the same, I guess.

Which @NotNull Java annotation should I use?

If anyone is just looking for the IntelliJ classes: you can get them from the maven repository with

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations</artifactId>
    <version>15.0</version>
</dependency> 

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

How can I check MySQL engine type for a specific table?

If you are a linux user:

To show the engines for all tables for all databases on a mysql server, without tables information_schema, mysql, performance_schema:

less < <({ for i in $(mysql -e "show databases;" | cat | grep -v -e Database-e information_schema -e mysql -e performance_schema); do echo "--------------------$i--------------------";  mysql -e "use $i; show table status;"; done } | column -t)

You might love this, if you are on linux, at least.

Will open all info for all tables in less, press -S to chop overly long lines.

Example output:

--------------------information_schema--------------------
Name                                                        Engine              Version  Row_format  Rows   Avg_row_length  Data_length  Max_data_length     Index_length  Data_free  Auto_increment  Create_time  Update_time  Check_time  C
CHARACTER_SETS                                              MEMORY              10       Fixed       NULL   384             0            16434816            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLLATIONS                                                  MEMORY              10       Fixed       NULL   231             0            16704765            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLLATION_CHARACTER_SET_APPLICABILITY                       MEMORY              10       Fixed       NULL   195             0            16357770            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLUMNS                                                     MyISAM              10       Dynamic     NULL   0               0            281474976710655     1024          0          NULL            2015-07-13   15:48:45     2015-07-13  1
COLUMN_PRIVILEGES                                           MEMORY              10       Fixed       NULL   2565            0            16757145            0             0          NULL            2015-07-13   15:48:45     NULL        N
ENGINES                                                     MEMORY              10       Fixed       NULL   490             0            16574250            0             0          NULL            2015-07-13   15:48:45     NULL        N
EVENTS                                                      MyISAM              10       Dynamic     NULL   0               0            281474976710655     1024          0          NULL            2015-07-13   15:48:45     2015-07-13  1
FILES                                                       MEMORY              10       Fixed       NULL   2677            0            16758020            0             0          NULL            2015-07-13   15:48:45     NULL        N
GLOBAL_STATUS                                               MEMORY              10       Fixed       NULL   3268            0            16755036            0             0          NULL            2015-07-13   15:48:45     NULL        N
GLOBAL_VARIABLES                                            MEMORY              10       Fixed       NULL   3268            0            16755036            0             0          NULL            2015-07-13   15:48:45     NULL        N
KEY_COLUMN_USAGE                                            MEMORY              10       Fixed       NULL   4637            0            16762755            0 

.
.
.

Change the Theme in Jupyter Notebook?

For Dark Mode Only: -

I have used Raleway Font for styling

To C:\User\UserName\.jupyter\custom\custom.css file

append the given styles, this is specifically for Dark Mode for jupyter notebook...

This should be your current custom.css file: -

/* This file contains any manual css for this page that needs to override the global styles.
    This is only required when different pages style the same element differently. This is just
    a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}

#jupyter-main-app {
    position: relative;
}

Content to be append starts now

.header-bar {
    display: none;
}

#header-container img {
    display: none;
}

#notebook_name {
    margin-left: 0px !important;
}

#header-container {
    padding-left: 0px !important
}

html,
body {
    overflow: hidden;
    font-family: OpenSans;
}

#header {
    background-color: #212121 !important;
    color: #fff;
    padding-top: 20px;
    padding-bottom: 50px;
}

.navbar-collapse {
    background-color: #212121 !important;
    color: #fff;
    border: none !important
}

#menus {
    border: none !important;
    color: white !important;
}

#menus .dropdown-toggle {
    color: white !important;
}

#filelink {
    color: white !important;
    text-align: centerimportant;
    padding-left: 7px;
    text-decoration: none !important;
}

.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:hover,
.navbar-default .navbar-nav>.open>a:focus {
    background-color: #191919 !important;
    color: #eee !important;
    text-align: left !important;
}

.dropdown-menu,
.dropdown-menu a,
.dropdown-submenu a {
    background-color: #191919;
    color: #fff !important;
}

.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-submenu>a:after {
    background-color: #212121;
    color: #fff !important;
}

.btn-default {
    color: #fff !important;
    background-color: #212121 !important;
    border: none !important;
}

.dropdown {
    text-align: left !important;
}

.form-control.select-xs {
    background-color: #191919 !important;
    color: #eee !important;
    border: none;
    outline: none;
}

#modal_indicator {
    display: none;
}

#kernel_indicator {
    color: #fff;
}

#notification_trusted,
#notification_notebook {
    background-color: #212121;
    color: #eee !important;
    border: none;
    border-bottom: 1px solid #eee;
}

#logout {
    background-color: #191919;
    color: #eee;
}

#maintoolbar-container {
    padding-top: 0px !important;
}

.notebook_app {
    background-color: #222222;
}

::-webkit-scrollbar {
    display: none;
}

#notebook-container {
    background-color: #212121;
}

div.cell.selected,
div.cell.selected.jupyter-soft-selected {
    border: none !important;
}

.cm-keyword {
    color: orange !important;
}

.input_area {
    background-color: #212121 !important;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.cm-def {
    color: #5bc0de !important;
}

.cm-variable {
    color: yellow !important;
}

.output_subarea.output_text.output_result pre,
.output_subarea.output_text.output_stream.output_stdout pre {
    color: white !important;
}

.CodeMirror-line {
    color: white !important;
}

.cm-operator {
    color: white !important;
}

.cm-number {
    color: lightblue !important;
}

.inner_cell {
    border: 1px thin #eee;
    border-radius: 50px !important;
}

.CodeMirror-lines {
    border-radius: 20px;
}

.prompt.input_prompt {
    color: #5cb85c !important;
}

.prompt.output_prompt {
    color: lightblue;
}

.cm-string {
    color: #6872ac !important;
}

.cm-builtin {
    color: #f0ad4e !important;
}

.run_this_cell {
    color: lightblue !important;
}

.input_area {
    border-radius: 20px;
}

.output_png {
    background-color: white;
}

.CodeMirror-cursor {
    border-left: 1.4px solid white;
}

.box-flex1.output_subarea.raw_input_container {
    color: white;
}

input.raw_input {
    color: black !important;
}

div.output_area pre {
    color: white
}

h1,
h2,
h3,
h4,
h5,
h6 {
    color: white !important;
    font-weight: bolder !important;
}

.CodeMirror-gutter.CodeMirror-linenumber,
.CodeMirror-gutters {
    background-color: #212121 !important;
}


span.filename:hover {
    color: #191919 !important;
    height: auto !important;
}

#site {
    background-color: #191919 !important;
    color: white !important;
}

#tabs li.active a {
    background-color: #212121 !important;
    color: white !important;
}

#tabs li {
    background-color: #191919 !important;
    color: white !important;
    border-top: 1px thin #eee;
}

#notebook_list_header {
    background-color: #212121 !important;
    color: white !important;
}

#running .panel-group .panel {
    background-color: #212121 !important;
    color: white !important;
}

#accordion.panel-heading {
    background-color: #212121 !important;
}

#running .panel-group .panel .panel-heading {
    background-color: #212121;
    color: white
}

.item_name {
    color: white !important;
    cursor: pointer !important;
}

.list_item:hover {
    background-color: #212121 !important;
}

.item_icon.icon-fixed-width {
    color: white !important;
}

#texteditor-backdrop {
    background-color: #191919 !important;
    border-top: 1px solid #eee;
}

.CodeMirror {
    background-color: #212121 !important;
}

#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
    background-color: #212121 !important;
}

.celltoolbar {
    background-color: #212121 !important;
    border: none !important;
}

Dark Mode for Jupyter Notebook

Dark Mode for Jupyter Notebook

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

Cleanest way to toggle a boolean variable in Java?

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

   var stringToSplit = "0, 10, 20, 30, 100, 200";

    // To parse your string 
    var elements = test.Split(new[]
    { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

    // To Loop through
    foreach (string items in elements)
    {
       // enjoy
    }

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

How to write LDAP query to test if user is member of a group?

If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.

Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.