Programs & Examples On #Algol

ALGOL (short for ALGOrithmic Language) is a programming language developed during the 1950s. Used in text books and academic work for algorithm description. Predecessor of many modern computer languages, like Pascal, Simula and C.

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

Set background image in CSS using jquery

<div class="rmz-srchbg">
  <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
  <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
  <br style="clear:both;">
</div>
$(document).ready(function() {
  $('#globalsearchstr').bind('mouseenter', function() {
    $(this).parent().css("background", "black");
  });
});

How to unzip files programmatically in Android?

Based on zapl's answer, adding try() around Closeable's closes the streams automatically after use.

public static void unzip(File zipFile, File targetDirectory) {
    try (FileInputStream fis = new FileInputStream(zipFile)) {
        try (BufferedInputStream bis = new BufferedInputStream(fis)) {
            try (ZipInputStream zis = new ZipInputStream(bis)) {
                ZipEntry ze;
                int count;
                byte[] buffer = new byte[Constant.DefaultBufferSize];
                while ((ze = zis.getNextEntry()) != null) {
                    File file = new File(targetDirectory, ze.getName());
                    File dir = ze.isDirectory() ? file : file.getParentFile();
                    if (!dir.isDirectory() && !dir.mkdirs())
                        throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath());
                    if (ze.isDirectory())
                        continue;
                    try (FileOutputStream fout = new FileOutputStream(file)) {
                        while ((count = zis.read(buffer)) != -1)
                            fout.write(buffer, 0, count);
                    }
                }
            }
        }
    } catch (Exception ex) {
        //handle exception
    }
}

Using Constant.DefaultBufferSize (65536) gotten from C# .NET 4 Stream.CopyTo from Jon Skeet's answer here: https://stackoverflow.com/a/411605/1876355

I always just see posts using byte[1024] or byte[4096] buffer, never knew it can be much larger which improves performance and is still working perfectly normal.

Here is the Stream Source code: https://referencesource.microsoft.com/#mscorlib/system/io/stream.cs

//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.

private const int _DefaultCopyBufferSize = 81920;

However, I dialed it back to 65536 which is also a multiple of 4096 just to be safe.

How do you pull first 100 characters of a string in PHP

A late but useful answer, PHP has a function specifically for this purpose.

mb_strimwidth

$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

How to get date in BAT file

set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause

Generate an integer sequence in MySQL

There is a way to get a range of values in a single query, but its a bit slow. It can be sped up by using cache tables.

assume you want a select with a range of all BOOLEAN values:

SELECT 0 as b UNION SELECT 1 as b;

we can make a view

CREATE VIEW ViewBoolean AS SELECT 0 as b UNION SELECT 1 as b;

then you can do a Byte by

CREATE VIEW ViewByteValues AS
SELECT b0.b + b1.b*2 + b2.b*4 + b3.b*8 + b4.b*16 + b5.b*32 + b6.b*64 + b7.b*128 as v FROM
ViewBoolean b0,ViewBoolean b1,ViewBoolean b2,ViewBoolean b3,ViewBoolean b4,ViewBoolean b5,ViewBoolean b6,ViewBoolean b7;

then you can do a

CREATE VIEW ViewInt16 AS
SELECT b0.v + b1.v*256 as v FROM
ViewByteValues b0,ViewByteValues b1;

then you can do a

SELECT v+MIN as x FROM ViewInt16 WHERE v<MAX-MIN;

To speed this up I skipped the auto-calculation of byte values and made myself a

CREATE VIEW ViewByteValues AS
SELECT 0 as v UNION SELECT 1 as v UNION SELECT ...
...
...254 as v UNION SELECT 255 as v;

If you need a range of dates you can do.

SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE v<NumDays;

or

SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE day<'end_date';

you might be able to speed this up with the slightly faster MAKEDATE function

SELECT MAKEDATE(start_year,1+v) as day FRON ViewInt16 WHERE day>'start_date' AND day<'end_date';

Please note that this tricks are VERY SLOW and only allow the creation of FINITE sequences in a pre-defined domain (for example int16 = 0...65536 )

I am sure you can modify the queries a bit to speed things up by hinting to MySQL where to stop calculating ;) (using ON clauses instead of WHERE clauses and stuff like that)

For example:

SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0,
ViewByteValues b1,
ViewByteValues b2,
ViewByteValues b3
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < MAX-MIN;

will keep your SQL server busy for a few hours

However

SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0
INNER JOIN ViewByteValues b1 ON (b1.v*256<(MAX-MIN))
INNER JOIN ViewByteValues b2 ON (b2.v*65536<(MAX-MIN))
INNER JOIN ViewByteValues b3 ON (b3.v*16777216<(MAX-MIN)
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < (MAX-MIN);

will run reasonably fast - even if MAX-MIN is huge as long as you limit the result with LIMIT 1,30 or something. a COUNT(*) however will take ages and if you make the mistake of adding ORDER BY when MAX-MIN is bigger than say 100k it will again take several seconds to calculate...

Scroll to the top of the page using JavaScript?

You dont need JQuery. Simply you can call the script

window.location = '#'

on click of the "Go to top" button

Sample demo:

output.jsbin.com/fakumo#

PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.

How to export JSON from MongoDB using Robomongo

A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray() and right click Copy JSON. Paste the data in the editor of your choice.

enter image description here

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Cannot get to $rootScope

I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run, config, service, factory, etc..), which are more professional.In this function you don't even have to inject that by yourself like

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];

you can use it, as you know.

create table in postgreSQL

Please try this:

CREATE TABLE article (
  article_id bigint(20) NOT NULL serial,
  article_name varchar(20) NOT NULL,
  article_desc text NOT NULL,
  date_added datetime default NULL,
  PRIMARY KEY (article_id)
);

How can I pause setInterval() functions?

I know this thread is old, but this could be another solution:

var do_this = null;

function y(){
   // what you wanna do
}

do_this = setInterval(y, 1000);

function y_start(){
    do_this = setInterval(y, 1000);
};
function y_stop(){
    do_this = clearInterval(do_this);
};

How do I use Assert.Throws to assert the type of the exception?

Since I'm disturbed by the verbosity of some of the new NUnit patterns, I use something like this to create code that is cleaner for me personally:

public void AssertBusinessRuleException(TestDelegate code, string expectedMessage)
{
    var ex = Assert.Throws<BusinessRuleException>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

public void AssertException<T>(TestDelegate code, string expectedMessage) where T:Exception
{
    var ex = Assert.Throws<T>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

The usage is then:

AssertBusinessRuleException(() => user.MakeUserActive(), "Actual exception message");

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

Regex: match word that ends with "Id"

Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:

\w+Id\b

1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

Ok here is my version of doing this. I noticed that you want your output to be 7, which means you dont want to count special characters and numbers. So here is regex pattern:

re.findall("[a-zA-Z_]+", string)

Where [a-zA-Z_] means it will match any character beetwen a-z (lowercase) and A-Z (upper case).


About spaces. If you want to remove all extra spaces, just do:

string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while "  " in string: # While  there are 2 spaces beetwen words in our string...
    string = string.replace("  ", " ") # ... replace them by one space!

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

Convert string to Boolean in javascript

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.

How stable is the git plugin for eclipse?

I've set up EGit in Eclipse for a few of my projects and find that its a lot easier, faster to use a command line interface versus having to drill down menus and click around windows.

I would prefer something like a command line view within Eclipse to do all the Git duties.

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

jquery-ui-dialog - How to hook into dialog close event

This is what worked for me...

$('#dialog').live("dialogclose", function(){
   //code to run on dialog close
});

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

Copy/duplicate database without using mysqldump

Actually i wanted to achieve exactly that in PHP but none of the answers here were very helpful so here's my – pretty straightforward – solution using MySQLi:

// Database variables

$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '1234';

$DB_SRC = 'existing_db';
$DB_DST = 'newly_created_db';



// MYSQL Connect

$mysqli = new mysqli( $DB_HOST, $DB_USER, $DB_PASS ) or die( $mysqli->error );



// Create destination database

$mysqli->query( "CREATE DATABASE $DB_DST" ) or die( $mysqli->error );



// Iterate through tables of source database

$tables = $mysqli->query( "SHOW TABLES FROM $DB_SRC" ) or die( $mysqli->error );

while( $table = $tables->fetch_array() ): $TABLE = $table[0];


    // Copy table and contents in destination database

    $mysqli->query( "CREATE TABLE $DB_DST.$TABLE LIKE $DB_SRC.$TABLE" ) or die( $mysqli->error );
    $mysqli->query( "INSERT INTO $DB_DST.$TABLE SELECT * FROM $DB_SRC.$TABLE" ) or die( $mysqli->error );


endwhile;

How do I get the size of a java.sql.ResultSet?

I was having the same problem. Using ResultSet.first() in this way just after the execution solved it:

if(rs.first()){
    // Do your job
} else {
    // No rows take some actions
}

Documentation (link):

boolean first()
    throws SQLException

Moves the cursor to the first row in this ResultSet object.

Returns:

true if the cursor is on a valid row; false if there are no rows in the result set

Throws:

SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY

SQLFeatureNotSupportedException - if the JDBC driver does not support this method

Since:

1.2

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
} 
</script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);

