Programs & Examples On #Adventureworks

A sample SQL database for SQL Server, maintained by Microsoft.

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Use Master
alter database databasename set offline with rollback immediate;

--Do Actual Restore
RESTORE DATABASE databasename
FROM DISK = 'path of bak file'
WITH MOVE 'datafile_data' TO 'D:\newDATA\data.mdf',
MOVE 'logfile_Log' TO 'D:\newDATA\DATA_log.ldf',replace

alter database databasename set online with rollback immediate;
GO

Java program to connect to Sql Server and running the sample query From Eclipse

The problem is with Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); this line. The Class qualified name is wrong

It is sqlserver.jdbc not jdbc.sqlserver

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

For me it was because only Windows Authentication was enabled. To change security authentication mode. In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties. On the Security page, under Server authentication, select the new server authentication mode, and then click OK. Change Server Authentication Mode - MSDN - Microsoft https://msdn.microsoft.com/en-AU/library/ms188670.aspx

Inserting values into a SQL Server database using ado.net via C#

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
    con.Open();
    SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
    SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
    DataSet ds = new DataSet("detail1");
    ad.Fill(ds, "detail1");
    DataRow row = ds.Tables["detail1"].NewRow();
    row["Name"] = textBox1.Text;
    row["address"] =textBox2.Text;
    ds.Tables["detail1"].Rows.Add(row);
    ad.Update(ds, "detail1");
    con.Close();
    MessageBox.Show("insert secussfully"); 
}

The SQL OVER() clause - when and why is it useful?

The OVER clause is powerful in that you can have aggregates over different ranges ("windowing"), whether you use a GROUP BY or not

Example: get count per SalesOrderID and count of all

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) AS 'Count'
    ,COUNT(*) OVER () AS 'CountAll'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)
GROUP BY
     SalesOrderID, ProductID, OrderQty

Get different COUNTs, no GROUP BY

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'CountQtyPerOrder'
    ,COUNT(OrderQty) OVER(PARTITION BY ProductID) AS 'CountQtyPerProduct',
    ,COUNT(*) OVER () AS 'CountAllAgain'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)

How do I obtain a list of all schemas in a Sql Server database

You can also query the INFORMATION_SCHEMA.SCHEMATA view:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA

I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:

Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

Ironically, this is immediately preceded by this note:

Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Access is denied when attaching a database

Every time I have run into this issue was when attempting to attach a database that is in a different directory from the default database directory that is setup in SQL server.

I would highly recommend that instead of jacking with permissions on various directories and accounts that you simply move your data file into the directory that sql server expects to find it.

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine

Specifically I would point out the following

Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.

So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

WITH CHECK is indeed the default behaviour however it is good practice to include within your coding.

The alternative behaviour is of course to use WITH NOCHECK, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.

Proper use of 'yield return'

The usage of yield is similar to the keyword return, except that it will return a generator. And the generator object will only traverse once.

yield has two benefits:

  1. You do not need to read these values twice;
  2. You can get many child nodes but do not have to put them all in memory.

There is another clear explanation maybe help you.

Today's Date in Perl in MM/DD/YYYY format

Perl Code for Unix systems:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;

# Remove newline character
$current_date = substr($current_date,0,-1);

print $current_date, "\n";

Create Hyperlink in Slack

I know you wanted only a hypertext link, but if you copy & paste a link address into Slack that does work very nicely. i.e. if referring to VersionOne ticket number (V1 mouseover the ticket window to open the mouseover window, then right click on the ticket number for the option to "copy link address", then in Slack paste. It'll paste the full ticket URL but then it shows a nice summary of the ticket number and name and you can click it to go right into the ticket.)

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Since you're dealing with values that are just supposed to be boolean anyway, just use == and convert the logical response to as.integer:

df <- data.frame(col = c("true", "true", "false"))
df
#     col
# 1  true
# 2  true
# 3 false
df$col <- as.integer(df$col == "true")
df
#   col
# 1   1
# 2   1
# 3   0

Git cli: get user info from username

While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:

To see a list of all users in a git repo using the git cli:

git log --format="%an %ae" | sort | uniq

To search for a specific user by name, e.g., "John":

git log --format="%an %ae" | sort | uniq | grep -i john

How do I update/upsert a document in Mongoose?

There is a bug introduced in 2.6, and affects to 2.7 as well

The upsert used to work correctly on 2.4

https://groups.google.com/forum/#!topic/mongodb-user/UcKvx4p4hnY https://jira.mongodb.org/browse/SERVER-13843

Take a look, it contains some important info

UPDATED:

It doesnt mean upsert does not work. Here is a nice example of how to use it:

User.findByIdAndUpdate(userId, {online: true, $setOnInsert: {username: username, friends: []}}, {upsert: true})
    .populate('friends')
    .exec(function (err, user) {
        if (err) throw err;
        console.log(user);

        // Emit load event

        socket.emit('load', user);
    });

How to convert a String to CharSequence?

Attempting to provide some (possible) context for OP's question by posting my own trouble. I'm working in Scala, but the error messages I'm getting all reference Java types, and the error message reads a lot like the compiler complaining that CharSequence is not a String. I confirmed in the source code that String implements the CharSequence interface, but the error message draws attention to the difference between String and CharSequence while hiding the real source of the trouble:

scala> cols
res8: Iterable[String] = List(Item, a, b)

scala> val header = String.join(",", cols)
<console>:13: error: overloaded method value join with alternatives:
  (x$1: CharSequence,x$2: java.lang.Iterable[_ <: CharSequence])String <and>
  (x$1: CharSequence,x$2: CharSequence*)String
 cannot be applied to (String, Iterable[String])
       val header = String.join(",", cols)

I was able to fix this problem with the realization that the problem wasn't String / CharSequence, but rather a mismatch between java.lang.Iterable and Scala's built-in Iterable.

scala> val header = String.join(",", coll: _*)
header: String = Item,a,b

My particular problem can also be solved via the answers at Scala: join an iterable of strings

In summary, OP and others who come across similar problems should parse the error messages very closely and see what other type conversions might be involved.

Setting a PHP $_SESSION['var'] using jQuery

I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...

My problem was kind of easy:

-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.

In my case, to correct that situation, I changed my jQuery $.post code this way:

$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
    if(ret==0){
        window.alert("success!");
        location.replace("next_page.php");
    }
    else{
        window.alert("error!");
    }
});

Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).

Greetings.

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Check if EditText is empty.

"check out this i m sure you will like it."

log_in.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        username=user_name.getText().toString();
        password=pass_word.getText().toString();
        if(username.equals(""))
        {
            user_name.setError("Enter username");
        }
        else if(password.equals(""))
        {
            pass_word.setError("Enter your password");
        }
        else
        {
            Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
            startActivity(intent);
        }
    }
});

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)
    clear

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

How to check if an NSDictionary or NSMutableDictionary contains a key?

I like Fernandes' answer even though you ask for the obj twice.

This should also do (more or less the same as Martin's A).

id obj;

if ((obj=[dict objectForKey:@"blah"])) {
   // use obj
} else {
   // Do something else like creating the obj and add the kv pair to the dict
}

Martin's and this answer both work on iPad2 iOS 5.0.1 9A405

Material Design not styling alert dialogs

AppCompat doesn't do that for dialogs (not yet at least)

EDIT: it does now. make sure to use android.support.v7.app.AlertDialog

Open multiple Projects/Folders in Visual Studio Code

It's not possible to open a new instance of Visual Studio Code normally, neither it works if you open the new one as Administrator.

Solution: simply right click on VS Code .exe file, and click "New Window" you can open as many new windows as you want. :)

Java String split removed empty values

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

String[] split = data.split("\\|", -1);

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Exception:

It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array.
It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.

How can I run a php without a web server?

See https://github.com/php-pm/php-pm.

Works fine with symphony.

But I'm fighting with it, trying run a slim app

Is there a CSS selector for the first direct child only?

The CSS selector for the direct first-child in your case is:

.section > :first-child

The direct selector is > and the first child selector is :first-child

No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:

div.section > :first-child

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

Java naming convention for static final variables

There is no "right" way -- there are only conventions. You've stated the most common convention, and the one that I follow in my own code: all static finals should be in all caps. I imagine other teams follow other conventions.

What is the difference between __init__ and __call__?

__call__ makes the instance of a class callable. Why would it be required?

Technically __init__ is called once by __new__ when object is created, so that it can be initialized.

But there are many scenarios where you might want to redefine your object, say you are done with your object, and may find a need for a new object. With __call__ you can redefine the same object as if it were new.

This is just one case, there can be many more.

Array inside a JavaScript Object?

var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

