Programs & Examples On #Country

jQuery - Add ID instead of Class

Try this:

$('element').attr('id', 'value');

So it becomes;

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').attr('id', $(this).text());
        $('#container').attr('id', $(this).text());
        $('.stretch_footer').attr('id', $(this).text())
        $('#footer').attr('id', $(this).text());
    });
});

So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...

Kill Attached Screen in Linux

Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.

result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result; 
do      
    `screen -X -S $i quit`;
done

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

Cannot find the '@angular/common/http' module

You should import http from @angular/http in your service:

import {Http} from '@angular/http';

constructor(private http: http) {} // <--Then Inject it here


// now you can use it in any function eg:
getUsers() {
    return this.http.get('whateverURL');
}

How to enable file sharing for my app?

You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

How to download Visual Studio 2017 Community Edition for offline installation?

Check your %temp% folder after download. In my case, download went both in temp folder and one I specified. After download was completed, files from temp folder were not deleted.
Also, make sure to have enough space on system partition (or wherever your %temp% is) in the first place. For community edition download is over 16GB for everything.

Most efficient way to remove special characters from string

It seems good to me. The only improvement I would make is to initialize the StringBuilder with the length of the string.

StringBuilder sb = new StringBuilder(str.Length);

Postgresql query between date ranges

From PostreSQL 9.2 Range Types are supported. So you can write this like:

SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date

this should be more efficient than the string comparison

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

How to use breakpoints in Eclipse

Here is a video about Debugging with eclipse.

For more details read this page.

Instead of Debugging as Java program, use Debug as Android Application

May help new comers.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Does uninstalling a package with "pip" also remove the dependent packages?

i've successfully removed dependencies of a package using this bash line:

for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done

this worked on pip 1.5.4

How to install an APK file on an Android phone?

Directly connect your Android device and select the USB debugging option in the device. Eclipse will itself find your device, and then just run the code.

Or alternatively, paste your APK file in the Android SDK platform-tools folder and from the command prompt install it like this:

D:......../platform-tools> adb install yourfile.apk.

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

A flexible solution with Java 8 lambda that lets you provide a Consumer that will process the output (eg. log it) line by line. run() is a one-liner with no checked exceptions thrown. Alternatively to implementing Runnable, it can extend Thread instead as other answers suggest.

class StreamGobbler implements Runnable {
    private InputStream inputStream;
    private Consumer<String> consumeInputLine;

    public StreamGobbler(InputStream inputStream, Consumer<String> consumeInputLine) {
        this.inputStream = inputStream;
        this.consumeInputLine = consumeInputLine;
    }

    public void run() {
        new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumeInputLine);
    }
}

You can then use it for example like this:

public void runProcessWithGobblers() throws IOException, InterruptedException {
    Process p = new ProcessBuilder("...").start();
    Logger logger = LoggerFactory.getLogger(getClass());

    StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), System.out::println);
    StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), logger::error);

    new Thread(outputGobbler).start();
    new Thread(errorGobbler).start();
    p.waitFor();
}

Here the output stream is redirected to System.out and the error stream is logged on the error level by the logger.

How to make remote REST call inside Node.js? any CURL?

I didn't find any with cURL so I wrote a wrapper around node-libcurl and can be found at https://www.npmjs.com/package/vps-rest-client.

To make a POST is like so:

var host = 'https://api.budgetvm.com/v2/dns/record';
var key = 'some___key';
var domain_id = 'some___id';

var rest = require('vps-rest-client');
var client = rest.createClient(key, {
  verbose: false
});

var post = {
  domain: domain_id,
  record: 'test.example.net',
  type: 'A',
  content: '111.111.111.111'
};

client.post(host, post).then(function(resp) {
  console.info(resp);

  if (resp.success === true) {
    // some action
  }
  client.close();
}).catch((err) => console.info(err));

How to create an executable .exe file from a .m file

Try:

mcc -m yourfile

Also see help mcc

Where does git config --global get written to?

When is the global .gitconfig file created?

First off, git doesn't automatically create the global config file (.gitconfig) during its installation. The file is not created until it is written to for the first time. If you have never set a system variable, it will not be on your file system. I'm guessing that might be the source of the problem.

One way to ask Git to create it is to request an edit. Doing so will force the file's creation.

git config --global --edit

If you monitor the user's home folder when you issue this command, you will see the .gitconfig file magically appear.

Where is git configuration stored?

Here's a quick rundown of the the name and location of the configuration files associated with the three Git scopes, namely system, global and local:

  • System Git configuration: File named gitconfig located in -git-install-location-/ming<32>/etc
  • Global Git configuraiton: File named .gitconfig located in the user's home folder (C:\Users\git user)
  • Local Git configuration: File named config in the .git folder of the local repo

Of course, seeing is believing, so here's an image showing each file and each location. I pulled the image from an article I wrote on the topic.

Windows Git configuration file locations (TheServerSide.com)

Location of Git configuration files

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

SpringApplication.run main method

You need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        // Recon Logic
    }
}

Why not SpringApplication.run(ReconTool.class, args)

Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).

Example project: https://github.com/mariuszs/spring-run-magic

Recommended way to embed PDF in HTML?

Scribd no longer require you to host your documents on their server. If you create an account with them so you get a publisher ID. It only takes a few lines of JavaScript code to load up PDF files stored on your own server.

For more details, see Developer Tools.

using lodash .groupBy. how to add your own keys for grouped output?

I would suggest a different approach, using my own library you could do this in a few lines:

var groupMe = sequence(
  groupBy(pluck('color')),
  forOwn(function(acc, k, v) {
    acc.push({colors: k, users: v});
    return acc;
  },[])
);

var result = groupMe(collection);

This would a be a bit difficult with lodash or Underscore because the arguments are in the opposite order order, so you'd have to use _.partial a lot.

ImportError: No module named MySQLdb

If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL bindings.

Simply pip install pymysql and switch your SQLAlchemy URI to start like this:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

There are some other drivers you could also try.

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

Quickest way to find missing number in an array of numbers

Let the given array be A with length N. Lets assume in the given array, the single empty slot is filled with 0.

We can find the solution for this problem using many methods including algorithm used in Counting sort. But, in terms of efficient time and space usage, we have two algorithms. One uses mainly summation, subtraction and multiplication. Another uses XOR. Mathematically both methods work fine. But programatically, we need to assess all the algorithms with main measures like

  • Limitations(like input values are large(A[1...N]) and/or number of input values is large(N))
  • Number of condition checks involved
  • Number and type of mathematical operations involved

etc. This is because of the limitations in time and/or hardware(Hardware resource limitation) and/or software(Operating System limitation, Programming language limitation, etc), etc. Lets list and assess the pros and cons of each one of them.

Algorithm 1 :