than in the test.jsp

<%
session.setMaxInactiveInterval(2);
%>

 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");
 } 
 }
 </script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

How to check if a table contains an element in Lua?

I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.

ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.

function addValue(key, value)
    if (value == nil) then
        removeKey(key)
        return
    end
    _primaryTable[key] = value
    _secodaryTable[value] = key
end

function removeKey(key)
    local value = _primaryTable[key]
    if (value == nil) then
        return
    end
    _primaryTable[key] = nil
    _secondaryTable[value] = nil
end

function getValue(key)
    return _primaryTable[key]
end

function containsValue(value)
    return _secondaryTable[value] ~= nil
end

You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.

If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring on it for example, and then use that as the key.

Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.

The wording of the question however strongly suggests that you have a large number of items to deal with.

"Rate This App"-link in Google Play store app on the phone

I always use this code:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=PackageName")));

Bootstrap 4 File Input

Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":

HTML:

<div class="custom-file">
    <input id="logo" type="file" class="custom-file-input" multiple>
    <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('input[type="file"]').on('change', function () {
    let filenames = [];
    let files = document.getElementById('health_claim_file_form_files').files;

    for (let i in files) {
        if (files.hasOwnProperty(i)) {
            filenames.push(files[i].name);
        }
    }

    $(this).next('.custom-file-label').addClass("selected").html(filenames.join(',    '));
});

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.

Applying styles to tables with Twitter Bootstrap

bootstrap provides various classes for table

 <table class="table"></table>
 <table class="table table-bordered"></table>
 <table class="table table-hover"></table>
 <table class="table table-condensed"></table>
 <table class="table table-responsive"></table>

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

How to tell Jackson to ignore a field during serialization if its value is null?

Jackson 2.x+ use

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);

Best way to list files in Java, sorted by Date Modified?

Elegant solution since Java 8:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Or, if you want it in descending order, just reverse it:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

Pass parameter from a batch file to a PowerShell script

Let's say you would like to pass the string Dev as a parameter, from your batch file:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev"

put inside your powershell script head:

$w = $args[0]       # $w would be set to "Dev"

This if you want to use the built-in variable $args. Otherwise:

 powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\""

and inside your powershell script head:

param([string]$Environment)

This if you want a named parameter.

You might also be interested in returning the error level:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE"

The error level will be available inside the batch file as %errorlevel%.

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

Center Contents of Bootstrap row container

For Bootstrap 4, use the below code:

<div class="mx-auto" style="width: 200px;">
  Centered element
</div>

Ref: https://getbootstrap.com/docs/4.0/utilities/spacing/#horizontal-centering

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

How to count duplicate value in an array in javascript

You can have an object that contains counts. Walk over the list and increment the count for each element:

var counts = {};

uniqueCount.forEach(function(element) {
  counts[element] = (counts[element] || 0) + 1;
});

for (var element in counts) {
  console.log(element + ' = ' + counts[element]);
} 

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

How do you get the width and height of a multi-dimensional array?

You could also consider using getting the indexes of last elements in each specified dimensions using this as following;

int x = ary.GetUpperBound(0);
int y = ary.GetUpperBound(1);

Keep in mind that this gets the value of index as 0-based.

Removing the textarea border in HTML

textarea {
border: 0;
overflow: auto; }

less CSS ^ you can't align the text to the bottom unfortunately.

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

Toggle show/hide on click with jQuery

$(document).ready( function(){
  $("button").click(function(){
    $("p").toggle(1000,'linear');
  });
});

Live Demo

Is there a way of setting culture for a whole application? All current threads and new threads?

Actually you can set the default thread culture and UI culture, but only with Framework 4.5+

I put in this static constructor

static MainWindow()
{
  CultureInfo culture = CultureInfo
    .CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
  var dtf = culture.DateTimeFormat;
  dtf.ShortTimePattern = (string)Microsoft.Win32.Registry.GetValue(
    "HKEY_CURRENT_USER\\Control Panel\\International", "sShortTime", "hh:mm tt");
  CultureInfo.DefaultThreadCurrentUICulture = culture;
}

and put a breakpoint in the Convert method of a ValueConverter to see what arrived at the other end. CultureInfo.CurrentUICulture ceased to be en-US and became instead en-AU complete with my little hack to make it respect regional settings for ShortTimePattern.

Hurrah, all is well in the world! Or not. The culture parameter passed to the Convert method is still en-US. Erm, WTF?! But it's a start. At least this way

  • you can fix the UI culture once when your app loads
  • it's always accessible from CultureInfo.CurrentUICulture
  • string.Format("{0}", DateTime.Now) will use your customised regional settings

If you can't use version 4.5 of the framework then give up on setting CurrentUICulture as a static property of CultureInfo and set it as a static property of one of your own classes. This won't fix default behaviour of string.Format or make StringFormat work properly in bindings then walk your app's logical tree to recreate all the bindings in your app and set their converter culture.

Create Test Class in IntelliJ

Use @Test annotation on one of the test methods or annotate your test class with @RunWith(JMockit.class) if using jmock. Intellij should identify that as test class & enable navigation. Also make sure junit plugin is enabled.

npm global path prefix

I managed to fix Vue Cli no command error by doing the following:

  • In terminal sudo nano ~/.bash_profile to edit your bash profile.
  • Add export PATH=$PATH:/Users/[your username]/.npm-packages/bin
  • Save file and restart terminal
  • Now you should be able to use vue create my-project and vue --version etc.

I did this after I installed the latest Vue Cli from https://cli.vuejs.org/

I generally use yarn, but I installed this globally with npm npm install -g @vue/cli. You can use yarn too if you'd like yarn global add @vue/cli

Note: you may have to uninstall it first globally if you already have it installed: npm uninstall -g vue-cli

Hope this helps!

Is it possible to specify the schema when connecting to postgres with JDBC?

I don't believe there is a way to specify the schema in the connection string. It appears you have to execute

set search_path to 'schema'

after the connection is made to specify the schema.

Increment a Integer's int value?

You can use IntHolder as mutable alternative to Integer. But does it worth?

How do I uninstall nodejs installed from pkg (Mac OS X)?

Following previous posts, here is the full list I used

sudo npm uninstall npm -g
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
sudo rm /usr/local/lib/dtrace/node.d
brew install node

how to change text box value with jQuery?

you simply do like this hope will help you

$(document).ready(function(){   

  $("#cd").click(function () {   

    $('#dsxzcv').val("Changed_Value");   

})
})

here you can see the demo

http://jsbin.com/dolebana/1

Updating a JSON object using Javascript

$(document).ready(function(){        
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.Username = "Thomas";
        return false;
      }
    });

alert("New Username: " + jsonObj[2].Username);

});

Convert an object to an XML string

This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.

public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(keyFather);
            foreach (var objeto in anyObject)
            {
                writer.WriteStartElement(keySon);
                foreach (PropertyDescriptor item in props)
                {
                    writer.WriteStartElement(item.DisplayName);
                    writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return builder.ToString();
        }
    }

Open a folder using Process.Start

Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?

The following code should open a new explorer instance

class sample{

static void Main()
{
  System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");
}
}

How do I analyze a .hprof file?

YourKit Java Profiler seems to handle them too.

Change the "From:" address in Unix "mail"

In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses

  • the -a switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header
  • the $REPLYTO environment variable specifies a Reply-To: header

so the following sequence

export [email protected]
mail -aFrom:[email protected] -s 'Testing'

The result, in my mail clients, is a mail from [email protected], which any replies to will default to [email protected]

NB: Mac OS users: you don't have -a , but you do have $REPLYTO

NB(2): CentOS users, many commenters have added that you need to use -r not -a

NB(3): This answer is at least ten years old(1), please bear that in mind when you're coming in from Google.

How can I view array structure in JavaScript with alert()?

EDIT: Firefox and Google Chrome now have a built-in JSON object, so you can just say alert(JSON.stringify(myArray)) without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON object being present in all browsers, but for debugging purposes it's incredibly useful.

I tend to use the jQuery-json plugin as follows:

alert( $.toJSON(myArray) );