visual c++: #include files from other projects in the same solution

Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :

  1. The include can be written in a relative path (E.g. #include "../libProject/libHeader.h").
  2. For the linker, right click on "References", Click on Add Reference, and choose the other project.

Is there a command for formatting HTML in the Atom editor?

Not Just HTML, Using atom-beautify - Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.

To Install the atom-beautify package :

  • Open Atom Editor.
  • Press Ctrl+Shift+P (Cmd+Shift+P on mac), this will open the atom Command Palette.
  • Search and click on Install Packages & Themes. A Install Package window comes up.
  • Search for Beautify package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify.
  • Now Restart atom and TADA! now you are ready for quick formatting.

To Format text Using atom-beautify :

  • Go to the file you want to format.
  • Hit Ctrl+Alt+B (Ctrl+Option+B on mac).
  • Your file is formatted in seconds.

Are there bookmarks in Visual Studio Code?

You need to do this via an extension as of the version 1.8.1.

  1. Go to View ? Extensions. This will open Extensions Panel.

  2. Type bookmark to list all related extensions.

  3. Install


I personally like "Numbered Bookmarks" - it is pretty simple and powerful.

Go to the line you need to create a bookmark.

Click Ctrl + Shift + [some number]

Ex: Ctrl + Shift + 2

Now you can jump to this line from anywhere by pressing Ctrl + number

Ex: Ctrl + 2

Multiple lines of text in UILabel

I found a solution.

One just has to add the following code:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

How to simulate "Press any key to continue?"

Also you can use getch() from conio.h. Just like this:

...includes, defines etc
void main()
{
//operator
getch(); //now this function is waiting for any key press. When you have pressed its     just     //finish and next line of code will be called
}

So, because UNIX does not have conio.h, we can simulate getch() by this code (but this code already written by Vinary, my fail):

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch( ) {
  struct termios oldt,
             newt;
  int            ch;
  tcgetattr( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
  return ch;
}

Difference between float and decimal data type

MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.

The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.

By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)

The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.

As 18 8-bit chars: 144 bits

As 18 4-bit nybbles: 72 bits

As 2 32-bit integers: 64 bits

Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.

So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.

With an 7-bit int: 0 - 99

With a 15-bit int: 0 - 9,999

With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)

1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.

This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.

Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.

In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.

The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.

As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.

Adding space/padding to a UILabel

Objective-C

Based on Tai Le answer up there which implements the feature inside an IB Designable, here's the Objective-C version.

Put this in YourLabel.h

@interface YourLabel : UILabel

@property IBInspectable CGFloat topInset;
@property IBInspectable CGFloat bottomInset;
@property IBInspectable CGFloat leftInset;
@property IBInspectable CGFloat rightInset;

@end

And this would go in YourLabel.m

IB_DESIGNABLE

@implementation YourLabel

#pragma mark - Super

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.topInset = 0;
        self.bottomInset = 0;
        self.leftInset = 0;
        self.rightInset = 0;
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = UIEdgeInsetsMake(self.topInset, self.leftInset, self.bottomInset, self.rightInset);
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

- (CGSize)intrinsicContentSize {

    CGSize size = [super intrinsicContentSize];
    return CGSizeMake(size.width + self.leftInset + self.rightInset,
                      size.height + self.topInset + self.bottomInset);
}

@end

You can then modify YourLabel insets directly in Interface Builder after specifying the class inside the XIB or storyboard, the default value of the insets being zero.

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.

How to remove any URL within a string in Python

import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
    print (i)

Out

list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6    ?

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

FtpWebRequest Download File

I know this is an old Post but I am adding here for future reference. Here is a solution that I found:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

Updated based upon excellent suggestion by Ilya Kogan

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

How to test if JSON object is empty in Java

I have added isEmpty() methods on JSONObject and JSONArray()

 //on JSONObject 
 public Boolean isEmpty(){         
     return !this.keys().hasNext();
 }

...

//on JSONArray
public Boolean isEmpty(){
    return this.length()==0;        
}

you can get it here https://github.com/kommradHomer/JSON-java

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

btoa() only support characters from String.fromCodePoint(0) up to String.fromCodePoint(255). For Base64 characters with a code point 256 or higher you need to encode/decode these before and after.

And in this point it becomes tricky...

Every possible sign are arranged in a Unicode-Table. The Unicode-Table is divided in different planes (languages, math symbols, and so on...). Every sign in a plane has a unique code point number. Theoretically, the number can become arbitrarily large.

A computer stores the data in bytes (8 bit, hexadecimal 0x00 - 0xff, binary 00000000 - 11111111, decimal 0 - 255). This range normally use to save basic characters (Latin1 range).

For characters with higher codepoint then 255 exist different encodings. JavaScript use 16 bits per sign (UTF-16), the string called DOMString. Unicode can handle code points up to 0x10fffff. That means, that a method must be exist to store several bits over several cells away.

String.fromCodePoint(0x10000).length == 2

UTF-16 use surrogate pairs to store 20bits in two 16bit cells. The first higher surrogate begins with 110110xxxxxxxxxx, the lower second one with 110111xxxxxxxxxx. Unicode reserved own planes for this: https://unicode-table.com/de/#high-surrogates

To store characters in bytes (Latin1 range) standardized procedures use UTF-8.

Sorry to say that, but I think there is no other way to implement this function self.

function stringToUTF8(str)
{
    let bytes = [];

    for(let character of str)
    {
        let code = character.codePointAt(0);

        if(code <= 127)
        {
            let byte1 = code;

            bytes.push(byte1);
        }
        else if(code <= 2047)
        {
            let byte1 = 0xC0 | (code >> 6);
            let byte2 = 0x80 | (code & 0x3F);

            bytes.push(byte1, byte2);
        }
        else if(code <= 65535)
        {
            let byte1 = 0xE0 | (code >> 12);
            let byte2 = 0x80 | ((code >> 6) & 0x3F);
            let byte3 = 0x80 | (code & 0x3F);

            bytes.push(byte1, byte2, byte3);
        }
        else if(code <= 2097151)
        {
            let byte1 = 0xF0 | (code >> 18);
            let byte2 = 0x80 | ((code >> 12) & 0x3F);
            let byte3 = 0x80 | ((code >> 6) & 0x3F);
            let byte4 = 0x80 | (code & 0x3F);

            bytes.push(byte1, byte2, byte3, byte4);
        }
    }

    return bytes;
}

function utf8ToString(bytes, fallback)
{
    let valid = undefined;
    let codePoint = undefined;
    let codeBlocks = [0, 0, 0, 0];

    let result = "";

    for(let offset = 0; offset < bytes.length; offset++)
    {
        let byte = bytes[offset];

        if((byte & 0x80) == 0x00)
        {
            codeBlocks[0] = byte & 0x7F;

            codePoint = codeBlocks[0];
        }
        else if((byte & 0xE0) == 0xC0)
        {
            codeBlocks[0] = byte & 0x1F;

            byte = bytes[++offset];
            if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }

            codeBlocks[1] = byte & 0x3F;

            codePoint = (codeBlocks[0] << 6) + codeBlocks[1];
        }
        else if((byte & 0xF0) == 0xE0)
        {
            codeBlocks[0] = byte & 0xF;

            for(let blockIndex = 1; blockIndex <= 2; blockIndex++)
            {
                byte = bytes[++offset];
                if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }

                codeBlocks[blockIndex] = byte & 0x3F;
            }
            if(valid === false) { break; }

            codePoint = (codeBlocks[0] << 12) + (codeBlocks[1] << 6) + codeBlocks[2];
        }
        else if((byte & 0xF8) == 0xF0)
        {
            codeBlocks[0] = byte & 0x7;

            for(let blockIndex = 1; blockIndex <= 3; blockIndex++)
            {
                byte = bytes[++offset];
                if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }

                codeBlocks[blockIndex] = byte & 0x3F;
            }
            if(valid === false) { break; }

            codePoint = (codeBlocks[0] << 18) + (codeBlocks[1] << 12) + (codeBlocks[2] << 6) + (codeBlocks[3]);
        }
        else
        {
            valid = false; break;
        }

        result += String.fromCodePoint(codePoint);
    }

    if(valid === false)
    {
        if(!fallback)
        {
            throw new TypeError("Malformed utf-8 encoding.");
        }

        result = "";

        for(let offset = 0; offset != bytes.length; offset++)
        {
            result += String.fromCharCode(bytes[offset] & 0xFF);
        }
    }

    return result;
}

function decodeBase64(text, binary)
{
    if(/[^0-9a-zA-Z\+\/\=]/.test(text)) { throw new TypeError("The string to be decoded contains characters outside of the valid base64 range."); }

    let codePointA = 'A'.codePointAt(0);
    let codePointZ = 'Z'.codePointAt(0);
    let codePointa = 'a'.codePointAt(0);
    let codePointz = 'z'.codePointAt(0);
    let codePointZero = '0'.codePointAt(0);
    let codePointNine = '9'.codePointAt(0);
    let codePointPlus = '+'.codePointAt(0);
    let codePointSlash = '/'.codePointAt(0);

    function getCodeFromKey(key)
    {
        let keyCode = key.codePointAt(0);

        if(keyCode >= codePointA && keyCode <= codePointZ)
        {
            return keyCode - codePointA;
        }
        else if(keyCode >= codePointa && keyCode <= codePointz)
        {
            return keyCode + 26 - codePointa;
        }
        else if(keyCode >= codePointZero && keyCode <= codePointNine)
        {
            return keyCode + 52 - codePointZero;
        }
        else if(keyCode == codePointPlus)
        {
            return 62;
        }
        else if(keyCode == codePointSlash)
        {
            return 63;
        }

        return undefined;
    }

    let codes = Array.from(text).map(character => getCodeFromKey(character));

    let bytesLength = Math.ceil(codes.length / 4) * 3;

    if(codes[codes.length - 2] == undefined) { bytesLength = bytesLength - 2; } else if(codes[codes.length - 1] == undefined) { bytesLength--; }

    let bytes = new Uint8Array(bytesLength);

    for(let offset = 0, index = 0; offset < bytes.length;)
    {
        let code1 = codes[index++];
        let code2 = codes[index++];
        let code3 = codes[index++];
        let code4 = codes[index++];

        let byte1 = (code1 << 2) | (code2 >> 4);
        let byte2 = ((code2 & 0xf) << 4) | (code3 >> 2);
        let byte3 = ((code3 & 0x3) << 6) | code4;

        bytes[offset++] = byte1;
        bytes[offset++] = byte2;
        bytes[offset++] = byte3;
    }

    if(binary) { return bytes; }

    return utf8ToString(bytes, true);
}