In algorithm 1, we have 3 implementations.

  1. Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2). Here, N=100. Calculate the total sum of all the given numbers. Subtract the second result from the first result will give the missing number.

    Missing Number = (N(N+1))/2) - (A[1]+A[2]+...+A[100])

  2. Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2). Here, N=100. From that result, subtract each given number gives the missing number.

    Missing Number = (N(N+1))/2)-A[1]-A[2]-...-A[100]

    (Note:Even though the second implementation's formula is derived from first, from the mathematical point of view both are same. But from programming point of view both are different because the first formula is more prone to bit overflow than the second one(if the given numbers are large enough). Even though addition is faster than subtraction, the second implementation reduces the chance of bit overflow caused by addition of large values(Its not completely eliminated, because there is still very small chance since (N+1) is there in the formula). But both are equally prone to bit overflow by multiplication. The limitation is both implementations give correct result only if N(N+1)<=MAXIMUM_NUMBER_VALUE. For the first implementation, the additional limitation is it give correct result only if Sum of all given numbers<=MAXIMUM_NUMBER_VALUE.)

  3. Calculate the total sum of all the numbers(this includes the unknown missing number) and subtract each given number in the same loop in parallel. This eliminates the risk of bit overflow by multiplication but prone to bit overflow by addition and subtraction.

    //ALGORITHM missingNumber = 0; foreach(index from 1 to N) { missingNumber = missingNumber + index; //Since, the empty slot is filled with 0, //this extra condition which is executed for N times is not required. //But for the sake of understanding of algorithm purpose lets put it. if (inputArray[index] != 0) missingNumber = missingNumber - inputArray[index]; }

In a programming language(like C, C++, Java, etc), if the number of bits representing a integer data type is limited, then all the above implementations are prone to bit overflow because of summation, subtraction and multiplication, resulting in wrong result in case of large input values(A[1...N]) and/or large number of input values(N).

Algorithm 2 :

We can use the property of XOR to get solution for this problem without worrying about the problem of bit overflow. And also XOR is both safer and faster than summation. We know the property of XOR that XOR of two same numbers is equal to 0(A XOR A = 0). If we calculate the XOR of all the numbers from 1 to N(this includes the unknown missing number) and then with that result, XOR all the given numbers, the common numbers get canceled out(since A XOR A=0) and in the end we get the missing number. If we don't have bit overflow problem, we can use both summation and XOR based algorithms to get the solution. But, the algorithm which uses XOR is both safer and faster than the algorithm which uses summation, subtraction and multiplication. And we can avoid the additional worries caused by summation, subtraction and multiplication.

In all the implementations of algorithm 1, we can use XOR instead of addition and subtraction.

Lets assume, XOR(1...N) = XOR of all numbers from 1 to N

Implementation 1 => Missing Number = XOR(1...N) XOR (A[1] XOR A[2] XOR...XOR A[100])

Implementation 2 => Missing Number = XOR(1...N) XOR A[1] XOR A[2] XOR...XOR A[100]

Implementation 3 =>

//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
    missingNumber = missingNumber XOR index;
    //Since, the empty slot is filled with 0,
    //this extra condition which is executed for N times is not required.
    //But for the sake of understanding of algorithm purpose lets put it.
    if (inputArray[index] != 0)
        missingNumber = missingNumber XOR inputArray[index];
}

All three implementations of algorithm 2 will work fine(from programatical point of view also). One optimization is, similar to

1+2+....+N = (N(N+1))/2

We have,

1 XOR 2 XOR .... XOR N = {N if REMAINDER(N/4)=0, 1 if REMAINDER(N/4)=1, N+1 if REMAINDER(N/4)=2, 0 if REMAINDER(N/4)=3}

We can prove this by mathematical induction. So, instead of calculating the value of XOR(1...N) by XOR all the numbers from 1 to N, we can use this formula to reduce the number of XOR operations.

Also, calculating XOR(1...N) using above formula has two implementations. Implementation wise, calculating

// Thanks to https://a3nm.net/blog/xor.html for this implementation
xor = (n>>1)&1 ^ (((n&1)>0)?1:n)

is faster than calculating

xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;

So, the optimized Java code is,

long n = 100;
long a[] = new long[n];

//XOR of all numbers from 1 to n
// n%4 == 0 ---> n
// n%4 == 1 ---> 1
// n%4 == 2 ---> n + 1
// n%4 == 3 ---> 0

//Slower way of implementing the formula
// long xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;
//Faster way of implementing the formula
// long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);
long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);

for (long i = 0; i < n; i++)
{
    xor = xor ^ a[i];
}
//Missing number
System.out.println(xor);

SQL Server SELECT LAST N Rows

First you most get record count from

 Declare @TableRowsCount Int
 select @TableRowsCount= COUNT(*) from <Your_Table>

And then :

In SQL Server 2012

SELECT *
FROM  <Your_Table> As L
ORDER BY L.<your Field>
OFFSET <@TableRowsCount-@N> ROWS
FETCH NEXT @N ROWS ONLY;

In SQL Server 2008

SELECT *
FROM 
(
SELECT ROW_NUMBER() OVER(ORDER BY ID) AS sequencenumber, *
FROM  <Your_Table>
    Order By <your Field>
) AS TempTable
WHERE sequencenumber > @TableRowsCount-@N 

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

How do I get the current absolute URL in Ruby on Rails?

To get the request URL without any query parameters.

def current_url_without_parameters
  request.base_url + request.path
end

How to calculate percentage when old value is ZERO

It should be (new minus old)/mod avg of old and new With a special case when both val are zeros

How do I catch a numpy warning like it's an exception (not just for testing)?

Remove warnings.filterwarnings and add:

numpy.seterr(all='raise')

how to fire event on file select

Solution for vue users, solving problem when you upload same file multiple times and @change event is not triggering:

 <input
      ref="fileInput"
      type="file"
      @click="onClick"
    />
  methods: {
    onClick() {
       this.$refs.fileInput.value = ''
       // further logic for file...
    }
  }

Java Minimum and Maximum values in Array

You just throw away Min/Max values:

  // get biggest number
  getMaxValue(array); // <- getMaxValue returns value, which is ignored
  // get smallest number
  getMinValue(array); // <- getMinValue returns value, which is ignored as well

You can do something like

  ... 
  array[i] = next;

  System.out.print("Max value = ");
  System.out.println(getMaxValue(array)); // <- Print out getMaxValue value

  System.out.print("Min value = ");
  System.out.println(getMinValue(array)); // <- Print out getMinValue value

  ...  

How to check if a table exists in a given schema

It depends on what you want to test exactly.

Information schema?

To find "whether the table exists" (no matter who's asking), querying the information schema (information_schema.tables) is incorrect, strictly speaking, because (per documentation):

Only those tables and views are shown that the current user has access to (by way of being the owner or having some privilege).

The query provided by @kong can return FALSE, but the table can still exist. It answers the question:

How to check whether a table (or view) exists, and the current user has access to it?

SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name   = 'table_name'
   );

The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (information_schema.tables is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which actually carry all information.

System catalogs

Your question was:

How to check whether a table exists?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   AND    c.relkind = 'r'    -- only tables
   );

Use the system catalogs pg_class and pg_namespace directly, which is also considerably faster. However, per documentation on pg_class:

The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, materialized views, composite types, and TOAST tables;

For this particular question you can also use the system view pg_tables. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):

SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'schema_name'
   AND    tablename  = 'table_name'
   );

Identifiers have to be unique among all objects mentioned above. If you want to ask:

How to check whether a name for a table or similar object in a given schema is taken?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

Alternative: cast to regclass

SELECT 'schema_name.table_name'::regclass

This raises an exception if the (optionally schema-qualified) table (or other object occupying that name) does not exist.

If you do not schema-qualify the table name, a cast to regclass defaults to the search_path and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas pg_catalog and pg_temp (the schema for temporary objects of the current session) are automatically part of the search_path.

You can use that and catch a possible exception in a function. Example:

A query like above avoids possible exceptions and is therefore slightly faster.

to_regclass(rel_name) in Postgres 9.4+

Much simpler now:

SELECT to_regclass('schema_name.table_name');

Same as the cast, but it returns ...

... null rather than throwing an error if the name is not found

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

CharSequence VS String in Java?

CharSequence

A CharSequence is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence is an umbrella for various types of text strings. Here are some of the common ones:

(You can read more about the differences between these here.)

If you have a CharSequence object, then it is actually an object of one of the classes that implement CharSequence. For example:

CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();

The benefit of having a general umbrella type like CharSequence is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence as a parameter, I could pass in a String or a SpannableStringBuilder and it would handle either one.

public int getLength(CharSequence text) {
    return text.length();
}

String

You could say that a String is just one kind of CharSequence. However, unlike CharSequence, it is an actual class, so you can make objects from it. So you could do this:

String myString = new String();

but you can't do this:

CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated

Since CharSequence is just a list of rules that String conforms to, you could do this:

CharSequence myString = new String();

That means that any time a method asks for a CharSequence, it is fine to give it a String.

String myString = "hello";
getLength(myString); // OK

// ...

public int getLength(CharSequence text) {
    return text.length();
}

However, the opposite is not true. If the method takes a String parameter, you can't pass it something that is only generally known to be a CharSequence, because it might actually be a SpannableString or some other kind of CharSequence.

CharSequence myString = "hello";
getLength(myString); // error

// ...

public int getLength(String text) {
    return text.length();
}

IntelliJ show JavaDocs tooltip on mouse over

In Intellij 2019, I did: File > Settings > Editor > General option Show quick documentation on mouse move.

Print debugging info from stored procedure in MySQL

Quick way to print something is:

select '** Place your mesage here' AS '** DEBUG:';

Get skin path in Magento?

To use it in phtml apply :

echo $this->getSkinUrl('your_image_folder_under_skin/image_name.png');

To use skin path in cms page :

<img style="width: 715px; height: 266px;" src="{{skin url=images/banner1.jpg}}" alt="title" />

This part====> {{skin url=images/banner1.jpg}}

I hope this will help you.

Enum to String C++

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

Anybody knows any knowledge base open source?

How about one of the many wikis?

Kenny: I've used FlexWiki & ScrewTurn (abandoned).

someone else with RepPower to edit my post added this.
Wikipedia is powered by MediaWiki.

Select the first row by group

A base R option is the split()-lapply()-do.call() idiom:

> do.call(rbind, lapply(split(test, test$id), head, 1))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

A more direct option is to lapply() the [ function:

> do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

The comma-space 1, ) at the end of the lapply() call is essential as this is equivalent of calling [1, ] to select first row and all columns.

How can I get the max (or min) value in a vector?

Just this:

// assuming "cloud" is:
// int cloud[10]; 
// or any other fixed size

#define countof(x) (sizeof(x)/sizeof((x)[0]))

int* pMax = std::max_element(cloud, cloud + countof(cloud));

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Why does z-index not work?

In many cases an element must be positioned for z-index to work.

Indeed, applying position: relative to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).

Actually, position: fixed, position: absolute and position: sticky will also enable z-index, but those values also change the layout. With position: relative the layout isn't disturbed.

Essentially, as long as the element isn't position: static (the default setting) it is considered positioned and z-index will work.


Many answers to "Why isn't z-index working?" questions assert that z-index only works on positioned elements. As of CSS3, this is no longer true.

Elements that are flex items or grid items can use z-index even when position is static.

From the specs:

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

Here's a demonstration of z-index working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/

HTML Entity Decode

here is another version:

_x000D_
_x000D_
function convertHTMLEntity(text){_x000D_
    const span = document.createElement('span');_x000D_
_x000D_
    return text_x000D_
    .replace(/&[#A-Za-z0-9]+;/gi, (entity,position,text)=> {_x000D_
        span.innerHTML = entity;_x000D_
        return span.innerText;_x000D_
    });_x000D_
}_x000D_
_x000D_
console.log(convertHTMLEntity('Large &lt; &#163; 500'));
_x000D_
_x000D_
_x000D_

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

Listing available com ports with Python

Please, try this code:

import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
    print(port.device)

first of all, you need to import package for serial port communication, so:

import serial

then you create the list of all the serial ports currently available:

ports = serial.tools.list_ports.comports(include_links=False)

and then, walking along whole list, you can for example print port names:

for port in ports :
    print(port.device)

This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after

port.

How to decide when to use Node.js?

I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user (or robot? or sensor?) does with the application needs to be seen by other users immediately, without a page refresh.

I should also mention that Socket.IO in combination with Node.js will reduce your real-time latency even further than what is possible with long polling. Socket.IO will fall back to long polling as a worst case scenario, and instead use web sockets or even Flash if they are available.

But I should also mention that just about any situation where the code might block due to threads can be better addressed with Node.js. Or any situation where you need the application to be event-driven.

Also, Ryan Dahl said in a talk that I once attended that the Node.js benchmarks closely rival Nginx for regular old HTTP requests. So if we build with Node.js, we can serve our normal resources quite effectively, and when we need the event-driven stuff, it's ready to handle it.

Plus it's all JavaScript all the time. Lingua Franca on the whole stack.

How do I export a project in the Android studio?

Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.

You don't need to harcode android:debuggable="false" in your application tag. Infact for me studio complaints -

Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)

It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.

Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.

enter image description here

Now you should see a prompt to select release build or debug build.

For production always select release build!

enter image description here

And you are done. Signed APK exported.

enter image description here

PS : Don't forget to increment your versionCode in manifest file before uploading to playstore :)

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to remove indentation from an unordered list item?

Add this to your CSS:

ul { list-style-position: inside; }

This will place the li elements in the same indent as other paragraphs and text.

Ref: http://www.w3schools.com/cssref/pr_list-style-position.asp

How to compute the similarity between two text documents?

Identical to @larsman, but with some preprocessing

import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer

nltk.download('punkt') # if necessary...


stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

'''remove punctuation, lowercase, stem'''
def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')

def cosine_sim(text1, text2):
    tfidf = vectorizer.fit_transform([text1, text2])
    return ((tfidf * tfidf.T).A)[0,1]


print cosine_sim('a little bird', 'a little bird')
print cosine_sim('a little bird', 'a little bird chirps')
print cosine_sim('a little bird', 'a big dog barks')

Convert String (UTF-16) to UTF-8 in C#

does this example help ?

using System;
using System.IO;
using System.Text;

class Test
{
   public static void Main() 
   {        
    using (StreamWriter output = new StreamWriter("practice.txt")) 
    {
        // Create and write a string containing the symbol for Pi.
        string srcString = "Area = \u03A0r^2";

        // Convert the UTF-16 encoded source string to UTF-8 and ASCII.
        byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
        byte[] asciiString = Encoding.ASCII.GetBytes(srcString);

        // Write the UTF-8 and ASCII encoded byte arrays. 
        output.WriteLine("UTF-8  Bytes: {0}", BitConverter.ToString(utf8String));
        output.WriteLine("ASCII  Bytes: {0}", BitConverter.ToString(asciiString));


        // Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded  
        // string and write.
        output.WriteLine("UTF-8  Text : {0}", Encoding.UTF8.GetString(utf8String));
        output.WriteLine("ASCII  Text : {0}", Encoding.ASCII.GetString(asciiString));

        Console.WriteLine(Encoding.UTF8.GetString(utf8String));
        Console.WriteLine(Encoding.ASCII.GetString(asciiString));
    }
}

}

How can I use random numbers in groovy?

Generate pseudo random numbers between 1 and an [UPPER_LIMIT]

You can use the following to generate a number between 1 and an upper limit.

Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1

Here is a specific example:

Example - Generate pseudo random numbers in the range 1 to 600:

Math.abs(new Random().nextInt() % 600) + 1

This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.


Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]

If you want to use a lower bound that is not equal to 1 then you can use the following formula.

Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]

Here is a specific example:

Example - Generate pseudo random numbers in the range of 40 to 99:

Math.abs( new Random().nextInt() % (99 - 40) ) + 40

This will generate a random number within a range of 40 and 99.

Getting json body in aws Lambda via API gateway

I am using lambda with Zappa; I am sending data with POST in json format:

My code for basic_lambda_pure.py is:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

I got the next json response:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded

I copy the value for body key and decode with This tool and "eureka", I get the values.

I hope this help you. :)

Call Jquery function

calling a function is simple ..

 myFunction();

so your code will be something like..

 $(function(){
     $('#elementID').click(function(){
         myFuntion();  //this will call your function
    });
 });

  $(function(){
     $('#elementID').click( myFuntion );

 });