This prints the array in a format like

[5, 6, 7, 11]

However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.

Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.

How to make 'submit' button disabled?

.html

<form [formGroup]="contactForm">

<button [disabled]="contactForm.invalid"  (click)="onSubmit()">SEND</button>

.ts

contactForm: FormGroup;

Remove all child elements of a DOM node in JavaScript

Functional only approach:

const domChildren = (el) => Array.from(el.childNodes)
const domRemove = (el) => el.parentNode.removeChild(el)
const domEmpty = (el) => domChildren(el).map(domRemove)

"childNodes" in domChildren will give a nodeList of the immediate children elements, which is empty when none are found. In order to map over the nodeList, domChildren converts it to array. domEmpty maps a function domRemove over all elements which removes it.

Example usage:

domEmpty(document.body)

removes all children from the body element.

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

How to add border radius on table row

I think collapsing your borders is the wrong thing to do in this case. Collapsing them basically means that the border between two neighboring cells becomes shared. This means it's unclear as to which direction it should curve given a radius.

Instead, you can give a border radius to the two lefthand corners of the first TD and the two righthand corners of the last one. You can use first-child and last-child selectors as suggested by theazureshadow, but these may be poorly supported by older versions of IE. It might be easier to just define classes, such as .first-column and .last-column to serve this purpose.

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

Is there a .NET/C# wrapper for SQLite?

From https://system.data.sqlite.org:

System.Data.SQLite is an ADO.NET adapter for SQLite.

System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.

"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."

It even supports Mono.

MVC DateTime binding with incorrect date format

  public class DateTimeFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.RequestType == "GET")
        {

            foreach (var parameter in filterContext.ActionParameters)
            {
                var properties = parameter.Value.GetType().GetProperties();

                foreach (var property in properties)
                {
                    Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;

                    if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
                    {
                        DateTime dateTime;

                        if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
                            property.SetValue(parameter.Value, dateTime,null);
                    }
                }

            }
        }
    }
}

Converting Stream to String and back...what are we missing?

In usecase where you want to serialize/deserialize POCOs, Newtonsoft's JSON library is really good. I use it to persist POCOs within SQL Server as JSON strings in an nvarchar field. Caveat is that since its not true de/serialization, it will not preserve private/protected members and class hierarchy.

Getting "conflicting types for function" in C, why?

You didn't declare it before you used it.

You need something like

char *do_something(char *, const char *);

before the printf.

Example:

#include <stdio.h>
char *do_something(char *, const char *);
char dest[5];
char src[5] = "test";
int main ()
{
printf("String: %s\n", do_something(dest, src));
 return 0;
}

char *do_something(char *dest, const char *src)
{
return dest;
}

Alternatively, you can put the whole do_something function before the printf.

Can you use CSS to mirror/flip text?

You can use CSS transformations to achieve this. A horizontal flip would involve scaling the div like this:

-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);

And a vertical flip would involve scaling the div like this:

-moz-transform: scale(1, -1);
-webkit-transform: scale(1, -1);
-o-transform: scale(1, -1);
-ms-transform: scale(1, -1);
transform: scale(1, -1);

DEMO:

_x000D_
_x000D_
span{ display: inline-block; margin:1em; } _x000D_
.flip_H{ transform: scale(-1, 1); color:red; }_x000D_
.flip_V{ transform: scale(1, -1); color:green; }
_x000D_
<span class='flip_H'>Demo text &#9986;</span>_x000D_
<span class='flip_V'>Demo text &#9986;</span>
_x000D_
_x000D_
_x000D_

How to cast ArrayList<> from List<>

When you are using second approach you are initializing arraylist with its predefined values. Like generally we do ArrayList listofStrings = new ArrayList<>(); Let's say you have an array with values, now you want to convert this array into arraylist.

you need to first get the list from the array using Arrays utils. Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.

List<String>  listofOptions = (List<String>) Arrays.asList(options);

then you can user constructoru of an arraylist to instantiate with predefined values.

ArrayList<String> arrlistofOptions = new ArrayList<String>(list);

So your second approach is working that you have passed values which will intantiate arraylist with the list elements.

More over

ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list. If you try to add or remove over Arrays.asList it will give you

UnsupportedOperationException

How can I make a link from a <td> table cell

I'd like to make the entire td a hyperlink. I'd prefer without javascript. Is this possible?

That's not possible without javascript. Also, that won't be semantic markup. You should use link instead otherwise it is a matter of attaching onclick handler to <td> to redirect to some other page.

Where do I find the current C or C++ standard documents?

The C99 and C++03 standards are available in book form from Wiley:

Plus, as already mentioned, the working draft for future standards is often available from the committee websites:

The C-201x draft is available as N1336, and the C++0x draft as N3225.

insert a NOT NULL column to an existing table

The error message is quite descriptive, try:

ALTER TABLE MyTable ADD Stage INT NOT NULL DEFAULT '-';

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

How to get an input text value in JavaScript

<script type="text/javascript">
function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}


</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" id="lolz" value=""/>
    <input type="button" value="click" onclick="kk();"/>
</body>

use this

changing textbox border colour using javascript

document.getElementById("fName").style.border="1px solid black";

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

There is another tricky way. The main idea is to double the section number, and first one only shows the headerView while the second one shows the real cells.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionCount * 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section%2 == 0) {
        return 0;
    }
    return _rowCount;
}

What need to do then is to implement the headerInSection delegates:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section%2 == 0) {
        //return headerview;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section%2 == 0) {
        //return headerheight;
    }
    return 0;
}

This approach also has little impact on your datasources:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int real_section = (int)indexPath.section / 2;
    //your code
}

Comparing with other approaches, this way is safe while not changing the frame or contentInsets of the tableview. Hope this may help.

Limit the size of a file upload (html input element)

You can't do it client-side. You'll have to do it on the server.

Edit: This answer is outdated!

As the time of this edit, HTML file API is now supported on all major browsers.

I'd provide an update with solution, but @mark.inman.winning already did it.

Keep in mind that even if it's now possible to validate on the client, you should still validate it on the server, though. All client side validations can be bypassed.

Java Multiple Inheritance

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

class A {  
    void msg() {
        System.out.println("From A");
    }  
}

class B {  
    void msg() {
        System.out.println("From B");
    }  
}

class C extends A,B { // suppose if this was possible
    public static void main(String[] args) {  
        C obj = new C();  
        obj.msg(); // which msg() method would be invoked?  
    }
} 

Retrieving parameters from a URL

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

Using TortoiseSVN via the command line

After selecting "SVN command line tools" it will become like this:

Enter image description here

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

another way

_.chain(data)
    .groupBy('color')
    .map((users, color) => ({ users, color }))
    .value();

How do you find out the type of an object (in Swift)?

Swift 2.0:

The proper way to do this kind of type introspection would be with the Mirror struct,

    let stringObject:String = "testing"
    let stringArrayObject:[String] = ["one", "two"]
    let viewObject = UIView()
    let anyObject:Any = "testing"

    let stringMirror = Mirror(reflecting: stringObject)
    let stringArrayMirror = Mirror(reflecting: stringArrayObject)
    let viewMirror = Mirror(reflecting: viewObject)
    let anyMirror = Mirror(reflecting: anyObject)

Then to access the type itself from the Mirror struct you would use the property subjectType like so:

    // Prints "String"
    print(stringMirror.subjectType)

    // Prints "Array<String>"
    print(stringArrayMirror.subjectType)

    // Prints "UIView"
    print(viewMirror.subjectType)

    // Prints "String"
    print(anyMirror.subjectType)

You can then use something like this:

    if anyMirror.subjectType == String.self {
        print("anyObject is a string!")
    } else {
        print("anyObject is not a string!")
    }

How can I get the file name from request.FILES?

The answer may be outdated, since there is a name property on the UploadedFile class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField correctly, the access should be as easy as:

if form.is_valid():
    form.cleaned_data['my_file'].name

How to validate white spaces/empty spaces? [Angular 2]

i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.

Like here:-