function encodeBase64(bytes) {
    if (bytes === undefined || bytes === null) {
        return '';
    }
    if (bytes instanceof Array) {
        bytes = bytes.filter(item => {
            return Number.isFinite(item) && item >= 0 && item <= 255;
        });
    }

    if (
        !(
            bytes instanceof Uint8Array ||
            bytes instanceof Uint8ClampedArray ||
            bytes instanceof Array
        )
    ) {
        if (typeof bytes === 'string') {
            const str = bytes;
            bytes = Array.from(unescape(encodeURIComponent(str))).map(ch =>
                ch.codePointAt(0)
            );
        } else {
            throw new TypeError('bytes must be of type Uint8Array or String.');
        }
    }

    const keys = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '+',
        '/'
    ];
    const fillKey = '=';

    let byte1;
    let byte2;
    let byte3;
    let sign1 = ' ';
    let sign2 = ' ';
    let sign3 = ' ';
    let sign4 = ' ';

    let result = '';

    for (let index = 0; index < bytes.length; ) {
        let fillUpAt = 0;

        // tslint:disable:no-increment-decrement
        byte1 = bytes[index++];
        byte2 = bytes[index++];
        byte3 = bytes[index++];

        if (byte2 === undefined) {
            byte2 = 0;
            fillUpAt = 2;
        }

        if (byte3 === undefined) {
            byte3 = 0;
            if (!fillUpAt) {
                fillUpAt = 3;
            }
        }

        // tslint:disable:no-bitwise
        sign1 = keys[byte1 >> 2];
        sign2 = keys[((byte1 & 0x3) << 4) + (byte2 >> 4)];
        sign3 = keys[((byte2 & 0xf) << 2) + (byte3 >> 6)];
        sign4 = keys[byte3 & 0x3f];

        if (fillUpAt > 0) {
            if (fillUpAt <= 2) {
                sign3 = fillKey;
            }
            if (fillUpAt <= 3) {
                sign4 = fillKey;
            }
        }

        result += sign1 + sign2 + sign3 + sign4;

        if (fillUpAt) {
            break;
        }
    }

    return result;
}

let base64 = encodeBase64("\u{1F604}"); // unicode code point escapes for smiley
let str = decodeBase64(base64);

console.log("base64", base64);
console.log("str", str);

document.body.innerText = str;

how to use it: decodeBase64(encodeBase64("\u{1F604}"))

demo: https://jsfiddle.net/qrLadeb8/

What are good ways to prevent SQL injection?

SQL injection can be a tricky problem but there are ways around it. Your risk is reduced your risk simply by using an ORM like Linq2Entities, Linq2SQL, NHibrenate. However you can have SQL injection problems even with them.

The main thing with SQL injection is user controlled input (as is with XSS). In the most simple example if you have a login form (I hope you never have one that just does this) that takes a username and password.

SELECT * FROM Users WHERE Username = '" + username + "' AND password = '" + password + "'"

If a user were to input the following for the username Admin' -- the SQL Statement would look like this when executing against the database.

SELECT * FROM Users WHERE Username = 'Admin' --' AND password = ''

In this simple case using a paramaterized query (which is what an ORM does) would remove your risk. You also have a the issue of a lesser known SQL injection attack vector and that's with stored procedures. In this case even if you use a paramaterized query or an ORM you would still have a SQL injection problem. Stored procedures can contain execute commands, and those commands themselves may be suceptable to SQL injection attacks.