or with some condition

if(something){
   myFunction();  //this will call your function
}

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

How to open my files in data_folder with pandas using relative path?

Keeping things tidy with f-strings:

import os
import pandas as pd

data_files = '../data_folder/'
csv_name = 'data.csv'

pd.read_csv(f"{data_files}{csv_name}")

error: Unable to find vcvarsall.bat

I tried many solutions but only one worked for me, the install of Microsoft Visual Studio 2008 Express C++.

I got this issue with a Python 2.7 module written in C (yEnc, which has other issues with MS VS). Note that Python 2.7 is built with MS VS 2008 version, not 2010!

Despite the fact it's free, it is quite hard to find since MS is promoting VS 2010. Still, the MSDN official very direct links are still working: check https://stackoverflow.com/a/15319069/2227298 for download links.

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.

Hosting ASP.NET in IIS7 gives Access is denied?

Checking the Application Pool Identity in Anonymous Authentication and enabling Forms Authentication would solve problem for access denied error.

Auto margins don't center image in page

I remember someday that I spent a lot of time trying to center a div, using margin: 0 auto.

I had display: inline-block on it, when I removed it, the div centered correctly.

As Ross pointed out, it doesn't work on inline elements.

Can you detect "dragging" in jQuery?

Make sure you set the element's draggable attribute to false so you don't have side effects when listening to mouseup events:

<div class="thing" draggable="false">text</div>

Then, you can use jQuery:

$(function() {
  var pressed, pressX, pressY,
      dragged,
      offset = 3; // helps detect when the user really meant to drag

  $(document)
  .on('mousedown', '.thing', function(e) {
    pressX = e.pageX;
    pressY = e.pageY;
    pressed = true;
  })
  .on('mousemove', '.thing', function(e) {
    if (!pressed) return;
    dragged = Math.abs(e.pageX - pressX) > offset ||
              Math.abs(e.pageY - pressY) > offset;
  })
  .on('mouseup', function() {
    dragged && console.log('Thing dragged');
    pressed = dragged = false;
  });
});

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

It sounds like you are using Visual Studio's Web Compiler extension. There is an open issue for this found here: https://github.com/madskristensen/WebCompiler/issues/413

There is a workaround posted in that issue:

  1. Close Visual Studio
  2. Head to C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X (X is the version of WebCompiler)
  3. Delete following folders from node_modules folder: caniuse-lite and browserslist Open up CMD (inside C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X) and run: npm i caniuse-lite browserslist

Add a row number to result set of a SQL query

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

how to run two commands in sudo?

If you would like to handle quotes:

sudo -s -- <<EOF
id
pwd
echo "Done."
EOF

Codeigniter's `where` and `or_where`

You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.

$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->group_start() //this will start grouping
    ->where('library.available_until >=', date("Y-m-d H:i:s"))
    ->or_where('library.available_until =', "00-00-00 00:00:00")
    ->group_end() //this will end grouping
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id')

Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

Creating a new ArrayList in Java

You are looking for Java generics

List<MyClass> list = new ArrayList<MyClass>();

Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Fastest way to set all values of an array?

I have a minor improvement on Ross Drew's answer.

For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.

The optimal size of the initial loop will be JVM specific and system specific of course.

private static final int SMALL = 16;

public static void arrayFill(byte[] array, byte value) {
  int len = array.length;
  int lenB = len < SMALL ? len : SMALL;

  for (int i = 0; i < lenB; i++) {
    array[i] = value;
  }

  for (int i = SMALL; i < len; i += i) {
    System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
  }
}

Spring Boot - Cannot determine embedded database driver class for database type NONE

The same to @Anas. I can run it in Eclipse, but when i use "java -jar ..." run it, it giving me this error. Then i find my java build path is wrong, it missing the folder “src/main/resources”, so, the application can't find application.properties. When i add the “src/main/resources” folder in java build path, it worked.

And, you need add "@PropertySource({"application.properties"})" in your Application class.

Screenshot-1

Screenshot-2

How to create a generic array?

Problem is that while runtime generic type is erased so new E[10] would be equivalent to new Object[10].

This would be dangerous because it would be possible to put in array other data than of E type. That is why you need to explicitly say that type you want by either

Copy struct to struct in C

For simple structures you can either use memcpy like you do, or just assign from one to the other:

RTCclk = RTCclkBuffert;

The compiler will create code to copy the structure for you.


An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

Failed to resolve: com.android.support:appcompat-v7:26.0.0

If you already use jitpack.io or any repository. You can add google repository like this:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

Recursive Fibonacci

I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.

unsigned fib(unsigned n) {
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fib(n-1) + fib(n-2);
}

This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).

You should better use this approach or if you want to use recursion try this:

unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)     
{
    if(n == 0) return 0;
    if(n == 1) return 1;
    if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
    return prev1+prev2;
}

This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

Service has zero application (non-infrastructure) endpoints

The endpoint should also have the namespace:

 <endpoint address="uri" binding="wsHttpBinding" contract="Namespace.Interface" />

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

How do I compile a .c file on my Mac?

You will need to install the Apple Developer Tools. Once you have done that, the easiest thing is to either use the Xcode IDE or use gcc, or nowadays better cc (the clang LLVM compiler), from the command line.

According to Apple's site, the latest version of Xcode (3.2.1) only runs on Snow Leopard (10.6) so if you have an earlier version of OS X you will need to use an older version of Xcode. Your Mac should have come with a Developer Tools DVD which will contain a version that should run on your system. Also, the Apple Developer Tools site still has older versions available for download. Xcode 3.1.4 should run on Leopard (10.5).

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

The error means that you're navigating to a view whose model is declared as typeof Foo (by using @model Foo), but you actually passed it a model which is typeof Bar (note the term dictionary is used because a model is passed to the view via a ViewDataDictionary).

The error can be caused by

Passing the wrong model from a controller method to a view (or partial view)

Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view

var model = db.Foos.Select(x => new
{
    ID = x.ID,
    Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo

or passing a collection of objects to a view that expect a single object

var model = db.Foos.Where(x => x.ID == id);
return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo

The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using var.

Passing the wrong model from a view to a partial view

Given the following model

public class Foo
{
    public Bar MyBar { get; set; }
}

and a main view declared with @model Foo and a partial view declared with @model Bar, then

Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();
return View(model);

will return the correct model to the main view. However the exception will be thrown if the view includes

@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }

By default, the model passed to the partial view is the model declared in the main view and you need to use

@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }

to pass the instance of Bar to the partial view. Note also that if the value of MyBar is null (has not been initialized), then by default Foo will be passed to the partial, in which case, it needs to be

@Html.Partial("_Bar", new Bar())

Declaring a model in a layout

If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.

If you want to include the html for a separate model in a Layout, then in the Layout, use @Html.Action(...) to call a [ChildActionOnly] method initializes that model and returns a partial view for it.

TypeError: Missing 1 required positional argument: 'self'

Works and is simpler than every other solution I see here :

Pump().getPumps()

This is great if you don't need to reuse a class instance. Tested on Python 3.7.3.

.prop('checked',false) or .removeAttr('checked')?

I recommend to use both, prop and attr because I had problems with Chrome and I solved it using both functions.

if ($(':checkbox').is(':checked')){
    $(':checkbox').prop('checked', true).attr('checked', 'checked');
}
else {
    $(':checkbox').prop('checked', false).removeAttr('checked');
}

Purpose of a constructor in Java?

Well, first I will tell the errors in two code snippets.

First code snippet

public class Program
{
    public constructor() // Error - Return type for the method is missing
    {
        function();
    }        
    private void function()
    {
        //do stuff
    }   

    public static void main(String[] args)
    {
        constructor a = new constructor(); // Error - constructor cannot be resolved to a type
    }
}

As you can see the code above, constructor name is not same as class name. In the main() method you are creating a object from a method which has no return type.