this.anyForm.valueChanges.subscribe(data => {
   for (var key in data) {
        if (data[key].trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }
    }

Edited --

if you work with any number/integer in you form control in that case trim function will not work directly use like :

this.anyForm.valueChanges.subscribe(data => {
  for (var key in data) {
        if (data[key] && data[key].toString().trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }  
  }

Vertical Alignment of text in a table cell

If you are using Bootstrap, please add the following customised style setting for your table:

.table>tbody>tr>td, 
.table>tbody>tr>th, 
.table>tfoot>tr>td, 
.table>tfoot>tr>th, 
.table>thead>tr>td, 
.table>thead>tr>th {
      vertical-align: middle;
 }

How do I check if a list is empty?

Best way to check if a list is empty

For example, if passed the following:

a = []

How do I check to see if a is empty?

Short Answer:

Place the list in a boolean context (for example, with an if or while statement). It will test False if it is empty, and True otherwise. For example:

if not a:                           # do this!
    print('a is an empty list')

PEP 8

PEP 8, the official Python style guide for Python code in Python's standard library, asserts:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No: if len(seq):
    if not len(seq):

We should expect that standard library code should be as performant and correct as possible. But why is that the case, and why do we need this guidance?

Explanation

I frequently see code like this from experienced programmers new to Python:

if len(a) == 0:                     # Don't do this!
    print('a is an empty list')

And users of lazy languages may be tempted to do this:

if a == []:                         # Don't do this!
    print('a is an empty list')

These are correct in their respective other languages. And this is even semantically correct in Python.

But we consider it un-Pythonic because Python supports these semantics directly in the list object's interface via boolean coercion.

From the docs (and note specifically the inclusion of the empty list, []):

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

And the datamodel documentation:

object.__bool__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

and

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

So instead of this:

if len(a) == 0:                     # Don't do this!
    print('a is an empty list')

or this:

if a == []:                     # Don't do this!
    print('a is an empty list')

Do this:

if not a:
    print('a is an empty list')

Doing what's Pythonic usually pays off in performance:

Does it pay off? (Note that less time to perform an equivalent operation is better:)

>>> import timeit
>>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))
0.13775854044661884
>>> min(timeit.repeat(lambda: [] == [], repeat=100))
0.0984637276455409
>>> min(timeit.repeat(lambda: not [], repeat=100))
0.07878462291455435

For scale, here's the cost of calling the function and constructing and returning an empty list, which you might subtract from the costs of the emptiness checks used above:

>>> min(timeit.repeat(lambda: [], repeat=100))
0.07074015751817342

We see that either checking for length with the builtin function len compared to 0 or checking against an empty list is much less performant than using the builtin syntax of the language as documented.

Why?

For the len(a) == 0 check:

First Python has to check the globals to see if len is shadowed.

Then it must call the function, load 0, and do the equality comparison in Python (instead of with C):

>>> import dis
>>> dis.dis(lambda: len([]) == 0)
  1           0 LOAD_GLOBAL              0 (len)
              2 BUILD_LIST               0
              4 CALL_FUNCTION            1
              6 LOAD_CONST               1 (0)
              8 COMPARE_OP               2 (==)
             10 RETURN_VALUE

And for the [] == [] it has to build an unnecessary list and then, again, do the comparison operation in Python's virtual machine (as opposed to C)

>>> dis.dis(lambda: [] == [])
  1           0 BUILD_LIST               0
              2 BUILD_LIST               0
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE

The "Pythonic" way is a much simpler and faster check since the length of the list is cached in the object instance header:

>>> dis.dis(lambda: not [])
  1           0 BUILD_LIST               0
              2 UNARY_NOT
              4 RETURN_VALUE

Evidence from the C source and documentation

PyVarObject

This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the PyObject_VAR_HEAD macro.

From the c source in Include/listobject.h:

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size

Response to comments:

I would point out that this is also true for the non-empty case though its pretty ugly as with l=[] then %timeit len(l) != 0 90.6 ns ± 8.3 ns, %timeit l != [] 55.6 ns ± 3.09, %timeit not not l 38.5 ns ± 0.372. But there is no way anyone is going to enjoy not not l despite triple the speed. It looks ridiculous. But the speed wins out
I suppose the problem is testing with timeit since just if l: is sufficient but surprisingly %timeit bool(l) yields 101 ns ± 2.64 ns. Interesting there is no way to coerce to bool without this penalty. %timeit l is useless since no conversion would occur.

IPython magic, %timeit, is not entirely useless here:

In [1]: l = []                                                                  

In [2]: %timeit l                                                               
20 ns ± 0.155 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

In [3]: %timeit not l                                                           
24.4 ns ± 1.58 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [4]: %timeit not not l                                                       
30.1 ns ± 2.16 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

We can see there's a bit of linear cost for each additional not here. We want to see the costs, ceteris paribus, that is, all else equal - where all else is minimized as far as possible:

In [5]: %timeit if l: pass                                                      
22.6 ns ± 0.963 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [6]: %timeit if not l: pass                                                  
24.4 ns ± 0.796 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [7]: %timeit if not not l: pass                                              
23.4 ns ± 0.793 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Now let's look at the case for an unempty list:

In [8]: l = [1]                                                                 

In [9]: %timeit if l: pass                                                      
23.7 ns ± 1.06 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [10]: %timeit if not l: pass                                                 
23.6 ns ± 1.64 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [11]: %timeit if not not l: pass                                             
26.3 ns ± 1 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

What we can see here is that it makes little difference whether you pass in an actual bool to the condition check or the list itself, and if anything, giving the list, as is, is faster.

Python is written in C; it uses its logic at the C level. Anything you write in Python will be slower. And it will likely be orders of magnitude slower unless you're using the mechanisms built into Python directly.

Bootstrap 3 Glyphicons are not working

As @Stijn described, the default location in Bootstrap.css is incorrect when installing this package from Nuget.

Change this section to look like this:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('Content/fonts/glyphicons-halflings-regular.eot');
  src: url('Content/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded- opentype'), url('Content/fonts/glyphicons-halflings-regular.woff') format('woff'), url('Content/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('Content/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

Convert the first element of an array to a string in PHP

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    $my_array = array(4, 1, 8);
    
    print_r($my_array);
    Array
    (
        [0] => 4
        [1] => 1
        [2] => 8
    )
    
    $result_string = join(',', $my_array);
    echo $result_string;
    

    Which delimits the items in the array by comma into a string:

    4,1,8
    
  2. Or use the PHP implode function like this:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    php> $keyvalues = array();
    
    php> $keyvalues['foo'] = "bar";
    
    php> $keyvalues['pyramid'] = "power";
    
    php> print_r($keyvalues);
    Array
    (
        [foo] => bar
        [pyramid] => power
    )
    
    php> echo join(',', $keyvalues);
    bar,power
    php> echo implode($keyvalues);
    barpower
    php>
    

How to revert initial git commit?

Under the conditions stipulated in the question:

  • The commit is the first commit in the repository.
  • Which means there have been very few commands executed:
    • a git init,
    • presumably some git add operations,
    • and a git commit,
    • and that's all!

If those preconditions are met, then the simplest way to undo the initial commit would be:

rm -fr .git

from the directory where you did git init. You can then redo the git init to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.

DANGER! This removes the Git repository directory.

It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything. All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.

It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.

Be careful, but it is safe and effective when the preconditions are met.

If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.

Format string to a 3 digit number

 string.Format("{0:000}", myString);

Anaconda export Environment file

  1. First activate your conda environment (the one u want to export/backup)
conda activate myEnv
  1. Export all packages to a file (myEnvBkp.txt)
conda list --explicit > myEnvBkp.txt
  1. Restore/import the environment:
conda create --name myEnvRestored --file myEnvBkp.txt

jQuery Show-Hide DIV based on Checkbox Value

A tip to all people that use flat-red, flat-green plugin, because of this plugin the answers above wont work!

In that case, use onchange="do_your_stuff();" on the label, for example: Your checkbox here

The reason why it doesn't work is that this Jquery creates a lot of objects around the real checkbox, so you can't see if it's changed or not.

But if someone click straight on checkbox, won't work :'(

Reducing video size with same format and reducing frame size

There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php

How to format a float in javascript?

I use this code to format floats. It is based on toPrecision() but it strips unnecessary zeros. I would welcome suggestions for how to simplify the regex.

function round(x, n) {
    var exp = Math.pow(10, n);
    return Math.floor(x*exp + 0.5)/exp;
}

Usage example:

function test(x, n, d) {
    var rounded = rnd(x, d);
    var result = rounded.toPrecision(n);
    result = result.replace(/\.?0*$/, '');
    result = result.replace(/\.?0*e/, 'e');
    result = result.replace('e+', 'e');
    return result;  
}

document.write(test(1.2000e45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2000e+45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2340e45, 3, 2) + '=' + '1.23e45' + '<br>');
document.write(test(1.2350e45, 3, 2) + '=' + '1.24e45' + '<br>');
document.write(test(1.0000, 3, 2) + '=' + '1' + '<br>');
document.write(test(1.0100, 3, 2) + '=' + '1.01' + '<br>');
document.write(test(1.2340, 4, 2) + '=' + '1.23' + '<br>');
document.write(test(1.2350, 4, 2) + '=' + '1.24' + '<br>');

Error "The input device is not a TTY"

Using docker-compose exec -T fixed the problem for me via Jenkins

docker-compose exec -T containerName php script.php

"cannot resolve symbol R" in Android Studio

In my case, it was solved by updating Android Studio from 3.1 to 3.3

To update your Android Studio: File -> Settings -> System Settings -> Updates and then click on check now.

enter image description here

Failure [INSTALL_FAILED_INVALID_APK]

It looks like having a number after the dot was the culprit.

I had the same issue with the following applicationId

org.tony.stark.125jarvis

Changing it to

org.tony.stark.jarvis

I was able to install the app to the android devices.

How to close a thread from within?

A little late, but I use a _is_running variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.

def stop(self):
  self._is_running = False

And in run() just loop on while(self._is_running)

How to find out line-endings in a text file?

Vim - always show Windows newlines as ^M

If you prefer to always see the Windows newlines in vim render as ^M, you can add this line to your .vimrc:

set ffs=unix

This will make vim interpret every file you open as a unix file. Since unix files have \n as the newline character, a windows file with a newline character of \r\n will still render properly (thanks to the \n) but will have ^M at the end of the file (which is how vim renders the \r character).


Vim - sometimes show Windows newlines

If you'd prefer just to set it on a per-file basis, you can use :e ++ff=unix when editing a given file.


Vim - always show filetype (unix vs dos)

If you want the bottom line of vim to always display what filetype you're editing (and you didn't force set the filetype to unix) you can add to your statusline with
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}.

My full statusline is provided below. Just add it to your .vimrc.

" Make statusline stay, otherwise alerts will hide it
set laststatus=2
set statusline=
set statusline+=%#PmenuSel#
set statusline+=%#LineNr#
" This says 'show filename and parent dir'
set statusline+=%{expand('%:p:h:t')}/%t
" This says 'show filename as would be read from the cwd'
" set statusline+=\ %f
set statusline+=%m\
set statusline+=%=
set statusline+=%#CursorColumn#
set statusline+=\ %y
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
set statusline+=\[%{&fileformat}\]
set statusline+=\ %p%%
set statusline+=\ %l:%c
set statusline+=\ 

It'll render like

.vim/vimrc\                                    [vim] utf-8[unix] 77% 315:6

at the bottom of your file


Vim - sometimes show filetype (unix vs dos)

If you just want to see what type of file you have, you can use :set fileformat (this will not work if you've force set the filetype). It will return unix for unix files and dos for Windows.

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Token Authentication vs. Cookies

A typical web app is mostly stateless, because of its request/response nature. The HTTP protocol is the best example of a stateless protocol. But since most web apps need state, in order to hold the state between server and client, cookies are used such that the server can send a cookie in every response back to the client. This means the next request made from the client will include this cookie and will thus be recognized by the server. This way the server can maintain a session with the stateless client, knowing mostly everything about the app's state, but stored in the server. In this scenario at no moment does the client hold state, which is not how Ember.js works.

In Ember.js things are different. Ember.js makes the programmer's job easier because it holds indeed the state for you, in the client, knowing at every moment about its state without having to make a request to the server asking for state data.

However, holding state in the client can also sometimes introduce concurrency issues that are simply not present in stateless situations. Ember.js, however, deals also with these issues for you; specifically ember-data is built with this in mind. In conclusion, Ember.js is a framework designed for stateful clients.

Ember.js does not work like a typical stateless web app where the session, the state and the corresponding cookies are handled almost completely by the server. Ember.js holds its state completely in Javascript (in the client's memory, and not in the DOM like some other frameworks) and does not need the server to manage the session. This results in Ember.js being more versatile in many situations, e.g. when your app is in offline mode.

Obviously, for security reasons, it does need some kind of token or unique key to be sent to the server everytime a request is made in order to be authenticated. This way the server can look up the send token (which was initially issued by the server) and verify if it's valid before sending a response back to the client.

In my opinion, the main reason why to use an authentication token instead of cookies as stated in Ember Auth FAQ is primarily because of the nature of the Ember.js framework and also because it fits more with the stateful web app paradigm. Therefore the cookie mechanism is not the best approach when building an Ember.js app.

I hope my answer will give more meaning to your question.

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

How to extract this specific substring in SQL Server?

Combine the SUBSTRING(), LEFT(), and CHARINDEX() functions.

SELECT LEFT(SUBSTRING(YOUR_FIELD,
                      CHARINDEX(';', YOUR_FIELD) + 1, 100),
                      CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;

This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN() function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.

How to keep environment variables when using sudo

You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"

You should also consider specifying env_keep for only a single command like this:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"

How to stop a thread created by implementing runnable interface?

How to stop a thread created by implementing runnable interface?

There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

  // set this to true to stop the thread
  volatile boolean shutdown = false;
  ...
  public void run() {
      while (!shutdown) {
          // continue processing
      }
  }

You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

  public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          // continue processing
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
          }
      }
  }

Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

EF 5 Enable-Migrations : No context type was found in the assembly

Change the default project to data access

change the default project dropdown in the package manager console to data access and give enable migrations...

Thats all success

How can I create a "Please Wait, Loading..." animation using jQuery?

As far as the actual loading image, check out this site for a bunch of options.

As far as displaying a DIV with this image when a request begins, you have a few choices:

A) Manually show and hide the image:

$('#form').submit(function() {
    $('#wait').show();
    $.post('/whatever.php', function() {
        $('#wait').hide();
    });
    return false;
});

B) Use ajaxStart and ajaxComplete:

$('#wait').ajaxStart(function() {
    $(this).show();
}).ajaxComplete(function() {
    $(this).hide();
});

Using this the element will show/hide for any request. Could be good or bad, depending on the need.

C) Use individual callbacks for a particular request:

$('#form').submit(function() {
    $.ajax({
        url: '/whatever.php',
        beforeSend: function() { $('#wait').show(); },
        complete: function() { $('#wait').hide(); }
    });
    return false;
});

How to add Class in <li> using wp_nav_menu() in Wordpress?

I added a class to easily implement menu arguments. So you can customize and include in your function like this:

include_once get_template_directory() . DIRECTORY_SEPARATOR . "your-directory" . DIRECTORY_SEPARATOR . "Menu.php";

<?php $menu = (new Menu('your-theme-location'))
            ->setMenuClass('your-menu')
            ->setMenuID('your-menu-id')
            ->setListClass('your-menu-class')
            ->setLinkClass('your-menu-link anchor') ?>
    
            // Print your menu
            <?php $menu->showMenu() ?>
<?php

class Menu
{
    private $args = [
        'theme_location' => '',
        'container' => '',
        'menu_id' => '',
        'menu_class' => '',
        'add_li_class' => '',
        'link_class' => ''
    ];

    public function __construct($themeLocation)
    {
        add_filter('nav_menu_css_class', [$this,'add_additional_class_on_li'], 1, 3);
        add_filter( 'nav_menu_link_attributes', [$this,'add_menu_link_class'], 1, 3 );

        $this->args['theme_location'] = $themeLocation;
    }

    public function wrapWithTag($tagName){
        $this->args['container'] = $tagName;
        return $this;
    }

    public function setMenuID($id)
    {
        $this->args['menu_id'] = $id;
        return $this;
    }

    public function setMenuClass($class)
    {
        $this->args['menu_class'] = $class;
        return $this;
    }

    public function setListClass($class)
    {
        $this->args['add_li_class'] = $class;
        return $this;
    }

    public function setLinkClass($class)
    {
        $this->args['link_class'] = $class;
        return $this;
    }

    public function showMenu()
    {
        return wp_nav_menu($this->args);
    }

    function add_additional_class_on_li($classes, $item, $args) {
        if(isset($args->add_li_class)) {
            $classes[] = $args->add_li_class;
        }
        return $classes;
    }

    function add_menu_link_class( $atts, $item, $args ) {
        if (property_exists($args, 'link_class')) {
            $atts['class'] = $args->link_class;
        }
        return $atts;
    }
}

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

pg_dump as insert statements 
pg_dump -d -O database filename
-d ( data as inserts ) -O ( capital O is no owner )

Then pipe the backup file back in to PostgreSQL using:

psql -d database -U username -h hostname < filename

As there is no owner included then all of the created table, schema, etc, are created under the login user you specify.

I have read this could be a good approach for migrating between PostgreSQL versions as well.

How do I check if an element is hidden in jQuery?

Using hidden selection you can match all hidden elements

$('element:hidden')

Using Visible selection you can match all visible elements

$('element:visible')

How can I enable the Windows Server Task Scheduler History recording?