CREATE PROCEDURE SP_GetLogin @username varchar(100), @password varchar(100) AS
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT * FROM users' +
              ' FROM Product Where username = ''' + @username + ''' AND password = '''+@password+''''

EXECUTE sp_executesql @sql

So this example would have the same SQL injection problem as the previous one even if you use paramaterized queries or an ORM. And although the example seems silly you'd be surprised as to how often something like this is written.

My recommendations would be to use an ORM to immediately reduce your chances of having a SQL injection problem, and then learn to spot code and stored procedures which can have the problem and work to fix them. I don't recommend using ADO.NET (SqlClient, SqlCommand etc...) directly unless you have to, not because it's somehow not safe to use it with parameters but because it's that much easier to get lazy and just start writing a SQL query using strings and just ignoring the parameters. ORMS do a great job of forcing you to use parameters because it's just what they do.

Next Visit the OWASP site on SQL injection https://www.owasp.org/index.php/SQL_Injection and use the SQL injection cheat sheet to make sure you can spot and take out any issues that will arise in your code. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet finally I would say put in place a good code review between you and other developers at your company where you can review each others code for things like SQL injection and XSS. A lot of times programmers miss this stuff because they're trying to rush out some feature and don't spend too much time on reviewing their code.

Getting mouse position in c#

You must also have the following imports in order to import the DLL

using System.Runtime.InteropServices;
using System.Diagnostics;

How to get request URI without context path?

With Spring you can do:

String path = new UrlPathHelper().getPathWithinApplication(request);

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Back button and refreshing previous activity

If you want to refresh previous activity, this solution should work:

In previous activity where you want to refresh:

@Override
public void onRestart()
{
    super.onRestart();
    // do some stuff here
}

Table header to stay fixed at the top when user scrolls it out of view with jQuery

Well, I was trying to obtain the same effect without resorting to fixed size columns or having a fixed height for the entire table.

The solution I came up with is a hack. It consists of duplicating the entire table then hiding everything but the header, and making that have a fixed position.

HTML

<div id="table-container">
<table id="maintable">
    <thead>
        <tr>
            <th>Col1</th>
            <th>Col2</th>
            <th>Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>some really long line here instead</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
    </tbody>
</table>
<div id="bottom_anchor"></div>
</div>

CSS

body { height: 1000px; }
thead{
    background-color:white;
}

javascript

function moveScroll(){
    var scroll = $(window).scrollTop();
    var anchor_top = $("#maintable").offset().top;
    var anchor_bottom = $("#bottom_anchor").offset().top;
    if (scroll>anchor_top && scroll<anchor_bottom) {
    clone_table = $("#clone");
    if(clone_table.length == 0){
        clone_table = $("#maintable").clone();
        clone_table.attr('id', 'clone');
        clone_table.css({position:'fixed',
                 'pointer-events': 'none',
                 top:0});
        clone_table.width($("#maintable").width());
        $("#table-container").append(clone_table);
        $("#clone").css({visibility:'hidden'});
        $("#clone thead").css({'visibility':'visible','pointer-events':'auto'});
    }
    } else {
    $("#clone").remove();
    }
}
$(window).scroll(moveScroll); 

See here: http://jsfiddle.net/QHQGF/7/

Edit: updated the code so that the thead can receive pointer events(so buttons and links in the header still work). This fixes the problem reported by luhfluh and Joe M.

New jsfiddle here: http://jsfiddle.net/cjKEx/

Rails: Can't verify CSRF token authenticity when making a POST request

Another way to turn off CSRF that won't render a null session is to add:

skip_before_action :verify_authenticity_token

in your Rails Controller. This will ensure you still have access to session info.

Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.

Simple state machine example in C#?

What a bout StatePattern. Does that fit your needs?

I think its context related, but its worth a shot for sure.

http://en.wikipedia.org/wiki/State_pattern

This let your states decide where to go and not the "object" class.

Bruno

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

Purge Kafka Topic

./kafka-topics.sh --describe --zookeeper zkHost:2181 --topic myTopic

This should give retention.ms configured. Then you can use above alter command to change to 1second (and later revert back to default).

Topic:myTopic   PartitionCount:6        ReplicationFactor:1     Configs:retention.ms=86400000

Making a drop down list using swift?

Unfortunately if you're looking to apply UIPopoverController in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover property to achieve the same result.

Popover

In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.

Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

just add in build.gradle

compile 'com.parse.bolts:bolts-android:1.+'

compile 'com.parse:parse-android:1.11.0'

and sync Project with Gradle Files enter image description here But Don't Add The parse Jar in libs :) OKK

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

Give all permissions to a user on a PostgreSQL database

All commands must be executed while connected to the right database in the right database cluster. Make sure of it.

The user needs access to the database, obviously:

GRANT CONNECT ON DATABASE my_db TO my_user;

And (at least) the USAGE privilege on the schema:

GRANT USAGE ON SCHEMA public TO my_user;

Or grant USAGE on all custom schemas:

DO
$$
BEGIN
   -- RAISE NOTICE '%', (  -- use instead of EXECUTE to see generated commands
   EXECUTE (
   SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
   FROM   pg_namespace
   WHERE  nspname <> 'information_schema' -- exclude information schema and ...
   AND    nspname NOT LIKE 'pg\_%'        -- ... system schemas
   );
END
$$;

Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;

For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).

There are some other objects, the manual for GRANT has the complete list as of Postgres 12:

privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)

But the rest is rarely needed. More details:

Consider upgrading to a current version.

HTML button to NOT submit form

Another option that worked for me was to add onsubmit="return false;" to the form tag.

<form onsubmit="return false;">

Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element the won't submit.

CSS: Center block, but align contents to the left

<div>
    <div style="text-align: left; width: 400px; border: 1px solid black; margin: 0 auto;">
         <pre>
Hello
Testing
Beep
         </pre>
    </div>
</div>

Using $_POST to get select option value from HTML

<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];

Please add a @Pipe/@Directive/@Component annotation. Error

In my case, I accidentally added the package in the declaration but it should be in imports.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

In windows environment just check the PATH environment variable if Oracle JRE runtime refreshed the path and put himself at the very beginning of the path. In this case even if the JAVA_HOME AND JRE_HOME points to the correct JDK, the JRE will have precedence. And this case IntelliJ will not start Tomcat instance with the mentioned error message.

dynamically set iframe src

Try this...

function urlChange(url) {
    var site = url+'?toolbar=0&amp;navpanes=0&amp;scrollbar=0';
    document.getElementById('iFrameName').src = site;
}

<a href="javascript:void(0);" onClick="urlChange('www.mypdf.com/test.pdf')">TEST </a>

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

Set initial focus in an Android application

I found this worked best for me.

In AndroidManifest.xml <activity> element add android:windowSoftInputMode="stateHidden"

This always hides the keyboard when entering the activity.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

How to retrieve Jenkins build parameters using the Groovy API?

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 

Working with $scope.$emit and $scope.$on

The Easiest way :

HTML

  <div ng-app="myApp" ng-controller="myCtrl"> 

        <button ng-click="sendData();"> Send Data </button>

    </div>

JavaScript

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $rootScope) {
            function sendData($scope) {
                var arrayData = ['sam','rumona','cubby'];
                $rootScope.$emit('someEvent', arrayData);
            }

        });
        app.controller('yourCtrl', function($scope, $rootScope) {
            $rootScope.$on('someEvent', function(event, data) {
                console.log(data); 
            }); 
        });
    </script>

How to use NULL or empty string in SQL

You can simply do this:

SELECT *
FROM   yourTable
WHERE  yourColumn IS NULL OR yourColumn = ''

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

How to make PyCharm always show line numbers

For version 3.0 (Community Edition):

File -> Settings -> Editor (under IDE Settings) -> Appearance -> check 'Show line numbers'

Load dimension value from res/values/dimension.xml from source code

For those who just need to save some int value in the resources, you can do the following.

integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="default_value">100</integer>
</resources> 

Code

int defaultValue = getResources().getInteger(R.integer.default_value);

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

MySQL stored procedure return value

Add:

  • DELIMITER at the beginning and end of the SP.
  • DROP PROCEDURE IF EXISTS validar_egreso; at the beginning
  • When calling the SP, use @variableName.

This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).

DROP PROCEDURE IF EXISTS `validar_egreso`;

DELIMITER $$

CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
)
BEGIN

    DECLARE resta INT;
    SET resta = 0;

    SELECT (codigo_producto - cantidad) INTO resta;

    IF(resta > 1) THEN
       SET valido = 1;
    ELSE
       SET valido = -1;
    END IF;

    SELECT valido;
END $$

DELIMITER ;

-- execute the stored procedure
CALL validar_egreso(4, 1, @val);

-- display the result
select @val;

PHP import Excel into database (xls & xlsx)

Sometimes I need to import large xlsx files into database, so I use spreadsheet-reader as it can read file per-row. It is very memory-efficient way to import.

<?php
    // If you need to parse XLS files, include php-excel-reader
    require('php-excel-reader/excel_reader2.php');

    require('SpreadsheetReader.php');

    $Reader = new SpreadsheetReader('example.xlsx');
    // insert every row just after reading it
    foreach ($Reader as $row)
    {
        $db->insert($row);
    }
?>

https://github.com/nuovo/spreadsheet-reader

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

C# - Fill a combo box with a DataTable

A few points:

1) "DataBind()" is only for web apps (not windows apps).

2) Your code looks very 'JAVAish' (not a bad thing, just an observation).

Try this:

mnuActionLanguage.ComboBox.DataSource = languages;

If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.

But make sure you include x64 JDK and JRE addresses in your path.

How to send a "multipart/form-data" with requests in python?

import requests
# assume sending two files
url = "put ur url here"
f1 = open("file 1 path", 'rb')
f2 = open("file 2 path", 'rb')
response = requests.post(url,files={"file1 name": f1, "file2 name":f2})
print(response)

xls to csv converter

Quoting an answer from Scott Ming, which works with workbook containing multiple sheets:

Here is a python script getsheets.py (mirror), you should install pandas and xlrd before you use it.

Run this:

pip3 install pandas xlrd  # or `pip install pandas xlrd`

How does it works?

$ python3 getsheets.py -h
Usage: getsheets.py [OPTIONS] INPUTFILE

Convert a Excel file with multiple sheets to several file with one sheet.

Examples:

    getsheets filename

    getsheets filename -f csv

Options:
-f, --format [xlsx|csv]  Default xlsx.
-h, --help               Show this message and exit.

Convert to several xlsx:

$ python3 getsheets.py goods_temp.xlsx
Sheet.xlsx Done!
Sheet1.xlsx Done!

All Done!

Convert to several csv:

$ python3 getsheets.py goods_temp.xlsx -f csv
Sheet.csv Done!
Sheet1.csv Done!

All Done!

getsheets.py:

# -*- coding: utf-8 -*-

import click
import os
import pandas as pd


def file_split(file):
    s = file.split('.')
    name = '.'.join(s[:-1])  # get directory name
    return name


def getsheets(inputfile, fileformat):
    name = file_split(inputfile)
    try:
        os.makedirs(name)
    except:
        pass

    df1 = pd.ExcelFile(inputfile)
    for x in df1.sheet_names:
        print(x + '.' + fileformat, 'Done!')
        df2 = pd.read_excel(inputfile, sheetname=x)
        filename = os.path.join(name, x + '.' + fileformat)
        if fileformat == 'csv':
            df2.to_csv(filename, index=False)
        else:
            df2.to_excel(filename, index=False)
    print('\nAll Done!')


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('inputfile')
@click.option('-f', '--format', type=click.Choice([
    'xlsx', 'csv']), default='xlsx', help='Default xlsx.')
def cli(inputfile, format):
    '''Convert a Excel file with multiple sheets to several file with one sheet.

    Examples:

    \b
        getsheets filename

    \b
        getsheets filename -f csv
    '''
    if format == 'csv':
        getsheets(inputfile, 'csv')
    else:
        getsheets(inputfile, 'xlsx')


cli()

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

I found a hint in the following question - Python: Histogram with area normalized to something other than 1

But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

import matplotlib.pyplot as plt

# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.

nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))

plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.

This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

Just thought I'd share my experience. Thank you.

Preserve Line Breaks From TextArea When Writing To MySQL

why make is sooooo hard people when it can be soooo easy :)

//here is the pull from the form
$your_form_text = $_POST['your_form_text'];


//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);

//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);

you will obviously need headers and likely have more fields, but this is your textarea take care of

referenced before assignment error in python

I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!

-Sam

How can I run a function from a script in command line?

Briefly, no.

You can import all of the functions in the script into your environment with source (help source for details), which will then allow you to call them. This also has the effect of executing the script, so take care.

There is no way to call a function from a shell script as if it were a shared library.

Zabbix server is not running: the information displayed may not be current

On RHEL/CentOS/OEL 6

  • Check that the firewall is allowing connection to Zabbix Server port which is 10051, as a user with root priv:

    vi /etc/sysconfig/iptables

and add the following lines

-A INPUT -m state --state NEW -m tcp -p tcp --dport 10051 -j ACCEPT

restart iptables

# service iptables restart

If you have disabled IPV6, you need to also edit the hosts file and remove IPV6 line for "localhost"

# vi /etc/hosts

remove or comment out "#" the ipv6 line for localhost

::1                   localhost6.localdomain6   localhost6

restart the zabbix-server and check if the error message is gone.

What is the default Precision and Scale for a Number in Oracle?

NUMBER (precision, scale)

If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero.

A lot more info at:

http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

Sort table rows In Bootstrap

These examples are minified because StackOverflow has a maximum character limit and links to external code are discouraged since links can break.

There are multiple plugins if you look: Bootstrap Sortable, Bootstrap Table or DataTables.

Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs

_x000D_
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs

_x000D_
_x000D_
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
                  

DisplayName attribute from Resources?

How about writing a custom attribute:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}

How to set a variable to be "Today's" date in Python/Pandas

Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

I got this issue.But I think this problem is not related to commit and commitAllowStateLoss.

The following stack trace and exception message is about commit().

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)

But this exception was caused by onBackPressed()

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(Unknown Source)
at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(Unknown Source)
at android.support.v4.app.FragmentActivity.onBackPressed(Unknown Source)

They were all caused by checkStateLoss()

private void checkStateLoss() {
    if (mStateSaved) {
        throw new IllegalStateException(
                "Can not perform this action after onSaveInstanceState");
    }
    if (mNoTransactionsBecause != null) {
        throw new IllegalStateException(
                "Can not perform this action inside of " + mNoTransactionsBecause);
    }

mStateSaved will be true after onSaveInstanceState.

This problem rarely happens.I have never encountered this problem.I can not reoccurrence the problem.

I found issue 25517

It might have occurred in the following circumstances

  1. Back key is called after onSaveInstanceState, but before the new activity is started.

  2. use onStop() in code

I'm not sure what the root of the problem is. So I used an ugly way.

@Override
public void onBackPressed() {

    try{
        super.onBackPressed();
    }catch (IllegalStateException e){
        // can output some information here
        finish();
    }
}

How can one grab a stack trace in C?

For the past few years I have been using Ian Lance Taylor's libbacktrace. It is much cleaner than the functions in the GNU C library which require exporting all the symbols. It provides more utility for the generation of backtraces than libunwind. And last but not least, it is not defeated by ASLR as are approaches requiring external tools such as addr2line.

Libbacktrace was initially part of the GCC distribution, but it is now made available by the author as a standalone library under a BSD license:

https://github.com/ianlancetaylor/libbacktrace

At the time of writing, I would not use anything else unless I need to generate backtraces on a platform which is not supported by libbacktrace.

how to run python files in windows command prompt?

You have to install Python and add it to PATH on Windows. After that you can try:

python `C:/pathToFolder/prog.py`

or go to the files directory and execute:

python prog.py

HTML Code for text checkbox '?'

This will do:

&#x25a2;

It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)

Or

&#x25fb;

as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)

Two with shadow:

&#x274f;
&#x2751;

as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).

You can also use

&#x2610;

which is ?
(known as a "BALLOT BOX").

A sample is at http://jsfiddle.net/S2QCt/267/

(a note: on the Mac, &#x25a2; is quite nice, because it is bigger and somewhat more elegant than &#x2610; On Windows, &#x2610; looks more standard, while &#x25a2; is somewhat small.)

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

OR

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;

How to populate/instantiate a C# array with a single value?

Just a benchmark:

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.997 (1909/November2018Update/19H2)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.302
  [Host]        : .NET Core 3.1.6 (CoreCLR 4.700.20.26901, CoreFX 4.700.20.31603), X64 RyuJIT
  .NET Core 3.1 : .NET Core 3.1.6 (CoreCLR 4.700.20.26901, CoreFX 4.700.20.31603), X64 RyuJIT

Job=.NET Core 3.1  Runtime=.NET Core 3.1

|           Method |     Mean |     Error |    StdDev |
|----------------- |---------:|----------:|----------:|
| EnumerableRepeat | 2.311 us | 0.0228 us | 0.0213 us |
|  NewArrayForEach | 2.007 us | 0.0392 us | 0.0348 us |
|        ArrayFill | 2.426 us | 0.0103 us | 0.0092 us |
    [SimpleJob(BenchmarkDotNet.Jobs.RuntimeMoniker.NetCoreApp31)]
    public class InitializeArrayBenchmark {
        const int ArrayLength = 1600;

        [Benchmark]
        public double[] EnumerableRepeat() {
            return Enumerable.Repeat(double.PositiveInfinity, ArrayLength).ToArray();
        }

        [Benchmark]
        public double[] NewArrayForEach() {
            var array = new double[ArrayLength];

            for (int i = 0; i < array.Length; i++) {
                array[i] = double.PositiveInfinity;
            }

            return array;
        }

        [Benchmark]
        public double[] ArrayFill() {
            var array = new double[ArrayLength];
            Array.Fill(array, double.PositiveInfinity);

            return array;
        }
    }

Reset Entity-Framework Migrations

In Entity Framework Core.

  1. Remove all files from migrations folder.

  2. Type in console

    dotnet ef database drop -f -v
    dotnet ef migrations add Initial
    dotnet ef database update
    

UPD: Do that only if you don't care about your current persisted data. If you do, use Greg Gum's answer

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to declare a structure in a header that is to be used by multiple files in c?

if this structure is to be used by some other file func.c how to do it?

When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.

The right way is putting it in an header file, and include this header file whenever needed.

shall we open a new header file and declare the structure there and include that header in the func.c?

This is the solution I like more, because it makes the code highly modular. I would code your struct as:

#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME

struct a
{ 
    int i;
    struct b
    {
        int j;
    }
};

#endif

I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").

And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.

If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:

struct a ;

Will be enough, and it decreases coupling.

or can we define the total structure in header file and include that in both source.c and func.c?

This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.

In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.

then how to declare that structure as extern in both the files. ?

I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.

shall we typedef it then how?

  • If you are using C++, don't.
  • If you are using C, you should.

The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:

struct MyStruct ; /* Forward declaration */

struct MyStruct
{
   /* etc. */
} ;

void doSomething(struct MyStruct * p) /* parameter */
{
   struct MyStruct a ; /* variable */
   /* etc */
}

While a typedef will enable you to write it without the struct keyword.

struct MyStructTag ; /* Forward declaration */

typedef struct MyStructTag
{
   /* etc. */
} MyStruct ;

void doSomething(MyStruct * p) /* parameter */
{
   MyStruct a ; /* variable */
   /* etc */
}

It is important you still keep a name for the struct. Writing:

typedef struct
{
   /* etc. */
} MyStruct ;

will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:

typedef struct MyStructTag
{
   /* etc. */
} MyStruct ;

Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)

Edit:

Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.

Edit 2018-06-01:

Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.

Indeed, the code above could well be written as:

typedef struct MyStruct
{
   /* etc. */
} MyStruct ;

IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:

// C++ explicit declaration by the user
struct MyStruct
{
   /* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;

Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.

Can't create handler inside thread which has not called Looper.prepare()

Try running you asyntask from the UI thread. I faced this issue when I wasn't doing the same!

Python: how can I check whether an object is of type datetime.date?

If you are using freezegun package in tests you may need to have more smart isinstance checks which works well with FakeDate and original Date/Datetime beeing inside with freeze_time context:

def isinstance_date(value):
    """Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
    import datetime
    if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.today().date()) == type(value):
        return True
    else:
        return False


def isinstance_datetime(value):
    """Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
    import datetime
    if isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.now()) == type(value):
        return True
    else:
        return False

and tests to verify the implementation

class TestDateUtils(TestCase):

    def setUp(self):
        self.date_orig = datetime.date(2000, 10, 10)
        self.datetime_orig = datetime.datetime(2000, 10, 10)

        with freeze_time('2001-01-01'):
            self.date_freezed = datetime.date(2002, 10, 10)
            self.datetime_freezed = datetime.datetime(2002, 10, 10)

    def test_isinstance_date(self):
        def check():
            self.assertTrue(isinstance_date(self.date_orig))
            self.assertTrue(isinstance_date(self.date_freezed))
            self.assertFalse(isinstance_date(self.datetime_orig))
            self.assertFalse(isinstance_date(self.datetime_freezed))
            self.assertFalse(isinstance_date(None))

        check()
        with freeze_time('2005-01-01'):
            check()

    def test_isinstance_datetime(self):
        def check():
            self.assertFalse(isinstance_datetime(self.date_orig))
            self.assertFalse(isinstance_datetime(self.date_freezed))
            self.assertTrue(isinstance_datetime(self.datetime_orig))
            self.assertTrue(isinstance_datetime(self.datetime_freezed))
            self.assertFalse(isinstance_datetime(None))

        check()
        with freeze_time('2005-01-01'):
            check()

Integer to hex string in C++

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

You can prepend the first << with << "0x" or whatever you like if you wish.

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;

So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

C# DLL config file

It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

echo that outputs to stderr

My suggestion:

echo "my errz" >> /proc/self/fd/2

or

echo "my errz" >> /dev/stderr

echo "my errz" > /proc/self/fd/2 will effectively output to stderr because /proc/self is a link to the current process, and /proc/self/fd holds the process opened file descriptors, and then, 0, 1, and 2 stand for stdin, stdout and stderr respectively.

The /proc/self link doesn't work on MacOS, however, /proc/self/fd/* is available on Termux on Android, but not /dev/stderr. How to detect the OS from a Bash script? can help if you need to make your script more portable by determining which variant to use.

When should I create a destructor?

It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

What online brokers offer APIs?

Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.

How to create a numeric vector of zero length in R

Simply:

x <- vector(mode="numeric", length=0)

Box shadow for bottom side only

You can do the following after adding class one-edge-shadow or use as you like.

.one-edge-shadow {
    -webkit-box-shadow: 0 8px 6px -6px black;
       -moz-box-shadow: 0 8px 6px -6px black;
            box-shadow: 0 8px 6px -6px black;
}

Source

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Can an html element have multiple ids?

No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

and then use navigation to get what you really want.

If you are just looking to apply styles, class names are better.

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

error: Libtool library used but 'LIBTOOL' is undefined

For people using Tiny Core Linux, you also need to install libtool-dev as it has the *.m4 files needed for libtoolize.

Angular CLI SASS options

The following should work in an angular CLI 6 project. I.e if you are getting:

get/set have been deprecated in favor of the config command.

npm install node-sass --save-dev

Then (making sure you change the project name)

ng config projects.YourPorjectName.schematics.@schematics/angular:component.styleext sass

To get your default project name use:

ng config defaultProject

However: If you have migrated your project from <6 up to angular 6 there is a good chance that the config wont be there. In which case you might get:

Invalid JSON character: "s" at 0:0

Therefore a manual editing of angular.json will be required.

You will want it to look something like this (taking note of the styleex property):

...
"projects": {
    "Sassy": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      }
...

Seems like an overly complex schema to me. ¯_(?)_/¯

You will now have to go and change all your css/less files to be scss and update any references in components etc, but you should be good to go.

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

No Network Security Config specified, using platform default - Android Log

I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new 
        StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Java resource as file

I had the same problem and was able to use the following:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

Characters allowed in a URL

These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.

How to get memory usage at runtime using C++?

David Robert Nadeau has put a good self contained multi-platform C function to get the process resident set size (physical memory use) in his website:

/*
 * Author:  David Robert Nadeau
 * Site:    http://NadeauSoftware.com/
 * License: Creative Commons Attribution 3.0 Unported License
 *          http://creativecommons.org/licenses/by/3.0/deed.en_US
 */

#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>

#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>

#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#include <stdio.h>

#endif

#else
#error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
#endif





/**
 * Returns the peak (maximum so far) resident set size (physical
 * memory use) measured in bytes, or zero if the value cannot be
 * determined on this OS.
 */
size_t getPeakRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.PeakWorkingSetSize;

#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
    /* AIX and Solaris ------------------------------------------ */
    struct psinfo psinfo;
    int fd = -1;
    if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 )
        return (size_t)0L;      /* Can't open? */
    if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) )
    {
        close( fd );
        return (size_t)0L;      /* Can't read? */
    }
    close( fd );
    return (size_t)(psinfo.pr_rssize * 1024L);

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
    /* BSD, Linux, and OSX -------------------------------------- */
    struct rusage rusage;
    getrusage( RUSAGE_SELF, &rusage );
#if defined(__APPLE__) && defined(__MACH__)
    return (size_t)rusage.ru_maxrss;
#else
    return (size_t)(rusage.ru_maxrss * 1024L);
#endif

#else
    /* Unknown OS ----------------------------------------------- */
    return (size_t)0L;          /* Unsupported. */
#endif
}





/**
 * Returns the current resident set size (physical memory use) measured
 * in bytes, or zero if the value cannot be determined on this OS.
 */
size_t getCurrentRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.WorkingSetSize;

#elif defined(__APPLE__) && defined(__MACH__)
    /* OSX ------------------------------------------------------ */
    struct mach_task_basic_info info;
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
    if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO,
        (task_info_t)&info, &infoCount ) != KERN_SUCCESS )
        return (size_t)0L;      /* Can't access? */
    return (size_t)info.resident_size;

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    /* Linux ---------------------------------------------------- */
    long rss = 0L;
    FILE* fp = NULL;
    if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
        return (size_t)0L;      /* Can't open? */
    if ( fscanf( fp, "%*s%ld", &rss ) != 1 )
    {
        fclose( fp );
        return (size_t)0L;      /* Can't read? */
    }
    fclose( fp );
    return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);

#else
    /* AIX, BSD, Solaris, and Unknown OS ------------------------ */
    return (size_t)0L;          /* Unsupported. */
#endif
}

Usage

size_t currentSize = getCurrentRSS( );
size_t peakSize    = getPeakRSS( );

For more discussion, check the web site, it also provides a function to get the physical memory size of a system.

How to make my font bold using css?

Sine you are new to html here are three ready to use examples on how to use CSS together with html. You can simply put them into a file, save it and open it up with the browser of your choice:

This one directly embeds your CSS style into your tags/elements. Generally this is not a very nice approach, because you should always separate the content/html from design.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
    </head>           
    <body>
        <p style="font-weight:bold;">Hi, I'm very bold!</p>
    </body>
</html> 

The next one is a more general approach and works on all "p" (stands for paragraph) tags in your document and additionaly makes them HUGE. Btw. Google uses this approach on his search:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
        <style type="text/css">
            p {
              font-weight:bold;
              font-size:26px;
            }
        </style>
    </head>   
    <body>
        <p>Hi, I'm very bold and HUGE!</p>
    </body>
</html>  

You probably will take a couple of days playing around with the first examples, however here is the last one. In this you finally fully seperate design (css) and content (html) from each other in two different files. stackoverflow takes this approach.

In one file you put all the CSS (call it 'hello_world.css'):

  p {
    font-weight:bold;
    font-size:26px;
  }

In another file you should put the html (call it 'hello_world.html'):

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
        <link rel="stylesheet" type="text/css" href="hello_world.css" />  
    </head>       
    <body>
        <p>Hi, I'm very bold and HUGE!</p>
    </body>
</html> 

Hope this helps a little. To address specific elements in your document and not all tags you should make yourself familiar with the class, id and name attributes. Have fun!

How to catch a click event on a button?

Change your onCreate to

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

for me this update worked

How to get the children of the $(this) selector?

If you need to get the first img that's down exactly one level, you can do

$(this).children("img:first")

Flexbox not giving equal width to elements

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

From the spec:

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

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

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

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

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

And here is a working example with your fiddle.

React passing parameter via onclick event using ES6 syntax

TL;DR:

Don't bind function (nor use arrow functions) inside render method. See official recommendations.

https://reactjs.org/docs/faq-functions.html


So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

Basically, you have to bind your functions in the constructor.

class Actions extends Component {

    static propTypes = {
        entity_id: PropTypes.number,
        contact_id: PropTypes.number,
        onReplace: PropTypes.func.isRequired,
        onTransfer: PropTypes.func.isRequired
    }

    constructor() {
        super();
        this.onReplace = this.onReplace.bind(this);
        this.onTransfer = this.onTransfer.bind(this);
    }

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }

    onTransfer() {
        this.props.onTransfer(this.props.entity_id, this.props.contact_id);
    }

    render() {
        return (
            <div className="actions">
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onReplace}
                    title="Replace">
                        <i className="fa fa-refresh"></i>
                </button>
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onTransfer}
                    title="Transfer">
                    <i className="fa fa-share"></i>
                </button>                                 
            </div>
        )
    }
}

export default Actions

Key lines are:

constructor

this.onReplace = this.onReplace.bind(this);

method

onReplace() {
    this.props.onReplace(this.props.entity_id, this.props.contact_id);
}

render

onClick={this.onReplace}

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Capture Video of Android's Screen

AirPlay Mirroring and Screen Recording is now in CyanogenMod with Mirror APK (Beta).

concatenate two database columns into one resultset column

If both Column are numeric Then Use This code

Just Cast Column As Varchar(Size)

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

How to convert a string with comma-delimited items to a list in Python?

split() is your friend here. I will cover a few aspects of split() that are not covered by other answers.

  • If no arguments are passed to split(), it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.

Example:

>>> "   \t\t\none  two    three\t\t\tfour\nfive\n\n".split()
['one', 'two', 'three', 'four', 'five']
  • When a single character delimiter is passed, split() behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.

Example:

>>> ",,one,two,three,,\n four\tfive".split(',')
['', '', 'one', 'two', 'three', '', '\n four\tfive']

So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:

words = [item.strip() for item in string.split(',')]
  • When a multi-character string is passed as the delimiter, it is taken as a single delimiter and not as a character class or a set of delimiters.

Example:

>>> "one,two,three,,four".split(',,')
['one,two,three', 'four']

To coalesce multiple delimiters into one, you would need to use re.split(regex, string) approach. See the related posts below.


Related

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

django change default runserver port

Create a subclass of django.core.management.commands.runserver.Command and overwrite the default_port member. Save the file as a management command of your own, e.g. under <app-name>/management/commands/runserver.py:

from django.conf import settings
from django.core.management.commands import runserver

class Command(runserver.Command):
    default_port = settings.RUNSERVER_PORT

I'm loading the default port form settings here (which in turn reads other configuration files), but you could just as well read it from some other file directly.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Button button = findViewById(R.id.button) always resolves to null in Android Studio

R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

How do you create a remote Git branch?

I've solved this by adding this into my bash ~/.profile:

function gitb() { git checkout -b $1 && git push --set-upstream origin $1; }

Then to start up a new local + remote branch, I write:

gitb feature/mynewbranch

This creates the branch and does the first push, not just to setup tracking (so that later git pull and git push work without extra arguments), but actually confirming that the target repo doesn't already have such branch in it.

AngularJS: Basic example to use authentication in Single Page Application

In angularjs you can create the UI part, service, Directives and all the part of angularjs which represent the UI. It is nice technology to work on.

As any one who new into this technology and want to authenticate the "User" then i suggest to do it with the power of c# web api. for that you can use the OAuth specification which will help you to built a strong security mechanism to authenticate the user. once you build the WebApi with OAuth you need to call that api for token:

_x000D_
_x000D_
var _login = function (loginData) {_x000D_
 _x000D_
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
 _x000D_
        var deferred = $q.defer();_x000D_
 _x000D_
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
 _x000D_
            localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
 _x000D_
            _authentication.isAuth = true;_x000D_
            _authentication.userName = loginData.userName;_x000D_
 _x000D_
            deferred.resolve(response);_x000D_
 _x000D_
        }).error(function (err, status) {_x000D_
            _logOut();_x000D_
            deferred.reject(err);_x000D_
        });_x000D_
 _x000D_
        return deferred.promise;_x000D_
 _x000D_
    };_x000D_
 
_x000D_
_x000D_
_x000D_

and once you get the token then you request the resources from angularjs with the help of Token and access the resource which kept secure in web Api with OAuth specification.

Please have a look into the below article for more help:-

http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/

What is the most efficient way to check if a value exists in a NumPy array?

How about

if value in my_array[:, col_num]:
    do_whatever

Edit: I think __contains__ is implemented in such a way that this is the same as @detly's version

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Difference between return 1, return 0, return -1 and exit?

return in function return execution back to caller and exit from function terminates the program.

in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position.

returning different values like return 1 or return -1 means that program is returning error .

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I generally install Apache + PHP + MySQL by-hand, not using any package like those you're talking about.

It's a bit more work, yes; but knowing how to install and configure your environment is great -- and useful.

The first time, you'll need maybe half a day or a day to configure those. But, at least, you'll know how to do so.

And the next times, things will be far more easy, and you'll need less time.

Else, you might want to take a look at Zend Server -- which is another package that bundles Apache + PHP + MySQL.

Or, as an alternative, don't use Windows.

If your production servers are running Linux, why not run Linux on your development machine?

And if you don't want to (or cannot) install Linux on your computer, use a Virtual Machine.

Best way to incorporate Volley (or other library) into Android Studio project

As pointed out by others as well, Volley is officially available on Github:

Add this line to your gradle dependencies for volley:

compile 'com.android.volley:volley:1.0.0'


To install volley from source read below:

I like to keep the official volley repository in my app. That way I get it from the official source and can get updates without depending on anyone else and mitigating concerns expressed by other people.

Added volley as a submodule alongside app.

git submodule add -b master https://github.com/google/volley.git volley

In my settings.gradle, added the following line to add volley as a module.

include ':volley'

In my app/build.gradle, I added a compile dependency for the volley project

compile project(':volley')

That's all! Volley can now be used in my project.

Everytime I want to sync the volley module with Google's repo, i run this.

git submodule foreach git pull

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

For easier use CI have updated this so you can just use

$this->load->helper('language');

and to translate text

lang('language line');

and if you want to warp it inside label then use optional parameter

lang('language line', 'element id');

This will output

// becomes <label for="form_item_id">language_key</label>

For good reading http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html

Running code in main thread from another thread

Follow this method. Using this way you can simply update the UI from a background thread. runOnUiThread work on the main(UI) thread . I think this code snippet is less complex and easy, especially for beginners.

AsyncTask.execute(new Runnable() {
            @Override
            public void run() {

            //code you want to run on the background
            someCode();

           //the code you want to run on main thread
 MainActivity.this.runOnUiThread(new Runnable() {

                    public void run() {

/*the code you want to run after the background operation otherwise they will executed earlier and give you an error*/
                        executeAfterOperation();

                   }
                });
            }
        });

in the case of a service

create a handler in the oncreate

 handler = new Handler();

then use it like this

 private void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

You are getting this exception because your AWS SDK is unable to load your credentials. What you should do is goto Preferences then goto AWS and add your secret key and access key. So that your project can retrieve both keys.

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

How to pass variable from jade template file to a script file?

See this question: JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

I'm having the same problem. Jade does not pass local variables in (or do any templating at all) to javascript scripts, it simply passes the entire block in as literal text. If you use the local variables 'address' and 'port' in your Jade file above the script tag they should show up.

Possible solutions are listed in the question I linked to above, but you can either: - pass every line in as unescaped text (!= at the beginning of every line), and simply put "-" before every line of javascript that uses a local variable, or: - Pass variables in through a dom element and access through JQuery (ugly)

Is there no better way? It seems the creators of Jade do not want multiline javascript support, as shown by this thread in GitHub: https://github.com/visionmedia/jade/pull/405

jQuery selector regular expressions

I'm just giving my real time example:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

$("[id^='select2-qownerName_select-result']")

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

ActionBar text color

Setting a HTML string on the action bar doesn't work on the Material theme in SDK v21+

If you want to change it you should set the primary text color in your style.xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material.Light">
        <!-- Customize your theme here. -->
        <item name="android:textColorPrimary">@color/actionbar-text-color</item>
    </style>
</resources>    

Adding two Java 8 streams, or an extra element to a stream

You can use Guava's Streams.concat(Stream<? extends T>... streams) method, which will be very short with static imports:

Stream stream = concat(stream1, stream2, of(element));

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

Getting Started Install from npm:

npm install imask And import or require:

import IMask from 'imask';

or use CDN:

var dateMask = IMask(element, {
  mask: Date,  // enable date mask

  // other options are optional
  pattern: 'Y-`m-`d',  // Pattern mask with defined blocks, default is 'd{.}`m{.}`Y'
  // you can provide your own blocks definitions, default blocks for date mask are:
  blocks: {
    d: {
      mask: IMask.MaskedRange,
      from: 1,
      to: 31,
      maxLength: 2,
    },
    m: {
      mask: IMask.MaskedRange,
      from: 1,
      to: 12,
      maxLength: 2,
    },
    Y: {
      mask: IMask.MaskedRange,
      from: 1900,
      to: 9999,
    }
  },
  // define date -> str convertion
  format: function (date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (day < 10) day = "0" + day;
    if (month < 10) month = "0" + month;

    return [year, month, day].join('-');
  },
  // define str -> date convertion
  parse: function (str) {
    var yearMonthDay = str.split('-');
    return new Date(yearMonthDay[0], yearMonthDay[1] - 1, yearMonthDay[2]);
  },

  // optional interval options
  min: new Date(2000, 0, 1),  // defaults to `1900-01-01`
  max: new Date(2020, 0, 1),  // defaults to `9999-01-01`

  autofix: true,  // defaults to `false`

  // also Pattern options can be set
  lazy: false,

  // and other common options
  overwrite: true  // defaults to `false`
});

File to byte[] in Java

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

Opacity CSS not working in IE8

Apparently alpha transparency only works on block level elements in IE 8. Set display: block.

Plotting images side by side using matplotlib

As per matplotlib's suggestion for image grids:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

Downgrade npm to an older version

Even I run npm install -g npm@4, it is not ok for me.

Finally, I download and install the old node.js version.

https://nodejs.org/download/release/v7.10.1/

It is npm version 4.

You can choose any version here https://nodejs.org/download/release/

Array to String PHP?

Yet another way, PHP var_export() with short array syntax (square brackets) indented 4 spaces:

function varExport($expression, $return = true) {
    $export = var_export($expression, true);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    
    if ((bool) $return) return $export; else echo $export;
}

Taken here.

Seaborn Barplot - Displaying Values

Hope this helps for item #2: a) You can sort by total bill then reset the index to this column b) Use palette="Blue" to use this color to scale your chart from light blue to dark blue (if dark blue to light blue then use palette="Blues_d")

import pandas as pd
import seaborn as sns
%matplotlib inline

df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',')
groupedvalues=df.groupby('day').sum().reset_index()
groupedvalues=groupedvalues.sort_values('total_bill').reset_index()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette="Blues")

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

Changing anything in build.gradle file will re-sync everything again and the error will be gone.For me i changed the minSdkVersion and it worked. Don't worry this could happen if the system crashed or Android Studio was not shut properly.

Is there a simple way to delete a list element by value?

If you know what value to delete, here's a simple way (as simple as I can think of, anyway):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

You'll get [0, 0, 2, 3, 4]

Windows equivalent of the 'tail' command

When using more +n that Matt already mentioned, to avoid pauses in long files, try this:

more +1 myfile.txt > con

When you redirect the output from more, it doesn't pause - and here you redirect to the console. You can similarly redirect to some other file like this w/o the pauses of more if that's your desired end result. Use > to redirect to file and overwrite it if it already exists, or >> to append to an existing file. (Can use either to redirect to con.)

How can I get a list of users from active directory?

If you want to filter y active accounts add this to Harvey's code:

 UserPrincipal userPrin = new UserPrincipal(context);
 userPrin.Enabled = true;

after the first using. Then add

  searcher.QueryFilter = userPrin;

before the find all. And that should get you the active ones.

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

http://jsfiddle.net/Fy8vD/3041/

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
     left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
}
.gps_ring:before {
    content:"";
    display:block;
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    left:-8px;
    top:-8px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
}
.gps_ring:after {
    content:"";
    display:block;
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    left:-18px;
    top:-18px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

How to add extra whitespace in PHP?

is this for display purposes? if so you really should consider separating your display form your logic and use style sheets for formatting. being server side php should really allow providing and accepting data. while you could surely use php to do what you are asking I am a very firm believer in keeping display and logic with as much separation as possible. with styles you can do all of your typesetting.

give output class wrappers and style accordingly.

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

Angular js init ng-model from default values

If you like Kevin Stone's approach above https://stackoverflow.com/a/17823590/584761 consider an easier approach by writing directives for specific tags such as 'input'.

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
            }
        }
    }; });

If you go this route you won't have to worry about adding ng-initial to every tag. It automatically sets the value of the model to the tag's value attribute. If you do not set the value attribute it will default to an empty string.

Read Variable from Web.Config

I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.

However you can read web.config using System.Configuration.ConfigurationManager.AppSettings

What is the recommended project structure for spring boot rest projects?

Use Link-1 to generate a project. this a basic project for learning. you can understand the folder structure. Use Link-2 for creating a basic Spring boot project. 1: http://start.spring.io/ 2: https://projects.spring.io/spring-boot/

Create a gradle/maven project Automatically src/main/java and src/main/test will be created. create controller/service/Repository package and start writing the code.

-src/main/java(source folder) ---com.package.service(package) ---ServiceClass(Class) ---com.package.controller(package) ---ControllerClass(Class)

Jquery: Find Text and replace

More specific:

$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));

Post Build exited with code 1

Yet another answer ...

In my case I had a Visual Studio 2017 project targeting both .Net Standard 1.3 and .Net Framework 2.0. This was specified in the .csproj file like this:

<TargetFrameworks>netstandard1.3;net20</TargetFrameworks>

I also had a post-build event command line like this:

copy "E:\Yacks\YacksCore\YacksCore\bin\net20\Merlinia.YacksCore.dll" "E:\Merlinia\Trunk-Debug\Shared Bin\"

In other words I was trying to copy the .Net Framework .dll produced by the build to an alternative location.

This was failing with this error when I did a Rebuild:

MSB3073 The command "copy "E:\Yacks\YacksCore\YacksCore\bin\net20\Merlinia.YacksCore.dll" "E:\Merlinia\Trunk-Debug\Shared Bin\"" exited with code 1.

After much frustration I finally determined that what was happening was that Rebuild deleted all of the output files, then did the build for .Net Standard 1.3, then tried to run the post-build event command line, which failed because the file to be copied wasn't built yet.

So the solution was to change the order of building, i.e., build for .Net Framework 2.0 first, then for .Net Standard 1.3.

<TargetFrameworks>net20;netstandard1.3</TargetFrameworks>

This now works, with the minor glitch that the post-build event command line is being run twice, so the file is copied twice.

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

Make DateTimePicker work as TimePicker only in WinForms

The best way to do this is this:

datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;

How to install mechanize for Python 2.7?

sudo pip-2.7 install mechanize

Using Razor within JavaScript

I prefer "<!--" "-->" like a "text>"

<script type="text/javascript">
//some javascript here     

@foreach (var item in itens)
{                 
<!--  
   var title = @(item.name)
    ...
-->

</script>

CakePHP 3.0 installation: intl extension missing from system

If you are using latest version Ubuntu 16.04 or later just do

sudo apt-get install php-intl

Then restart your apache

sudo service apache2 restart

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

See http://api.jquery.com/on/

So instead of...

$(".myclass").click( function() {
    // do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
    // do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

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

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

This also works with the for and the switch loops.

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

How to render an ASP.NET MVC view as a string?

To render a view to a string in the Service Layer without having to pass ControllerContext around, there is a good Rick Strahl article here http://www.codemag.com/Article/1312081 that creates a generic controller. Code summary below:

// Some Static Class
public static string RenderViewToString(ControllerContext context, string viewPath, object model = null, bool partial = false)
{
    // first find the ViewEngine for this view
    ViewEngineResult viewEngineResult = null;
    if (partial)
        viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
    else
        viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

    if (viewEngineResult == null)
        throw new FileNotFoundException("View cannot be found.");

    // get the view and attach the model to view data
    var view = viewEngineResult.View;
    context.Controller.ViewData.Model = model;

    string result = null;

    using (var sw = new StringWriter())
    {
        var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
        view.Render(ctx, sw);
        result = sw.ToString();
    }

    return result;
}

// In the Service Class
public class GenericController : Controller
{ }

public static T CreateController<T>(RouteData routeData = null) where T : Controller, new()
{
    // create a disconnected controller instance
    T controller = new T();

    // get context wrapper from HttpContext if available
    HttpContextBase wrapper;
    if (System.Web.HttpContext.Current != null)
        wrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
    else
        throw new InvalidOperationException("Cannot create Controller Context if no active HttpContext instance is available.");

    if (routeData == null)
        routeData = new RouteData();

    // add the controller routing if not existing
    if (!routeData.Values.ContainsKey("controller") &&
        !routeData.Values.ContainsKey("Controller"))
        routeData.Values.Add("controller", controller.GetType().Name.ToLower().Replace("controller", ""));

    controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
    return controller;
}

Then to render the View in the Service class:

var stringView = RenderViewToString(CreateController<GenericController>().ControllerContext, "~/Path/To/View/Location/_viewName.cshtml", theViewModel, true);

Associative arrays in Shell scripts

Another non-bash 4 way.

#!/bin/bash

# A pretend Python dictionary with bash 3 
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY=${animal%%:*}
    VALUE=${animal#*:}
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

echo -e "${ARRAY[1]%%:*} is an extinct animal which likes to ${ARRAY[1]#*:}\n"

You could throw an if statement for searching in there as well. if [[ $var =~ /blah/ ]]. or whatever.

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

How to convert Seconds to HH:MM:SS using T-SQL

If your time amount exceeds 24 hours it won't be handled correctly with the DATEADD and CONVERT methods.

SELECT CONVERT(varchar, DATEADD(ms, 24*60*60 * 1000, 0), 114)
00:00:00:000

The following function will handle times exceeding 24 hours (~max 35,791,394 hours).

create function [dbo].[ConvertTimeToHHMMSS]
(
    @time decimal(28,3), 
    @unit varchar(20)
)
returns varchar(20)
as
begin

    declare @seconds decimal(18,3), @minutes int, @hours int;

    if(@unit = 'hour' or @unit = 'hh' )
        set @seconds = @time * 60 * 60;
    else if(@unit = 'minute' or @unit = 'mi' or @unit = 'n')
        set @seconds = @time * 60;
    else if(@unit = 'second' or @unit = 'ss' or @unit = 's')
        set @seconds = @time;
    else set @seconds = 0; -- unknown time units

    set @hours = convert(int, @seconds /60 / 60);
    set @minutes = convert(int, (@seconds / 60) - (@hours * 60 ));
    set @seconds = @seconds % 60;

    return 
        convert(varchar(9), convert(int, @hours)) + ':' +
        right('00' + convert(varchar(2), convert(int, @minutes)), 2) + ':' +
        right('00' + convert(varchar(6), @seconds), 6)

end

Usage:

select dbo.ConvertTimeToHHMMSS(123, 's')
select dbo.ConvertTimeToHHMMSS(96.999, 'mi')
select dbo.ConvertTimeToHHMMSS(35791394.999, 'hh')
0:02:03.000
1:36:59.940
35791394:59:56.400

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

SQL Switch/Case in 'where' clause

The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.

You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as

WHERE account_location = CASE @locationType
                              WHEN 'business' THEN 45
                              WHEN 'area' THEN 52
                         END

so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.

jQuery slide left and show

Don't forget the padding and margins...

jQuery.fn.slideLeftHide = function(speed, callback) { 
  this.animate({ 
    width: "hide", 
    paddingLeft: "hide", 
    paddingRight: "hide", 
    marginLeft: "hide", 
    marginRight: "hide" 
  }, speed, callback);
}

jQuery.fn.slideLeftShow = function(speed, callback) { 
  this.animate({ 
    width: "show", 
    paddingLeft: "show", 
    paddingRight: "show", 
    marginLeft: "show", 
    marginRight: "show" 
  }, speed, callback);
}

With the speed/callback arguments added, it's a complete drop-in replacement for slideUp() and slideDown().

How can I configure Logback to log different levels for a logger to different destinations?

<configuration scan="true" scanPeriod="60 seconds">
 <appender name="A1" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/${logfile.name}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/${logfile.name}.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>100MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} %c{1} [%p] %m%n</pattern>
    </encoder>
 </appender>

 <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/access.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/access.log.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>100MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} %c{1} [%p] %m%n</pattern>
    </encoder>
  </appender>

  <appender name="METRICS" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/metrics.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/logs/metrics.log.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>2MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d %-8r %m%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="A1"/>
  </root>

  <logger name="backtype.storm.security.auth.authorizer" additivity="false">
    <level value="INFO" />
    <appender-ref ref="ACCESS" />
  </logger>

  <logger name="backtype.storm.metric.LoggingMetricsConsumer" additivity="false" >
    <level value="INFO"/>
    <appender-ref ref="METRICS"/>
  </logger>

</configuration>

So here is the logback file in which I am not printing backtype.storm.metric.LoggingMetricsConsumer info level if i say additivity = "true" then for for all classes in backtype.* this rule will be applied

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
    
 2)  &gt; (>)
    
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

How to check for registry value using VbScript

Try this. This script gets current logged in user's name & home directory:

On Error Resume Next

Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp) 

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp) 

How do I vertically center an H1 in a div?

Just use padding top and bottom, it will automatically center the content vertically.

Returning a boolean value in a JavaScript function

An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:

function validatePassword() {
   const password = document.getElementById("password");
   const confirm_password = document.getElementById("password_confirm");

   if (password.value.length === 0) {
      return false;
   }

   if (password.value !== confirm_password.value) {
      return false;
   }
  
   return true;
}

Laravel Eloquent: Ordering results of all()

Note, you can do:

$results = Project::select('name')->orderBy('name')->get();

This generate a query like:

"SELECT name FROM proyect ORDER BY 'name' ASC"

In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:

$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();

Now is php who order the result.

Exception 'open failed: EACCES (Permission denied)' on Android

after adding permission solved my problem

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

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

Try to edit your project build.gradle file and set the android build gradle plugin to classpath 'com.android.tools.build:gradle:3.2.1' within the dependency section.

Get string between two strings in a string

var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

This returns only the value(s) between "key :" and the following occurance of "-"

Difference between static STATIC_URL and STATIC_ROOT on Django

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>

How to copy file from one location to another location?

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you're not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.