Second code snippet

public class Program
{
    public static void main(String[] args)
    {
        function(); // Error - Cannot make a static reference to the non-static method function() from the type Program
    }

    private void function()
    {
        //do stuff
    } 
}

Now in this code snippet you're trying to create a static reference to the non-static method function() from the type Program, which is not possible.

So the possible solution is this,

First code snippet

public class Program
{
    public Program()
    {
        function();
    }        
    private void function()
    {
        //do stuff
    }   

    public static void main(String[] args)
    {
        Program a = new Program();
        a.function();
    }
}

Second code snippet

public class Program
{
    public static void main(String[] args)
    {
        Program a = new Program();
        a.function();
    }

    private void function()
    {
        //do stuff
    } 
}

Finally the difference between the code snippets is that, in first code snippet class name is not same as the class name

While in the second code snippet there is no constructor defined.

Meanwhile to understand the purpose of constructor refer resources below,

https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html

http://www.flowerbrackets.com/learn-constructor-in-java/

http://www.flowerbrackets.com/java-constructor-example/

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

overflow-y : scroll;
overflow-x : hidden;

height is optional

How can I read large text files in Python, line by line, without loading it into memory?

The best solution I found regarding this, and I tried it on 330 MB file.

lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
    file.seek(lineno * (line_length + 2))
    print(file.readline(), end='')

Where line_length is the number of characters in a single line. For example "abcd" has line length 4.

I have added 2 in line length to skip the '\n' character and move to the next character.

How can I run a php without a web server?

You should normally be able to run a php file (after a successful installation) just by running this command:

$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way

You can read more about running PHP in CLI mode here.


It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:

$ php -S localhost:8000

You can read more about running a PHP in a Web Server mode here.

Play sound on button click android

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer mp;
    Button one;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mp = MediaPlayer.create(this, R.raw.soho);
        one = (Button)this.findViewById(R.id.button1);

        one.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.start();
            }
        });
    }
}

Text overwrite in visual studio 2010

I'm using Visual Studio with Parallels/Win 7 on a MacBook laptop keyboard and the only thing that worked was Fn + Enter/Return (that's the Mac shortcut for Insert).

When should I use GC.SuppressFinalize()?

SupressFinalize tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleaned up in the finalizer.

SupressFinalize is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().

Android Studio doesn't recognize my device

In my case it was due to already running and hanged adb.exe on another user under my PC. I had two users on my PC, the second user had the adb.exe process hanged even when I tried to end the process. It worked with me after (End Process Tree) from the Task Manager.

Hope this will help someone with multiple users :)

Ahmad

PDOException SQLSTATE[HY000] [2002] No such file or directory

My answer is specific to Laravel.

I had this message after creating a new connection in the database.php configuration file to a local Docker MySQL service and setting it as the default connection. I forgot that I was setting a different connection by overwriting it in the Model:

class Model extends \Illuminate\Database\Eloquent\Model
{
    protected $connection;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->connection = 'some_other_connection';
    }
...

So even if my default connection in the database.php file was pointing to the right credentials, the model was still using the remote database connection configuration which I had removed from the local environment file.

Async await in linq select

I wanted to call Select(...) but ensure it ran in sequence because running in parallel would cause some other concurrency problems, so I ended up with this. I cannot call .Result because it will block the UI thread.

public static class TaskExtensions
{
    public static async Task<IEnumerable<TResult>> SelectInSequenceAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> asyncSelector)
    {
        var result = new List<TResult>();
        foreach (var s in source)
        {
            result.Add(await asyncSelector(s));
        }
        
        return result;
    }
}

Usage:

var inputs = events.SelectInSequenceAsync(ev => ProcessEventAsync(ev))
                   .Where(i => i != null)
                   .ToList();

I am aware that Task.WhenAll is the way to go when we can run in parallel.

Increase number of axis ticks

You can supply a function argument to scale, and ggplot will use that function to calculate the tick locations.

library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))
number_ticks <- function(n) {function(limits) pretty(limits, n)}

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks=number_ticks(10)) +
  scale_y_continuous(breaks=number_ticks(10))

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

Can CSS force a line break after each word in an element?

I faced the same problem, and none of the options here helped me. Some mail services do not support specified styles. Here is my version, which solved the problem and works everywhere I checked:

<table>
    <tr>
        <td width="1">Gargantuan Word</td>
    </tr>
</table>

OR using CSS:

<table>
    <tr>
        <td style="width:1px">Gargantuan Word</td>
    </tr>
</table>

Meaning of delta or epsilon argument of assertEquals for double values

The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.

Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.

If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation

Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));

Or

Assert.assertEquals(0, Double.compareTo(expected, result));

Which can take these nuances into account.

I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.

How can one see the structure of a table in SQLite?

You will get the structure by typing the command:

.schema <tableName>

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How to determine if a type implements an interface with C# reflection

public static bool ImplementsInterface(this Type type, Type ifaceType) 
{
    Type[] intf = type.GetInterfaces();
    for(int i = 0; i < intf.Length; i++) 
    {
        if(intf[ i ] == ifaceType) 
        {
            return true;
        }
    }
    return false;
}

I think this is the correct release, for three reasons:

  1. It uses GetInterfaces and not IsAssignableFrom, it's faster since IsAssignableFrom eventually after several checks does call GetInterfaces.
  2. It iterates over the local array, so there will be no bounds checks.
  3. It uses the == operator which is defined for Type, so probably is safer than the Equals method (that the Contains call, will eventually use).

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

_x000D_
_x000D_
// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

Why can't Python import Image from PIL?

had the same error while using pytorch code which had deprecated pillow code. since PILLOW_VERSION was deprecated, i worked around it by:

Simply duplicating the _version file and renaming it as PILLOW_VERSION.py in the same folder.

worked for me

You need to use a Theme.AppCompat theme (or descendant) with this activity

Copying answer from @MarkKeen in the comments above as I had the same problem.

I had the error stated at the top of the post and happened after I added an alert dialog. I have all the relevant style information in the manifest. My problem was cured by changing a context reference in the alert builder - I changed:

new android.support.v7.app.AlertDialog.Builder(getApplicationContext())

to:

new android.support.v7.app.AlertDialog.Builder(this)

And no more problems.

Unable to get spring boot to automatically create database schema

If you had this problem on Spring Boot, double check your package names which should be exactly like:

com.example.YOURPROJECTNAME - consists main application class
com.example.YOURPROJECTNAME.entity - consists entities

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

Two-dimensional array in Swift

Before using multidimensional arrays in Swift, consider their impact on performance. In my tests, the flattened array performed almost 2x better than the 2D version:

var table = [Int](repeating: 0, count: size * size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        let val = array[row] * array[column]
        // assign
        table[row * size + column] = val
    }
}

Average execution time for filling up a 50x50 Array: 82.9ms

vs.

var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        // assign
        table[row][column] = val
    }
}

Average execution time for filling up a 50x50 2D Array: 135ms

Both algorithms are O(n^2), so the difference in execution times is caused by the way we initialize the table.

Finally, the worst you can do is using append() to add new elements. That proved to be the slowest in my tests:

var table = [Int]()    
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        table.append(val)
    }
}

Average execution time for filling up a 50x50 Array using append(): 2.59s

Conclusion

Avoid multidimensional arrays and use access by index if execution speed matters. 1D arrays are more performant, but your code might be a bit harder to understand.

You can run the performance tests yourself after downloading the demo project from my GitHub repo: https://github.com/nyisztor/swift-algorithms/tree/master/big-o-src/Big-O.playground

Java - How to convert type collection into ArrayList?

More information needed for a definitive answer, but this code

myNodeList = (ArrayList<MyNode>)this.getVertices();

will only work if this.getVertices() returns a (subtype of) List<MyNode>. If it is a different collection (like your Exception seems to indicate), you want to use