I have another possible answer for those wondering why event log entries are not showing up in the History tab of Task Scheduler for certain tasks, even though All Task History is enabled, the events for those tasks are viewable in the Event Log, and all other tasks show history just fine. In my case, I had created 13 new tasks. For 5 of them, events showed fine under History, but for the other 8, the History tab was completely blank. I even verified these tasks were enabled for history individually (and logging events) using Mick Wood's post about using the Event Viewer.

Then it hit me. I suddenly realized what all 8 had in common that the other 5 did not. They all had an ampersand (&) character in the event name. I created them by exporting the first task I created, "Sync E to N", renaming the exported file name, editing the XML contents, and then importing the new task. Windows Explorer happily let me rename the task, for example, to "Sync C to N & T", and Task Scheduler happily let me import it. However, with that pesky "&" in the name, it could not retrieve its history from the event log. When I deleted the original event, renamed the xml file to "Sync C to N and T", and imported it, voila, there were all of the log entries in the History tab in Task Scheduler.

How to print like printf in Python3?

Other words printf absent in python... I'm surprised! Best code is

def printf(format, *args):
    sys.stdout.write(format % args)

Because of this form allows not to print \n. All others no. That's why print is bad operator. And also you need write args in special form. There is no disadvantages in function above. It's a standard usual form of printf function.

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

Understanding the map function

The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.

Let's look at an example: map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.

Imagine you have a function that takes a number, adds 1 to that number and returns it:

def add_one(num):
  new_num = num + 1
  return new_num

You also have a list of numbers:

my_list = [1, 3, 6, 7, 8, 10]

if you want to increment every number in the list, you can do the following:

>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]

Note: At minimum map() needs two arguments. First a function name and second something like a list.

Let's see some other cool things map() can do. map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.

We have three lists:

list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]

map() can make you a new list that holds the addition of elements at a specific index.

Now remember map(), needs a function. This time we'll use the builtin sum() function. Running map() gives the following result:

>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]

REMEMBER:
In Python 2 map(), will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. In Python 3 map() will stop after finishing with the shortest list. Also, in Python 3, map() returns an iterator, not a list.

How to change plot background color?

Something like this? Use the axisbg keyword to subplot:

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(Granted, not a scatter plot, and not a black background.)

enter image description here

functional way to iterate over range (ES6/7)

ES7 Proposal

Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method

You can always use something like:

[for (i of Array(7).keys()) i*i];

Running this code on Firefox:

[ 0, 1, 4, 9, 16, 25, 36 ]

This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.

This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:

var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]

Then you can do:

[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25

ES6

A nice way to do this any of:

[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);

This will output:

[ 0, 1, 4, 9, 16, 25, 36 ]

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

How to solve npm install throwing fsevents warning on non-MAC OS?

package.json counts with a optionalDependencies key. NPM on Optional Dependencies.

You can add fsevents to this object and if you find yourself installing packages in a different platform than MacOS, fsevents will be skipped by either yarn or npm.

"optionalDependencies": {
  "fsevents": "2.1.2"
},

You will find a message like the following in the installation log:

info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.

Hope it helps!

CMake not able to find OpenSSL library

you are having the FindOpenSSL.cmake file in the cmake module(path usr/shared.cmake-3.5/modules) # Search OpenSSL

 find_package(OpenSSL REQUIRED) 
if( OpenSSL_FOUND )
    include_directories(${OPENSSL_INCLUDE_DIRS})
    link_directories(${OPENSSL_LIBRARIES})
    message(STATUS "Using OpenSSL ${OPENSSL_VERSION}")

target_link_libraries(project_name /path/of/libssl.so /path/of/libcrypto.so)

Apache won't follow symlinks (403 Forbidden)

In addition to changing the permissions as the other answers have indicated, I had to restart apache for it to take effect:

sudo service apache2 restart

How does C compute sin() and other math functions?

OK kiddies, time for the pros.... This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution. Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form: (((p4.x + p3).x + p2).x + p1).x + p0 ....and this is how you'd calculate cosine to 7 decimal places on that hardware.

Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware). Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first. Again, that book "Computer Approximations" will tell you that.

If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms. Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done.

Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there.

Enjoy.

How to detect iPhone 5 (widescreen devices)?

I think it should be good if this macro will work in device and simulator, below are the solution.

#define IS_WIDESCREEN (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)568) < DBL_EPSILON)
#define IS_IPHONE (([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"]) || ([[[UIDevice currentDevice] model] isEqualToString: @"iPhone Simulator"]))
#define IS_IPOD   ([[[UIDevice currentDevice]model] isEqualToString:@"iPod touch"])
#define IS_IPHONE_5 ((IS_IPHONE || IS_IPOD) && IS_WIDESCREEN)

In Windows cmd, how do I prompt for user input and use the result in another command?

Try this:

@echo off
set /p id="Enter ID: "

You can then use %id% as a parameter to another batch file like jstack %id%.

For example:

set /P id=Enter id: 
jstack %id% > jstack.txt

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How do I concatenate const/literal strings in C?

You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.

Specifically:

...snip...

destination

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

...snip...

http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

There's an example here as well.

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

_x000D_
_x000D_
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
_x000D_
_x000D_

sql query with multiple where statements

What is meta_key? Strip out all of the meta_value conditionals, reduce, and you end up with this:

SELECT
*
FROM
meta_data
WHERE
(
        (meta_key = 'lat')
)
AND
(
        (meta_key = 'long')
)
GROUP BY
item_id

Since meta_key can never simultaneously equal two different values, no results will be returned.


Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:

SELECT
*
FROM
meta_data
WHERE
(
    (meta_key = 'lat')
    AND
    (
        (meta_value >= '60.23457047672217')
        OR
        (meta_value <= '60.23457047672217')
    )
)
OR
(
    (meta_key = 'long')
    AND
    (
        (meta_value >= '24.879140853881836')
        OR
        (meta_value <= '24.879140853881836')
    )
)
GROUP BY
item_id

Note the OR between the top-level conditionals. This is because you want records which are lat or long, since no single record will ever be lat and long.

I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY clause, but that might be outside the context of this question entirely.

Difference between jQuery parent(), parents() and closest() functions

from http://api.jquery.com/closest/

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

.parent()

  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.

Here are related threads:

WCF timeout exception detailed investigation

Did you check the WCF traces? WCF has a tendency to swallow exceptions and only return the last exception, which is the timeout that you're getting, since the end point didn't return anything meaningful.

Click a button programmatically - JS

When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.

This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.

I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.

What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.

The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.

I also made a point to test for the element before attempting to assign values to it.