new ArrayList<MyNode>(this.getVertices())

This will work as long as a Collection type is returned by getVertices.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

Also, your encrypt method does the following:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

GoogleTest: How to skip a test?

You can now use the GTEST_SKIP() macro to conditionally skip a test at runtime. For example:

TEST(Foo, Bar)
{
    if (blah)
        GTEST_SKIP();

    ...
}

Note that this is a very recent feature so you may need to update your GoogleTest library to use it.

Convert InputStream to BufferedReader

InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Here is a complete screenshot example that works with chrome in 2021. The end result is a blob ready to be transmitted. Flow is: request media > grab frame > draw to canvas > transfer to blob. If you want to do it more memory efficient explore OffscreenCanvas or possibly ImageBitmapRenderingContext

https://jsfiddle.net/v24hyd3q/1/

// Request media
navigator.mediaDevices.getDisplayMedia().then(stream => 
{
  // Grab frame from stream
  let track = stream.getVideoTracks()[0];
  let capture = new ImageCapture(track);
  capture.grabFrame().then(bitmap => 
  {
    // Stop sharing
    track.stop();
      
    // Draw the bitmap to canvas
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext('2d').drawImage(bitmap, 0, 0);
      
    // Grab blob from canvas
    canvas.toBlob(blob => {
        // Do things with blob here
        console.log('output blob:', blob);
    });
  });
})
.catch(e => console.log(e));

Retaining file permissions with Git

We can improve on the other answers by changing the format of the .permissions file to be executable chmod statements, and to make use of the -printf parameter to find. Here is the simpler .git/hooks/pre-commit file:

#!/usr/bin/env bash

echo -n "Backing-up file permissions... "

cd "$(git rev-parse --show-toplevel)"

find . -printf 'chmod %m "%p"\n' > .permissions

git add .permissions

echo done.

...and here is the simplified .git/hooks/post-checkout file:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

Remember that other tools might have already configured these scripts, so you may need to merge them together. For example, here's a post-checkout script that also includes the git-lfs commands:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on you
r path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/post-checkout.\n"; exit 2; }
git lfs post-checkout "$@"

Set 4 Space Indent in Emacs in Text Mode

(defun my-custom-settings-fn ()
  (setq indent-tabs-mode t)
  (setq tab-stop-list (number-sequence 2 200 2))
  (setq tab-width 2)
  (setq indent-line-function 'insert-tab))

(add-hook 'text-mode-hook 'my-custom-settings-fn)

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

Selecting multiple columns with linq query and lambda expression

        Object AccountObject = _dbContext.Accounts
                                   .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
                                   .Where(x => x.usr.EmailAddress == key1)
                                   .Where(x => x.usr.Hash == key2)
                                   .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
                                   .SingleOrDefault();

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

Oracle pl-sql escape character (for a " ' ")

Instead of worrying about every single apostrophe in your statement. You can easily use the q' Notation.

Example

SELECT q'(Alex's Tea Factory)' FROM DUAL;

Key Components in this notation are

  • q' which denotes the starting of the notation
  • ( an optional symbol denoting the starting of the statement to be fully escaped.
  • Alex's Tea Factory (Which is the statement itself)
  • )' A closing parenthesis with a apostrophe denoting the end of the notation.

And such that, you can stuff how many apostrophes in the notation without worrying about each single one of them, they're all going to be handled safely.

IMPORTANT NOTE

Since you used ( you must close it with )', and remember it's optional to use any other symbol, for instance, the following code will run exactly as the previous one

SELECT q'[Alex's Tea Factory]' FROM DUAL;

Create an array with random values

The shortest approach (ES6)

// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));

Enjoy!

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

getting only name of the class Class.getName()

You can use following simple technique for print log with class name.

private String TAG = MainActivity.class.getSimpleName();

Suppose we have to check coming variable value in method then we can use log like bellow :

private void printVariable(){
Log.e(TAG, "printVariable: ");
}

Importance of this line is that, we can check method name along with class name. To write this type of log.

write :- loge and Enter.

will print on console

E/MainActivity: printVariable:

Google Gson - deserialize list<class> object? (generic type)

public static final <T> List<T> getList(final Class<T[]> clazz, final String json)
{
    final T[] jsonToObject = new Gson().fromJson(json, clazz);

    return Arrays.asList(jsonToObject);
}

Example:

getList(MyClass[].class, "[{...}]");

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

Bootstrap: Position of dropdown menu relative to navbar item

If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.

<div class="btn-group dropup">

enter image description here

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

How can I create an editable combo box in HTML/Javascript?

Here is a script for that: Demo, Source

Or another one which works slightly differently: link removed (site no longer exists)

Why is my Spring @Autowired field null?

This is only valid in case of Unit test.

My Service class had an annotation of service and it was @autowired another component class. When I tested the component class was coming null. Because for service class I was creating the object using new

If you are writing unit test make sure you are not creating object using new object(). Use instead injectMock.

This fixed my issue. Here is a useful link

Inserting a blank table row with a smaller height

I wanted to achieve the same as asked in this question but accepted answer did not work for me in May, 2018 (maybe answer is too old or some other reason). I am using bootsrap 3.3.7 and ionic v1. You need to set line-height to do set height of specific row.

_x000D_
_x000D_
.blank_row {_x000D_
  line-height: 3px;_x000D_
}
_x000D_
<table class="action_table">_x000D_
  <tbody>_x000D_
    <tr class="header_row">_x000D_
      <td>Header Item</td>_x000D_
      <td>Header Item 2</td>_x000D_
      <td>Header Item 3</td>_x000D_
    </tr>_x000D_
    <tr class="blank_row">_x000D_
      <td bgcolor="#000" colspan="3">&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr class="data_row">_x000D_
      <td>Data Item</td>_x000D_
      <td>Data Item 2</td>_x000D_
      <td>Data Item 3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Pipe subprocess standard output to a variable

To get the output of ls, use stdout=subprocess.PIPE.

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

The command cdrecord --help outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.

>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

As mentioned by Chris Morgan, you should be using proc.communicate() instead of proc.read().

>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout: 
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

Retrieving values from nested JSON Object

To see all keys of Jsonobject use this

    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
    JSONObject obj = new JSONObject(JSON);
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        System.out.pritnln(key);
    } 

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Things change. The escape/unescape methods have been deprecated.

You can URI encode the string before you Base64-encode it. Note that this does't produce Base64-encoded UTF8, but rather Base64-encoded URL-encoded data. Both sides must agree on the same encoding.

See working example here: http://codepen.io/anon/pen/PZgbPW

// encode string
var base64 = window.btoa(encodeURIComponent('€ ?? æøåÆØÅ'));
// decode string
var str = decodeURIComponent(window.atob(tmp));
// str is now === '€ ?? æøåÆØÅ'

For OP's problem a third party library such as js-base64 should solve the problem.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

How do I create a comma delimited string from an ArrayList?

Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:

List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
     histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());

Spring Security exclude url patterns in security annotation configurartion

When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):

@Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authFailure").permitAll()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()

If you are still not having any joy, then you will need to provide more details/stacktrace etc.

Details of XML to Java config switch is here

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The trick here is to use the -C (comment) parameter to specify your GCE userid. It looks like Google introduced this change last in 2018.

If the Google user who owns the GCE instance is [email protected] (which you will use as your login userid), then generate the key pair with (for example)

ssh-keygen -b521 -t ecdsa -C myname -f mykeypair

When you paste mykeypair.pub into the instance's public key list, you should see "myname" appear as the userid of the key.

Setting this up will let you use ssh, scp, etc from your command line.

what does "dead beef" mean?

http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef

"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.

How to create local notifications?

-(void)kundanselect
{
    NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    NSArray *allControllersCopy = [allControllers copy];
    if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]]) 
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
        [self performSegueWithIdentifier:@"kundansegue" sender:self];
    }
}

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Jupyter is base on ipython, a permanent solution could be changing the ipython config options.

Create a config file

$ ipython profile create
$ ipython locate
/Users/username/.ipython

Edit the config file

$ cd /Users/username/.ipython
$ vi profile_default/ipython_config.py

The following lines allow you to add your module path to sys.path

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/path/to/your/module")'
]

At the jupyter startup the previous line will be executed

Here you can find more details about ipython config https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/

Adding a dictionary to another

Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.

Implementation:

 public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
 {
        if (collection == null)
        {
            throw new ArgumentNullException("Collection is null");
        }

        foreach (var item in collection)
        {
            if(!source.ContainsKey(item.Key)){ 
               source.Add(item.Key, item.Value);
            }
            else
            {
               // handle duplicate key issue here
            }  
        } 
 }

Usage:

Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();

animals.AddRange(newanimals);

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

WPF: Create a dialog / prompt

Great answer of Josh, all credit to him, I slightly modified it to this however:

MyDialog Xaml

    <StackPanel Margin="5,5,5,5">
        <TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
        <TextBox Name="InputTextBox" Padding="3,3,3,3" />
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
            <Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />
        </Grid>
    </StackPanel>

MyDialog Code Behind

    public MyDialog()
    {
        InitializeComponent();
    }

    public MyDialog(string title,string input)
    {
        InitializeComponent();
        TitleText = title;
        InputText = input;
    }

    public string TitleText
    {
        get { return TitleTextBox.Text; }
        set { TitleTextBox.Text = value; }
    }

    public string InputText
    {
        get { return InputTextBox.Text; }
        set { InputTextBox.Text = value; }
    }

    public bool Canceled { get; set; }

    private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = true;
        Close();
    }

    private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = false;
        Close();
    }

And call it somewhere else

var dialog = new MyDialog("test", "hello");
dialog.Show();
dialog.Closing += (sender,e) =>
{
    var d = sender as MyDialog;
    if(!d.Canceled)
        MessageBox.Show(d.InputText);
}

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

How can I give the Intellij compiler more heap space?

GWT in Intellij 12

FWIW, I was getting a similar error with my GWT application during 'Build | Rebuild Project'.

This was caused by Intellij doing a full GWT compile which I didn't like because it is also a very lengthy process.

I disabled GWT compile by turning off the module check boxes under 'Project Structure | Facets | GWT'.

Alternatively there is a 'Compiler maximum heap size' setting in that location as well.

How to round up value C# to the nearest integer?

It is simple. So follow this code.

decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);

Result is 11

Open Jquery modal dialog on click event

May be helpful... :)

$(document).ready(function() {
    $('#buutonId').on('click', function() {
        $('#modalId').modal('open');
    });
});

How to to send mail using gmail in Laravel?

first login to your gmail account and under My account > Sign In And Security > Sign In to google, enable two step verification, then you can generate app password, and you can use that app password in .env file.

Your .env file will then look something like this

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=apppassword
MAIL_ENCRYPTION=tls

Don't forget to run php artisan config:cache after you make changes in your .env file.

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

How to change the Text color of Menu item in Android?

It seems that an

  <item name="android:itemTextAppearance">@style/myCustomMenuTextAppearance</item>

in my theme and

   <style name="myCustomMenuTextAppearance" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@android:color/primary_text_dark</item>
    </style>

in styles.xml change the style of list-items but not menu items.

How to assign pointer address manually in C programming language?

let's say you want a pointer to point at the address 0x28ff4402, the usual way is

uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want

So the short way is to use a MACRO,

#define ptr *(uint32_t *) (0x28ff4402)

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

My issue was due to version conflict. I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

How to make a function wait until a callback has been called using node.js

If you don't want to use call back then you can Use "Q" module.

For example:

function getdb() {
    var deferred = Q.defer();
    MongoClient.connect(databaseUrl, function(err, db) {
        if (err) {
            console.log("Problem connecting database");
            deferred.reject(new Error(err));
        } else {
            var collection = db.collection("url");
            deferred.resolve(collection);
        }
    });
    return deferred.promise;
}


getdb().then(function(collection) {
   // This function will be called afte getdb() will be executed. 

}).fail(function(err){
    // If Error accrued. 

});

For more information refer this: https://github.com/kriskowal/q

Filter df when values matches part of a string in pyspark

pyspark.sql.Column.contains() is only available in pyspark version 2.2 and above.

df.where(df.location.contains('google.com'))

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

Graph implementation C++

Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.

#include <iostream>
using namespace std;


// 1 ->2 
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;

// Structure of a vertex
struct vertex {
   int i;
   struct node *list;
   struct vertex *next;
};
typedef struct vertex * VPTR;

// Struct of adjacency list
struct node {
    struct vertex * n;
    struct node *next;
};

typedef struct node * NODEPTR;

class Graph {
    public:
        // list of nodes chained together
        VPTR V;
        Graph() {
            V = NULL;
        }
        void addEdge(int, int);
        VPTR  addVertex(int);
        VPTR existVertex(int i);
        void listVertex();
};

// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
    VPTR temp  = V;
    while(temp != NULL) {
        if(temp->i == i) {
            return temp;
        }
        temp = temp->next;
    }
   return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
    VPTR temp = new(struct vertex);
    temp->list = NULL;
    temp->i = i;
    temp->next = NULL;

    VPTR *curr = &V;
    while(*curr) {
        curr = &(*curr)->next;
    }
    *curr = temp;
    return temp;
}

// Add a node from vertex i to j. 
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {

    VPTR v_i = existVertex(i);   
    VPTR v_j = existVertex(j);   
    if(v_i == NULL) {
        v_i = addVertex(i);
    }
    if(v_j == NULL) {
        v_j = addVertex(j);
    }

    NODEPTR *temp = &(v_i->list);
    while(*temp) {
        temp = &(*temp)->next;
    }
    *temp = new(struct node);
    (*temp)->n = v_j;
    (*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
    VPTR temp = V;
    while(temp) {
        cout <<temp->i <<" ";
        temp = temp->next;
    }
    cout <<"\n";

}

// Client program
int main() {
    Graph G;
    G.addEdge(1, 2);
    G.listVertex();

}

With the above code, you can expand to do DFS/BFS etc.

How can I reconcile detached HEAD with master/origin?

I ran into this issue and when I read in the top voted answer:

HEAD is the symbolic name for the currently checked out commit.

I thought: Ah-ha! If HEAD is the symbolic name for the currenlty checkout commit, I can reconcile it against master by rebasing it against master:

git rebase HEAD master

This command:

  1. checks out master
  2. identifies the parent commits of HEAD back to the point HEAD diverged from master
  3. plays those commits on top of master

The end result is that all commits that were in HEAD but not master are then also in master. master remains checked out.


Regarding the remote:

a couple of the commits I'd killed in the rebase got pushed, and the new ones committed locally aren't there.

The remote history can no longer be fast-forwarded using your local history. You'll need to force-push (git push -f) to overwrite the remote history. If you have any collaborators, it usually makes sense to coordinate this with them so everyone is on the same page.

After you push master to remote origin, your remote tracking branch origin/master will be updated to point to the same commit as master.

assign value using linq

using Linq would be:

 listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";

UPDATE

This can be simplified to be...

 listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";

UPDATE

For multiple items (condition is met by multiple items):

 listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...

Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!

ERROR 1049 (42000): Unknown database

Very simple solution. Just rename your database and configure your new database name in your project.

The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.

phpmyadmin -> operations -> Rename database to

javascript node.js next()

It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:

http://howtonode.org/control-flow

Also see the Sequential Actions section of the second part of that posting:

http://howtonode.org/control-flow-part-ii

Get DateTime.Now with milliseconds precision

This should work:

DateTime.Now.ToString("hh.mm.ss.ffffff");

If you don't need it to be displayed and just need to know the time difference, well don't convert it to a String. Just leave it as, DateTime.Now();

And use TimeSpan to know the difference between time intervals:

Example

DateTime start;
TimeSpan time;

start = DateTime.Now;

//Do something here

time = DateTime.Now - start;
label1.Text = String.Format("{0}.{1}", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));