window.setTimeout(function() { if( document.getElementById("book") ) { // Code goes here }, 400 /* but after 400 ms */);

This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.

Checking that a List is not empty in Hamcrest

If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:

assertEquals(new ArrayList<>(0), yourList);

E.g. if you run

assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");

you get

java.lang.AssertionError
Expected :[]
Actual   :[foo, bar]

How to log a method's execution time exactly in milliseconds?

I use this in my utils library (Swift 4.2):

public class PrintTimer {
    let start = Date()
    let name: String

    public init(file: String=#file, line: Int=#line, function: String=#function, name: String?=nil) {
        let file = file.split(separator: "/").last!
        self.name = name ?? "\(file):\(line) - \(function)"
    }

    public func done() {
        let end = Date()
        print("\(self.name) took \((end.timeIntervalSinceReferenceDate - self.start.timeIntervalSinceReferenceDate).roundToSigFigs(5)) s.")
    }
}

... then call in a method like:

func myFunctionCall() {
    let timer = PrintTimer()
    // ...
    timer.done()
}

... which in turn looks like this in the console after running:

MyFile.swift:225 - myFunctionCall() took 1.8623 s.

Not as concise as TICK/TOCK above, but it is clear enough to see what it is doing and automatically includes what is being timed (by file, line at the start of the method, and function name). Obviously if I wanted more detail (ex, if I'm not just timing a method call as is the usual case but instead am timing a block within that method) I can add the "name="Foo"" parameter on the PrintTimer init to name it something besides the defaults.

Application Crashes With "Internal Error In The .NET Runtime"

For those arriving here from google, I've eventually come across this SO question, and this specific answer solved my problem. I've contacted Microsoft for the hotfix through the live chat on support.microsoft.com and they sent me a link to the hotfix by email.

Add and Remove Views in Android Dynamically?

ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.

For example:

View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);

Note that all Layouts are ViewGroups.

CreateProcess error=2, The system cannot find the file specified

The dir you specified is a working directory of running process - it doesn't help to find executable. Use cmd /c winrar ... to run process looking for executable in PATH or try to use absolute path to winrar.

Get Bitmap attached to ImageView

Write below code

ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

Different between parseInt() and valueOf() in java?

Integer.parseInt can just return int as native type.

Integer.valueOf may actually need to allocate an Integer object, unless that integer happens to be one of the preallocated ones. This costs more.

If you need just native type, use parseInt. If you need an object, use valueOf.

Also, because of this potential allocation, autoboxing isn't actually good thing in every way. It can slow down things.

How to get all elements which name starts with some string?

You can try using jQuery with the Attribute Contains Prefix Selector.

$('[id|=q1_]')

Haven't tested it though.

Node / Express: EADDRINUSE, Address already in use - Kill server

You can also go the command line route:

ps aux | grep node

to get the process ids.

Then:

kill -9 PID

Doing the -9 on kill sends a SIGKILL (instead of a SIGTERM). SIGTERM has been ignored by node for me sometimes.

Best practices for circular shift (rotate) operations in C++

Assuming you want to shift right by L bits, and the input x is a number with N bits:

unsigned ror(unsigned x, int L, int N) 
{
    unsigned lsbs = x & ((1 << L) - 1);
    return (x >> L) | (lsbs << (N-L));
}

Load a WPF BitmapImage from a System.Drawing.Bitmap

Thanks to Hallgrim, here is the code I ended up with:

ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   bmp.GetHbitmap(), 
   IntPtr.Zero, 
   System.Windows.Int32Rect.Empty, 
   BitmapSizeOptions.FromWidthAndHeight(width, height));

I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question

foreach vs someList.ForEach(){}

I know two obscure-ish things that make them different. Go me!

Firstly, there's the classic bug of making a delegate for each item in the list. If you use the foreach keyword, all your delegates can end up referring to the last item of the list:

    // A list of actions to execute later
    List<Action> actions = new List<Action>();

    // Numbers 0 to 9
    List<int> numbers = Enumerable.Range(0, 10).ToList();

    // Store an action that prints each number (WRONG!)
    foreach (int number in numbers)
        actions.Add(() => Console.WriteLine(number));

    // Run the actions, we actually print 10 copies of "9"
    foreach (Action action in actions)
        action();

    // So try again
    actions.Clear();

    // Store an action that prints each number (RIGHT!)
    numbers.ForEach(number =>
        actions.Add(() => Console.WriteLine(number)));

    // Run the actions
    foreach (Action action in actions)
        action();

The List.ForEach method doesn't have this problem. The current item of the iteration is passed by value as an argument to the outer lambda, and then the inner lambda correctly captures that argument in its own closure. Problem solved.

(Sadly I believe ForEach is a member of List, rather than an extension method, though it's easy to define it yourself so you have this facility on any enumerable type.)

Secondly, the ForEach method approach has a limitation. If you are implementing IEnumerable by using yield return, you can't do a yield return inside the lambda. So looping through the items in a collection in order to yield return things is not possible by this method. You'll have to use the foreach keyword and work around the closure problem by manually making a copy of the current loop value inside the loop.

More here

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

iOS how to set app icon and launch images

I've tried most of the above and a few others and have found https://appicon.co to be the easiest, fastest, and provides the most comprehensive set.

  1. Drag your image onto the screen
  2. Click Generate
  3. Open the file just downloaded to your Downloads folder

Here, you may be able to drag this entire folder into Xcode. If not:

  1. Double-click the Assets.xcassets folder
  2. Select all files
  3. Drag them to Assets.xcassets
  4. Rename it to Appicon

C# - Making a Process.Start wait until the process has start-up

I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

Parent Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyParentProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;
            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch(Exception exception)
            { }
            finally
            {
                if (ewh != null)
                    ewh.Close();
            }
        }
    }
}

Child Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Representing some time consuming work.
                Thread.Sleep(5000);

                EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                    .Set();

                Process.GetProcessById(Convert.ToInt32(args[0]))
                    .WaitForExit();
            }
            catch (Exception exception)
            { }
        }
    }
}

What is the OAuth 2.0 Bearer Token exactly?

Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".

The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.

In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.

Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM

copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.

Update:

A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:

POST /rsvp?eventId=123 HTTP/1.1
Host: events-organizer.com
Authorization: Bearer AbCdEf123456
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)

rsvpStatus=YES

The string "AbCdEf123456" in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from [email protected], the audience is https://example.com.

If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).

Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.

Return index of highest value in an array

<?php

$array = array(11 => 14,
               10 => 9,
               12 => 7,
               13 => 7,
               14 => 4,
               15 => 6);

echo array_search(max($array), $array);

?>

array_search() return values:

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

Open files always in a new tab

For 2020 ..

easy as pie, tap preferences (eg, apple-comma on a Mac),

they added it right there:

enter image description here

Turn "off" for normal behavior. (IE, to avoid the "automatic closing" behavior.)

How do I copy a folder from remote to local using scp?

scp -r [email protected]:/path/to/foo /home/user/Desktop/

By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.

From man scp (See online manual)

-r Recursively copy entire directories

Android camera intent

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

Then receive the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.

Get push notification while App in foreground iOS

Objective C

enter image description here

For iOS 10 we need integrate willPresentNotification method for show notification banner in foreground.

If app in foreground mode(active)

- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog( @"Here handle push notification in foreground" ); 
    //For notification Banner - when app in foreground
    
    completionHandler(UNNotificationPresentationOptionAlert);
    
    // Print Notification info
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
}

Return None if Dictionary key is not available

Wonder no more. It's built into the language.

    >>> help(dict)

    Help on class dict in module builtins:

    class dict(object)
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
    ...
     |  
     |  get(...)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
    ...

Create a git patch from the uncommitted changes in the current working directory

If you want to do binary, give a --binary option when you run git diff.

Git - How to close commit editor?

Had troubles as well. On Linux I used Ctrl+X (and Y to confirm) and then I was back on the shell ready to pull/push.

On Windows GIT Bash Ctrl+X would do nothing and found out it works quite like vi/vim. Press i to enter inline insert mode. Type the description at the very top, press esc to exit insert mode, then type :x! (now the cursor is at the bottom) and hit enter to save and exit.

If typing :q! instead, will exit the editor without saving (and commit will be aborted)

Client on Node.js: Uncaught ReferenceError: require is not defined

In my case I used another solution.

As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain

"module": "commonjs"

But use import and export statements in your referenced files

import { Utils } from "./utils"
export interface Actions {}

Final generated code will always have(at least for TypeScript 3.0) such lines

"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();

Can someone explain how to implement the jQuery File Upload plugin?

Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

How do I import a sql data file into SQL Server?

If you are talking about an actual database (an mdf file) you would Attach it

.sql files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.

Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's

Static variables in JavaScript

There's another approach, which solved my requirements after browsing this thread. It depends on exactly what you want to achieve with a "static variable".

The global property sessionStorage or localStorage allows data to be stored for the life of the session, or for an indefinite longer period until explicitly cleared, respectively. This allows data to be shared among all windows, frames, tab panels, popups etc of your page/app and is much more powerful than a simple "static/global variable" in one code segment.

It avoids all hassle with the scope, lifetime, semantics, dynamics etc of top-level global variables, ie Window.myglobal. Don't know how efficient it is, but that's not important for modest amounts of data, accessed at modest rates.

Easily accessed as "sessionStorage.mydata = anything" and retrieved similarly. See "JavaScript: The Definitive Guide, Sixth Edition", David Flanagan, ISBN: 978-0-596-80552-4, Chapter 20, section 20.1. This is easily downloadable as a PDF by simple search, or in your O'Reilly Safaribooks subscription (worth its weight in gold).

HTML5 Email input pattern attribute

This is a dual problem (as many in the world wide web world).

You need to evaluate if the browser supports html5 (I use Modernizr to do it). In this case if you have a normal form the browser will do the job for you, but if you need ajax/json (as many of everyday case) you need to perform manual verification anyway.

.. so, my suggestion is to use a regular expression to evaluate anytime before submit. The expression I use is the following:

var email = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;

This one is taken from http://www.regular-expressions.info/ . This is a hard world to understand and master, so I suggest you to read this page carefully.

iOS 7's blurred overlay effect using CSS?

It is possible with CSS3 :

#myDiv {
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -o-filter: blur(20px);
    -ms-filter: blur(20px);
    filter: blur(20px);
    opacity: 0.4;
}

Example here => jsfiddle

Passing arguments to AsyncTask, and returning results

You can receive returning results like that: AsyncTask class