How to turn off word wrapping in HTML?

You need to use the CSS white-space attribute.

In particular, white-space: nowrap and white-space: pre are the most commonly used values. The first one seems to be what you 're after.

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

WebSockets vs. Server-Sent events/EventSource

Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.

How to set the title text color of UIButton?

You can set UIButton title color with hex code

btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)

How can I get Eclipse to show .* files?

If using Zend Studio, same arrow, go to RSE view, click on the downward facing arrow, hit preferences, and then check show hidden files.

That did the trick for me.

Adding Table rows Dynamically in Android

You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:

    public void init(){
    TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);


    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);
    }
}

The activity must be exported or contain an intent-filter

just add intent-filter Tag inside your activity

for example ::

    <activity
        android:name=".activityName">
        <intent-filter>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

Java Set retain order?

To retain the order use List or a LinkedHashSet.

Regex: match everything but specific pattern

I need a regex able to match everything but except a string starting with index.php a specific pattern (specifically index.php and what follows, like index.php?id=2342343)

Use method Exec

_x000D_
_x000D_
    let match,_x000D_
        arr = [],_x000D_
        myRe = /([\s\S]+?)(?:index\.php\?id.+)/g;_x000D_
_x000D_
    var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
_x000D_
    while ((match = myRe.exec(str)) != null) {_x000D_
         arr.push(match[1]);_x000D_
    } _x000D_
    _x000D_
    console.log(arr);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var myRe = /([\s\S]+?)(?:index\.php\?id=.+)/g;_x000D_
var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
var matches_array = myRe.exec(str);_x000D_
console.log(matches_array[1]);
_x000D_
_x000D_
_x000D_

OR OTHER MATCH

_x000D_
_x000D_
let match,_x000D_
            arr = [],_x000D_
            myRe = /index.php\?id=((?:(?!index)[\s\S])*)/g;_x000D_
_x000D_
        var str = 'http://regular-viragenia/index.php?id=2342343index.php?id=111index.php?id=222';_x000D_
_x000D_
        while ((match = myRe.exec(str)) != null) {_x000D_
             arr.push(match[1]);_x000D_
        } _x000D_
_x000D_
        console.log(arr);
_x000D_
_x000D_
_x000D_

How to use if, else condition in jsf to display image

It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
    <c:if test="#{not empty user or user.userId eq 0}">
        <a href="Images/thumb_02.jpg" target="_blank" ></a>
        <img src="Images/thumb_02.jpg" />
    </c:if>
    <c:if test="#{empty user or user.userId eq 0}">
        <a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
        <img src="/DisplayBlobExample?userId=#{user.userId}" />
    </c:if>
</html>

Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:

<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>

Find and Replace text in the entire table using a MySQL query

For a single table update

 UPDATE `table_name`
 SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')

From multiple tables-

If you want to edit from all tables, best way is to take the dump and then find/replace and upload it back.

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

db.books.aggregate([
    {
        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        }
    },
    {
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        }
    },
    {
        $project: {
            _id: 1,
            bookCounts:1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"
            }
        }
    }

]) 

The response will be looking like below:

/* 1 */
{
    "_id" : "address4",
    "bookCounts" : [
        {
            "bookName" : "book3",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 2 */
{
    "_id" : "address90",
    "bookCounts" : [
        {
            "bookName" : "book33",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 3 */
{
    "_id" : "address15",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 4 */
{
    "_id" : "address3",
    "bookCounts" : [
        {
            "bookName" : "book9",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 5 */
{
    "_id" : "address5",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 6 */
{
    "_id" : "address1",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 3
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 4
},

/* 7 */
{
    "_id" : "address2",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 2
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 3
},

/* 8 */
{
    "_id" : "address77",
    "bookCounts" : [
        {
            "bookName" : "book11",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 9 */
{
    "_id" : "address9",
    "bookCounts" : [
        {
            "bookName" : "book99",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
}

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

Any difference between await Promise.all() and multiple await?

You can check for yourself.

In this fiddle, I ran a test to demonstrate the blocking nature of await, as opposed to Promise.all which will start all of the promises and while one is waiting it will go on with the others.

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

Get checkbox list values with jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

raw vs. html_safe vs. h to unescape html

Considering Rails 3:

html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.

h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe declaration, pretty unusual.

Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, so it can only be used on controllers and views.

"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.

How to properly ignore exceptions

How to properly ignore Exceptions?

There are several ways of doing this.

However, the choice of example has a simple solution that does not cover the general case.

Specific to the example:

Instead of

try:
    shutil.rmtree(path)
except:
    pass

Do this:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

new DateTime() vs default(DateTime)

No, they are identical.

default(), for any value type (DateTime is a value type) will always call the parameterless constructor.

How to echo (or print) to the js console with php

There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.

The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.

How do I convert a number to a numeric, comma-separated formatted string?

Not sure it works in tsql, but some platforms have to_char():

test=#select to_char(131213211653.78, '9,999,999,999,999.99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(131213211653.78, '9G999G999G999G999D99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(485, 'RN');
     to_char     
-----------------
         CDLXXXV

As the example suggests, the format's length needs to match that of the number for best results, so you might want to wrap it in a function (e.g. number_format()) if needed.


Converting to money works too, as point out by the other repliers.

test=# select substring(cast(cast(131213211653.78 as money) as varchar) from 2);
     substring      
--------------------
 131,213,211,653.78

Java Immutable Collections

Pure4J supports what you are after, in two ways.

First, it provides an @ImmutableValue annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final etc.).

Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.

Disclaimer: I'm the developer of this

Set textarea width to 100% in bootstrap modal

I am new to .NET/MVC programming, but my understanding is that the Site.css file (under the Content folder in MVC) is a site-level override for Bootstrap CSS, allowing you to override bootstrap native settings in a portable and non-destructive manner (e.g. you can easily save and reapply your site.css changes when updating Bootstrap on your system.)

In Bootstrap 3.0.0, Site.css has the following style setting:

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Other blogs have suggested that this 280px width was added in haste near a release date, in a desire to make the UI look better than it does with 100% width input. Fortunately it was placed in a "visible" location in the site file so you would notice it.

Simply change the width setting, either for all three input types, or pull out textarea and give it its own setting if you want to leave the others alone.

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

Possible to make labels appear when hovering over a point in matplotlib?

The other answers did not address my need for properly showing tooltips in a recent version of Jupyter inline matplotlib figure. This one works though:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors
np.random.seed(42)

fig, ax = plt.subplots()
ax.scatter(*np.random.random((2, 26)))
ax.set_title("Mouse over a point")
crs = mplcursors.cursor(ax,hover=True)

crs.connect("add", lambda sel: sel.annotation.set_text(
    'Point {},{}'.format(sel.target[0], sel.target[1])))
plt.show()

Leading to something like the following picture when going over a point with mouse: enter image description here

Extract first item of each sublist

Your code is almost correct. The only issue is the usage of list comprehension.

If you use like: (x[0] for x in lst), it returns a generator object. If you use like: [x[0] for x in lst], it return a list.

When you append the list comprehension output to a list, the output of list comprehension is the single element of the list.

lst = [["a","b","c"], [1,2,3], ["x","y","z"]]
lst2 = []
lst2.append([x[0] for x in lst])
print lst2[0]

lst2 = [['a', 1, 'x']]

lst2[0] = ['a', 1, 'x']

Please let me know if I am incorrect.