@Override
protected Boolean doInBackground(Void... params) {
    if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
        try {
            throw new SQLException("Database credentials missing");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return true;
}

receiving class:

_store.execute();
boolean result =_store.get();

Hoping it will help.

Github permission denied: ssh add agent has no identities

Steps for BitBucket:

if you dont want to generate new key, SKIP ssh-keygen

ssh-keygen -t rsa 

Copy the public key to clipboard:

clip < ~/.ssh/id_rsa.pub

Login to Bit Bucket: Go to View Profile -> Settings -> SSH Keys (In Security tab) Click Add Key, Paste the key in the box, add a descriptive title

Go back to Git Bash :

ssh-add -l

You should get :

2048 SHA256:5zabdekjjjaalajafjLIa3Gl/k832A /c/Users/username/.ssh/id_rsa (RSA)

Now: git pull should work

C - The %x format specifier

Break-down:

  • 8 says that you want to show 8 digits
  • 0 that you want to prefix with 0's instead of just blank spaces
  • x that you want to print in lower-case hexadecimal.

Quick example (thanks to Grijesh Chauhan):

#include <stdio.h>
int main() {
    int data = 29;
    printf("%x\n", data);    // just print data
    printf("%0x\n", data);   // just print data ('0' on its own has no effect)
    printf("%8x\n", data);   // print in 8 width and pad with blank spaces
    printf("%08x\n", data);  // print in 8 width and pad with 0's

    return 0;
}

Output:

1d
1d
      1d
0000001d

Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.

Generate a Hash from string in Javascript

Note: Even with the best 32-bit hash, collisions will occur sooner or later.

The hash collision probablility can be calculated as 1 - e ^ (-k(k-1) / 2N, aproximated as k^2 / 2N (see here). This may be higher than intuition suggests:
Assuming a 32-bit hash and k=10,000 items, a collision will occur with a probablility of 1.2%. For 77,163 samples the probability becomes 50%! (calculator).
I suggest a workaround at the bottom.

In an answer to this question Which hashing algorithm is best for uniqueness and speed?, Ian Boyd posted a good in depth analysis. In short (as I interpret it), he comes to the conclusion that Murmur is best, followed by FNV-1a.
Java’s String.hashCode() algorithm that esmiralha proposed seems to be a variant of DJB2.

  • FNV-1a has a a better distribution than DJB2, but is slower
  • DJB2 is faster than FNV-1a, but tends to yield more collisions
  • MurmurHash3 is better and faster than DJB2 and FNV-1a (but the optimized implementation requires more lines of code than FNV and DJB2)

Some benchmarks with large input strings here: http://jsperf.com/32-bit-hash
When short input strings are hashed, murmur's performance drops, relative to DJ2B and FNV-1a: http://jsperf.com/32-bit-hash/3

So in general I would recommend murmur3.
See here for a JavaScript implementation: https://github.com/garycourt/murmurhash-js

If input strings are short and performance is more important than distribution quality, use DJB2 (as proposed by the accepted answer by esmiralha).

If quality and small code size are more important than speed, I use this implementation of FNV-1a (based on this code).

/**
 * Calculate a 32 bit FNV-1a hash
 * Found here: https://gist.github.com/vaiorabbit/5657561
 * Ref.: http://isthe.com/chongo/tech/comp/fnv/
 *
 * @param {string} str the input value
 * @param {boolean} [asString=false] set to true to return the hash value as 
 *     8-digit hex string instead of an integer
 * @param {integer} [seed] optionally pass the hash of the previous chunk
 * @returns {integer | string}
 */
function hashFnv32a(str, asString, seed) {
    /*jshint bitwise:false */
    var i, l,
        hval = (seed === undefined) ? 0x811c9dc5 : seed;

    for (i = 0, l = str.length; i < l; i++) {
        hval ^= str.charCodeAt(i);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }
    if( asString ){
        // Convert to 8 digit hex string
        return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
    }
    return hval >>> 0;
}

Improve Collision Probability

As explained here, we can extend the hash bit size using this trick:

function hash64(str) {
    var h1 = hash32(str);  // returns 32 bit (as 8 byte hex string)
    return h1 + hash32(h1 + str);  // 64 bit (as 16 byte hex string)
}

Use it with care and don't expect too much though.

Getting list of lists into pandas DataFrame

Even without pop the list we can do with set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

Update from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

Display an image with Python

Using Jupyter Notebook, the code can be as simple as the following.

%matplotlib inline
from IPython.display import Image
Image('your_image.png')

Sometimes you might would like to display a series of images in a for loop, in which case you might would like to combine display and Image to make it work.

%matplotlib inline
from IPython.display import display, Image
for your_image in your_images:
    display(Image('your_image'))

JavaScript OR (||) variable assignment explanation

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

Unable to find valid certification path to requested target - error even after cert imported

(repost from my other response)
Use cli utility keytool from java software distribution for import (and trust!) needed certificates

Sample:

  1. From cli change dir to jre\bin

  2. Check keystore (file found in jre\bin directory)
    keytool -list -keystore ..\lib\security\cacerts
    Password is changeit

  3. Download and save all certificates in chain from needed server.

  4. Add certificates (before need to remove "read-only" attribute on file ..\lib\security\cacerts), run:

    keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore.\lib\security\cacerts -file "r:\root.crt"

accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK

source: http://www.java-samples.com/showtutorial.php?tutorialid=210

Why Doesn't C# Allow Static Methods to Implement an Interface?

I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:

string DoSomething<T>() where T:ISomeFunction
{
  if (T.someFunction())
    ...
}

Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:

  1. Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
  2. For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.

None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).

Check if file is already open

Hi I really hope this helps.

I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.

 try{

      Files.move(Paths.get(currentFile.getPath()), 
               Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);

      // DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM

 } catch (Exception e){

      // DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM

 }

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Formatting ISODate from Mongodb

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

HTML Text with tags to formatted text in an Excel cell

I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below

  1. First enable developer mode in Excel: Link
  2. Select the Developer Tab > Visual Basic
  3. Click View > Code
  4. Paste the code below updating the lines that require cell references to be correct.
  5. Click the Green Run Arrow or press F5
Sub Sample()
    Dim Ie As Object
    Set Ie = CreateObject("InternetExplorer.Application")
    With Ie
        .Visible = False
        .Navigate "about:blank"
        .document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
             'update to the cell that contains HTML you want converted
        .ExecWB 17, 0
             'Select all contents in browser
        .ExecWB 12, 2
             'Copy them
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
             'update to cell you want converted HTML pasted in
        .Quit
    End With
End Sub

How to import a jar in Eclipse

Jar File in the system path is:

C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar

ojdbc14.jar(it's jar file)

To import jar file in your Eclipse IDE, follow the steps given below.

  1. Right-click on your project
  2. Select Build Path
  3. Click on Configure Build Path
  4. Click on Libraries, select Modulepath and select Add External JARs
  5. Select the jar file from the required folder
  6. Click and Apply and Ok

While loop to test if a file exists in bash

do it like this

while true
do
  [ -f /tmp/list.txt ] && break
  sleep 2
done
ls -l /tmp/list.txt

What does string::npos mean in this code?

string::npos is a constant (probably -1) representing a non-position. It's returned by method find when the pattern was not found.

How can I convert a Word document to PDF?

unoconv, it's a python tool worked in UNIX. While I use Java to invoke the shell in UNIX, it works perfect for me. My source code : UnoconvTool.java. Both JODConverter and unoconv are said to use open office/libre office.

docx4j/docxreport, POI, PDFBox are good but they are missing some formats in conversion.

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

How to debug ORA-01775: looping chain of synonyms?

We had the same ORA-01775 error but in our case, the schema user was missing some 'grant select' on a couple of the public synonyms.

How to resolve /var/www copy/write permission denied?

Enter the following command in the directory you want to modify the right:

for example the directory: /var/www/html

sudo setfacl -m g:username:rwx . #-> for file

sudo setfacl -d -m g:username: rwx . #-> for directory

This will solve the problem.

Replace username with your username.

TypeScript Objects as Dictionary types as in C#

Lodash has a simple Dictionary implementation and has good TypeScript support

Install Lodash:

npm install lodash @types/lodash --save

Import and usage:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

Run PHP Task Asynchronously

PHP is a single-threaded language, so there is no official way to start an asynchronous process with it other than using exec or popen. There is a blog post about that here. Your idea for a queue in MySQL is a good idea as well.

Your specific requirement here is for sending an email to the user. I'm curious as to why you are trying to do that asynchronously since sending an email is a pretty trivial and quick task to perform. I suppose if you are sending tons of email and your ISP is blocking you on suspicion of spamming, that might be one reason to queue, but other than that I can't think of any reason to do it this way.

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

Converting between strings and ArrayBuffers

Yes:

const encstr = (`TextEncoder` in window) ? new TextEncoder().encode(str) : Uint8Array.from(str, c => c.codePointAt(0));

The source was not found, but some or all event logs could not be searched

I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.