Programs & Examples On #Mcrypt

MCrypt, and the accompanying libmcrypt, are intended to be replacements for the old Unix crypt, except that they are under the GPL and support an ever-wider range of algorithms and modes. MCrypt has not been updated since 2007

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

Installing mcrypt extension for PHP on OSX Mountain Lion

Solution with brew worked only after the following: in your php.ini

nano /private/etc/php.ini

add this line:

extension="/usr/local/Cellar/php53-mcrypt/5.3.26/mcrypt.so"

Warning! Set the correct PHP version.

Laravel requires the Mcrypt PHP extension

in ubuntu 14.04 based on your php version : 5.6,7.0,7.1,7.2,7.3

sudo apt-get install php{version}-mcrypt

sudo apt-get install php7.1-mcrypt

sudo phpenmod mcrypt 

Fatal error: Call to undefined function mcrypt_encrypt()

For windows

;extension=php_mcrypt.dll to extension=php_mcrypt.dll 
 then restart your apache server

For Redhat

sudo yum install php55-mcrypt //if php5.5
sudo yum install php-mcrypt //if less than 5.4
sudo service httpd restart //if apache 2.4
sudo /etc/init.d/httpd restart //if apache 2.2 or less

For Ubuntu

sudo apt-get install php5-mcrypt
sudo service apache2 restart //if server not reloaded automatically 

Still not working?

sudo php5enmod mcrypt && sudo service apache2 restart

Best way to use PHP to encrypt and decrypt passwords?

This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.

If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.

Issue in installing php7.2-mcrypt

sudo apt-get install php-pear php7.x-dev

x is your php version like 7.2 the php7.2-dev

apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1 

then add "extension=mcrypt.so" in "/etc/php/7.2/apache2/php.ini"

here php.ini is depends on your php installatio and apache used php version.

How To Add An "a href" Link To A "div"?

Your solutions don't seem to be working for me, I have the following code. How to put link into the last two divs.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">

<style>
/* Import */
@import url(https://fonts.googleapis.com/css?family=Quicksand:300,400);
* {
  font-family: "Quicksand", sans-serif; 
  font-weight: bold; 
  text-align: center;  
  text-transform: uppercase; 
  -webkit-transition: all 0.25s ease; 
  -moz-transition: all 0.25s ease; 
  -ms-transition: all 0.25s ease; 
  -o-transition: all 0.025s ease; 
}

/* Colors */

#ora {
  background-color: #e67e22; 
}

#red {
  background-color: #e74c3c; 
}

#orab {
  background-color: white; 
  border: 5px solid #e67e22; 
}

#redb {
  background-color: white; 
  border: 5px solid #e74c3c; 
}
/* End of Colors */

.B {
  width: 240px; 
  height: 55px; 
  margin: auto; 
  line-height: 45px; 
  display: inline-block; 
  box-sizing: border-box; 
  -webkit-box-sizing: border-box; 
  -moz-box-sizing: border-box; 
  -ms-box-sizing: border-box; 
  -o-box-sizing: border-box; 
} 

#orab:hover {
  background-color: #e67e22; 
}

#redb:hover {
  background-color: #e74c3c; 
}
#whib:hover {
  background-color: #ecf0f1; 
}

/* End of Border

.invert:hover {
  -webkit-filter: invert(1);
  -moz-filter: invert(1);
  -ms-filter: invert(1);
  -o-filter: invert(1);
}
</style>
<h1>Flat and Modern Buttons</h1>
<h2>Border Stylin'</h2> 

<div class="B bo" id="orab">See the movies list</div></a>
<div class="B bo" id="redb">Avail a free rental day</div>

</html>

How to correct TypeError: Unicode-objects must be encoded before hashing?

It is probably looking for a character encoding from wordlistfile.

wordlistfile = open(wordlist,"r",encoding='utf-8')

Or, if you're working on a line-by-line basis:

line.encode('utf-8')

EDIT

Per the comment below and this answer.

My answer above assumes that the desired output is a str from the wordlist file. If you are comfortable in working in bytes, then you're better off using open(wordlist, "rb"). But it is important to remember that your hashfile should NOT use rb if you are comparing it to the output of hexdigest. hashlib.md5(value).hashdigest() outputs a str and that cannot be directly compared with a bytes object: 'abc' != b'abc'. (There's a lot more to this topic, but I don't have the time ATM).

It should also be noted that this line:

line.replace("\n", "")

Should probably be

line.strip()

That will work for both bytes and str's. But if you decide to simply convert to bytes, then you can change the line to:

line.replace(b"\n", b"")

remove all special characters in java

Your problem is that the indices returned by match.start() correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c every time, these indices become incorrect.

The best approach to solve this is to use replaceAll, for example:

        System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));

How to get a list of column names

Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.

It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)

https://github.com/maghead/sqlite-parser

/etc/apt/sources.list" E212: Can't open file for writing

for me worked changing the filesystem from Read-Only before running vim:

bash-3.2# mount -o remount rw /

VBA collection: list of keys

You can snoop around in your memory using RTLMoveMemory and retrieve the desired information directly from there:

32-Bit:

Option Explicit

'Provide direct memory access:
Public Declare Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
    ByVal Destination As Long, _
    ByVal Source As Long, _
    ByVal Length As Long)


Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As Long
    Dim KeyPtr As Long
    Dim ItemPtr As Long

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 16)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLong(CollPtr + 24)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLong(ItemPtr + 16)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLong(ItemPtr + 24)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given MemoryAddress
Public Function PeekLong(Address As Long) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4&)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As Long) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, Length)

End Function

64-Bit:

Option Explicit

'Provide direct memory access:
Public Declare PtrSafe Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
     ByVal Destination As LongPtr, _
     ByVal Source As LongPtr, _
     ByVal Length As LongPtr)



Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As LongPtr
    Dim KeyPtr As LongPtr
    Dim ItemPtr As LongPtr

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 28)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLongLong(CollPtr + 40)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLongLong(ItemPtr + 24)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLongLong(ItemPtr + 40)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given Memory-Address
Public Function PeekLong(Address As LongPtr) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4^)

End Function

'Peek LongLong from given Memory Address
Public Function PeekLongLong(Address As LongPtr) As LongLong

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLongLong), Address, 8^)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As LongPtr) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, CLngLng(Length))

End Function

Convert char to int in C#

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

Find closing HTML tag in Sublime Text

It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag

Shortcut (Mac): Shift + Command + A

Shortcut (Windows): Control + Alt + A

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I also had the same problem, as a quick workaround, I used blend to determine how much padding was being added. In my case it was 12, so I used a negative margin to get rid of it. Now everything can now be centered properly

CSS: fixed position on x-axis but not y?

Its a simple technique using the script also. You can check a demo here too.

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

Update Credit: @PierredeLESPINAY

As commented, to make the script support the changes in the css without having to recode them in the script. You can use the following.

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

Demo :)

log4j configuration via JVM argument(s)?

This seems to have changed (probably with log4j2) to:

-Dlog4j.configurationFile=file:C:\Users\me\log4j.xml

See: https://logging.apache.org/log4j/2.x/manual/configuration.html

OperationalError, no such column. Django

As you went through the tutorial you must have come across the section on migration, as this was one of the major changes in Django 1.7

Prior to Django 1.7, the syncdb command never made any change that had a chance to destroy data currently in the database. This meant that if you did syncdb for a model, then added a new row to the model (a new column, effectively), syncdb would not affect that change in the database.

So either you dropped that table by hand and then ran syncdb again (to recreate it from scratch, losing any data), or you manually entered the correct statements at the database to add only that column.

Then a project came along called south which implemented migrations. This meant that there was a way to migrate forward (and reverse, undo) any changes to the database and preserve the integrity of data.

In Django 1.7, the functionality of south was integrated directly into Django. When working with migrations, the process is a bit different.

  1. Make changes to models.py (as normal).
  2. Create a migration. This generates code to go from the current state to the next state of your model. This is done with the makemigrations command. This command is smart enough to detect what has changed and will create a script to effect that change to your database.
  3. Next, you apply that migration with migrate. This command applies all migrations in order.

So your normal syncdb is now a two-step process, python manage.py makemigrations followed by python manage.py migrate.

Now, on to your specific problem:

class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name='snippets')
    highlighted = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                            default='python',
                                            max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                                     default='friendly',
                                     max_length=100)

In this model, you have two fields highlighted and code that is required (they cannot be null).

Had you added these fields from the start, there wouldn't be a problem because the table has no existing rows?

However, if the table has already been created and you add a field that cannot be null, you have to define a default value to provide for any existing rows - otherwise, the database will not accept your changes because they would violate the data integrity constraints.

This is what the command is prompting you about. You can tell Django to apply a default during migration, or you can give it a "blank" default highlighted = models.TextField(default='') in the model itself.

How do I encode and decode a base64 string?

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

How to atomically delete keys matching a pattern using Redis

I think what might help you is the MULTI/EXEC/DISCARD. While not 100% equivalent of transactions, you should be able to isolate the deletes from other updates.

HashMap to return default value for non-found keys?

I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:

public static String getString( final JSONObject response, 
                                final String key ) 
{ return getString( response, key, "" ); }  
public static String getString( final JSONObject response, 
                                final String key, final String defVal ) 
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }

public static long getLong( final JSONObject response, 
                            final String key ) 
{ return getLong( response, key, 0 ); } 
public static long getLong( final JSONObject response, 
                            final String key, final long defVal ) 
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }

public static float getFloat( final JSONObject response, 
                              final String key ) 
{ return getFloat( response, key, 0.0f ); } 
public static float getFloat( final JSONObject response, 
                              final String key, final float defVal ) 
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }

public static List<JSONObject> getList( final JSONObject response, 
                                        final String key ) 
{ return getList( response, key, new ArrayList<JSONObject>() ); }   
public static List<JSONObject> getList( final JSONObject response, 
                                        final String key, final List<JSONObject> defVal ) { 
    try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
    catch( ClassCastException e ) { return defVal; }
}   

Make body have 100% of the browser height

Here Update

html
  {
    height:100%;
  }

body{
     min-height: 100%;
     position:absolute;
     margin:0;
     padding:0; 
}

Factorial in numpy and scipy

The answer for Ashwini is great, in pointing out that scipy.math.factorial, numpy.math.factorial, math.factorial are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial is different. The one from scipy can take np.ndarray as an input, while the others can't.

In [12]: import scipy.special

In [13]: temp = np.arange(10) # temp is an np.ndarray

In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)

TypeError: only length-1 arrays can be converted to Python scalars

In [15]: scipy.special.factorial(temp) # This works!
Out[15]: 
array([  1.00000000e+00,   1.00000000e+00,   2.00000000e+00,
         6.00000000e+00,   2.40000000e+01,   1.20000000e+02,
         7.20000000e+02,   5.04000000e+03,   4.03200000e+04,
         3.62880000e+05])

So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

Where is SQL Server Management Studio 2012?

On the Official SQL Server 2012 ISO that's for download, just navigate to \x64\Setup\ (or \x86\Setup) and you will find "sql_ssms.msi". It's only about 60 MB, and since it's an .MSI you can probably provision it to be installed automatically (say for a large lab or classroom environment).

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Before you apply the suggested solution, you can check what is the Unicode character that appeared in your file (and in the error log), in this case 0x90: https://unicodelookup.com/#0x90/1 (or directly at Unicode Consortium site http://www.unicode.org/charts/ by searching 0x0090)

and then consider removing it from the file.

How do I bottom-align grid elements in bootstrap fluid layout

Please note: for Bootstrap 4+ users, please consider Christophe's solution (Bootstrap 4 introduced flexbox, which provides for a more elegant CSS-only solution). The following will work for earlier versions of Bootstrap...


See http://jsfiddle.net/jhfrench/bAHfj/ for a working solution.

//for each element that is classed as 'pull-down', set its margin-top to the difference between its own height and the height of its parent
$('.pull-down').each(function() {
  var $this = $(this);
  $this.css('margin-top', $this.parent().height() - $this.height())
});

On the plus side:

  • in the spirit of Bootstrap's existing helper classes, I named the class pull-down.
  • only the element that is getting "pulled down" needs to be classed, so...
  • ...it's reusable for different element types (div, span, section, p, etc)
  • it's fairly-well supported (all the major browsers support margin-top)

Now the bad news:

  • it requires jQuery
  • it's not, as-written, responsive (sorry)

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).

Oracle SQL: Update a table with data from another table

Try this:

MERGE INTO table1 t1
USING
(
-- For more complicated queries you can use WITH clause here
SELECT * FROM table2
)t2
ON(t1.id = t2.id)
WHEN MATCHED THEN UPDATE SET
t1.name = t2.name,
t1.desc = t2.desc;

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

How to create a GUID/UUID using iOS

In Swift 3.0

var uuid = UUID().uuidString

How do you declare an object array in Java?

This is the correct way:

You should declare the length of the array after "="

Veicle[] cars = new Veicle[N];

How to prevent a click on a '#' link from jumping to top of page?

I have used:

<a href="javascript://nop/" class="someClass">Text</a>

How to remove non-alphanumeric characters?

You can split the string into characters and filter it.

<?php 

function filter_alphanum($string) {
    $characters = str_split($string);
    $alphaNumeric = array_filter($characters,"ctype_alnum");
    return join($alphaNumeric);
}

$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123

?>

How to recursively find the latest modified file in a directory?

This seems to work fine, even with subdirectories:

find . -type f | xargs ls -ltr | tail -n 1

In case of too many files, refine the find.

How to pass objects to functions in C++?

Do I need to pass pointers, references, or non-pointer and non-reference values?

This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.

The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &, is needed.

For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *.

List of enum values in java

Yes it is definitely possible, but you will have to do

List<MyEnum> al = new ArrayList<MyEnum>();

You can then add elements to al: al.add(ONE) or al.add(TWO).

JavaScript: replace last occurrence of text in a string

Couldn't you just reverse the string and replace only the first occurrence of the reversed search pattern? I'm thinking . . .

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         var reversedHaystack = str.split('').reverse().join('');
         var reversedNeedle = list[i].split('').reverse().join('');

         reversedHaystack = reversedHaystack.replace(reversedNeedle, 'hsinif');
         str = reversedHaystack.split('').reverse().join('');
     }
 }

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

Can lambda functions be templated?

I am aware that this question is about C++11. However, for those who googled and landed on this page, templated lambdas are now supported in C++14 and go by the name Generic Lambdas.

[info] Most of the popular compilers support this feature now. Microsoft Visual Studio 2015 supports. Clang supports. GCC supports.

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
{
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
    {
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
        {
            dirSearch.Filter = getGroupsFilterForDn;
            dirSearch.PropertiesToLoad.Add("name");

            using (var results = dirSearch.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    if (result.Properties.Contains("name"))
                        groups.Add((string)result.Properties["name"][0]);
                }
            }
        }
    }

    return groups;
}

What is the difference between the dot (.) operator and -> in C++?

Note that the -> operator cannot be used for certain things, for instance, accessing operator[].

#include <vector>

int main()
{
   std::vector<int> iVec;
   iVec.push_back(42);
   std::vector<int>* iVecPtr = &iVec;

   //int i = iVecPtr->[0]; // Does not compile
   int i = (*iVecPtr)[0]; // Compiles.
}

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Using reCAPTCHA on localhost

The way that worked for me, was to use my external IP Address.

If you don't know what it is, just google What's My IP

Then use your IP address and set this in your domains for the captcha and it should start working ok.

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

How to get ERD diagram for an existing database?

Perhaps have a look at AquaFold's Aqua Data Studio. It is a database IDE with entity-relationship diagramming. It also includes data profiling. It is not free but its price is very reasonable considering its capabilities.

Deleting a local branch with Git

This worked for me...
I have removed the folders there in .git/worktrees folder and then tried "git delete -D branch-name".

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

In my case, I passed an async lambda to Console.CancelKeyPress, which won't work.

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

How to find the Center Coordinate of Rectangle?

Center x = x + 1/2 of width

Center y = y + 1/2 of height 

If you know the width and height already then you only need one set of coordinates.

UDP vs TCP, how much faster is it?

I will just make things clear. TCP/UDP are two cars are that being driven on the road. suppose that traffic signs & obstacles are Errors TCP cares for traffic signs, respects everything around. Slow driving because something may happen to the car. While UDP just drives off, full speed no respect to street signs. Nothing, a mad driver. UDP doesn't have error recovery, If there's an obstacle, it will just collide with it then continue. While TCP makes sure that all packets are sent & received perfectly, No errors , so , the car just passes obstacles without colliding. I hope this is a good example for you to understand, Why UDP is preferred in gaming. Gaming needs speed. TCP is preffered in downloads, or downloaded files may be corrupted.

Certificate is trusted by PC but not by Android

Adding this here as it might help someone. I was having problems with Android showing the popup and invalid certificate error.

We have a Comodo Extended Validation certificate and we received the zip file that contained 4 files:

  • AddTrustExternalCARoot.crt
  • COMODORSAAddTrustCA.crt
  • COMODORSAExtendedValidationSecureServerCA.crt
  • www_mydomain_com.crt

I concatenated them together all on one line like so:

cat www_mydomain_com.crt COMODORSAExtendedValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt >www.mydomain.com.ev-ssl-bundle.crt

Then I used that bundle file as my ssl_certificate_key in nginx. That's it, works now.

Inspired by this gist: https://gist.github.com/ipedrazas/6d6c31144636d586dcc3

Creating default object from empty value in PHP?

I had a similar problem while trying to add a variable to an object returned from an API. I was iterating through the data with a foreach loop.

foreach ( $results as $data ) {
    $data->direction = 0;
}

This threw the "Creating default object from empty value" Exception in Laravel.

I fixed it with a very small change.

foreach ( $results as &$data ) {
    $data->direction = 0;
}

By simply making $data a reference.

I hope that helps somebody a it was annoying the hell out of me!

Convert UTC dates to local time in PHP

I store date in the DB in UTC format but then I show them to the final user in their local timezone

// retrieve
$d = (new \DateTime($val . ' UTC'))->format('U');
return date("Y-m-d H:i:s", $d);

Java: How to convert String[] to List or Set

Collections.addAll provides the shortest (one-line) receipt

Having

String[] array = {"foo", "bar", "baz"}; 
Set<String> set = new HashSet<>();

You can do as below

Collections.addAll(set, array); 

Changing the "tick frequency" on x or y axis in matplotlib?

In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.

ax.set_xticks(ax.get_xticks()[::2])

Android SDK Manager Not Installing Components

In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).

So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"

MySQL SELECT DISTINCT multiple columns

can this help?

select 
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d

How to query SOLR for empty fields?

One caveat! If you want to compose this via OR or AND you cannot use it in this form:

-myfield:*

but you must use

(*:* NOT myfield:*)

This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!

Checking if a variable is defined?

Leaving an incredibly simple example in case it helps.

When variable doesn't exist:

if defined? a then "hi" end
# => nil

When variable does exist:

a = 2
if defined? a then "hi" end
# => "hi"

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

Youtube iframe wmode issue

Adding ?wmode=opaque to the URL seems to solve this problem for me, although I have not tested it in IE yet.

For those of you having troubles with the previously proposed solution, note that an inital ampersand will only work if you are already supplying other arguments to the URL. The first argument must have an initial question mark: http://www.example.com?first=foo&second=bar

How do I put my website's logo to be the icon image in browser tabs?

It is called 'favicon' and you need to add below code to the header section of your website.

Simply add this to the <head> section.

<link rel="icon" href="/your_path_to_image/favicon.jpg">

Spring - @Transactional - What happens in background?

It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.

For example, you have a class that looks like this

@Component("mySubordinate")
public class CoreBusinessSubordinate {

    public void doSomethingBig() {
        System.out.println("I did something small");
    }

    public void doSomethingSmall(int x){
        System.out.println("I also do something small but with an int");    
  }
}

and you have an aspect, that looks like this:

@Component
@Aspect
public class CrossCuttingConcern {

    @Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
    public void doCrossCutStuff(){
        System.out.println("Doing the cross cutting concern now");
    }
}

When you execute it like this:

 @Service
public class CoreBusinessKickOff {

    @Autowired
    CoreBusinessSubordinate subordinate;

    // getter/setters

    public void kickOff() {
       System.out.println("I do something big");
       subordinate.doSomethingBig();
       subordinate.doSomethingSmall(4);
   }

}

Results of calling kickOff above given code above.

I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int

but when you change your code to

@Component("mySubordinate")
public class CoreBusinessSubordinate {

    public void doSomethingBig() {
        System.out.println("I did something small");
        doSomethingSmall(4);
    }

    public void doSomethingSmall(int x){
       System.out.println("I also do something small but with an int");    
   }
}


public void kickOff() {
  System.out.println("I do something big");
   subordinate.doSomethingBig();
   //subordinate.doSomethingSmall(4);
}

You see, the method internally calls another method so it won't be intercepted and the output would look like this:

I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int

You can by-pass this by doing that

public void doSomethingBig() {
    System.out.println("I did something small");
    //doSomethingSmall(4);
    ((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}

Code snippets taken from: https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

Python Pandas - Find difference between two data frames

Using the lambda function you can filter the rows with _merge value “left_only” to get all the rows in df1 which are missing from df2

df3 = df1.merge(df2, how = 'outer' ,indicator=True).loc[lambda x :x['_merge']=='left_only']
df

Converting byte array to string in javascript

I think this would be more efficient:

function toBinString (arr) {
    var uarr = new Uint8Array(arr.map(function(x){return parseInt(x,2)}));
    var strings = [], chunksize = 0xffff;
    // There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
    for (var i=0; i*chunksize < uarr.length; i++){
        strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
    }
    return strings.join('');
}

linq where list contains any in list

Sounds like you want:

var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());

Call Class Method From Another Class

You can call a function from within a class with:

A().method1()

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How do you round UP a number in Python?

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20

How can I use the HTML5 canvas element in IE?

You can try fxCanvas: https://code.google.com/p/fxcanvas/

It implements almost all Canvas API within flash shim.

How to create a String with carriage returns?

Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

How to convert a String into an ArrayList?

 String s1="[a,b,c,d]";
 String replace = s1.replace("[","");
 System.out.println(replace);
 String replace1 = replace.replace("]","");
 System.out.println(replace1);
 List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
 System.out.println(myList.toString());

can not find module "@angular/material"

That's what solved this problem for me.

I used:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

but INSIDE THE APPLICATION'S FOLDER.

Source: https://medium.com/@ismapro/first-steps-with-angular-cli-and-angular-material-5a90406e9a4

How to set cookies in laravel 5 independently inside controller

If you want to set cookie and get it outside of request, Laravel is not your friend.

Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.

I want to delete all bin and obj folders to force all projects to rebuild everything

Considering the PS1 file is present in the currentFolder (the folder within which you need to delete bin and obj folders)

$currentPath = $MyInvocation.MyCommand.Path
$currentFolder = Split-Path $currentPath

Get-ChildItem $currentFolder -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }

Unique random string generation

I am surprised why there is not a CrytpoGraphic solution in place. GUID is unique but not cryptographically safe. See this Dotnet Fiddle.

var bytes = new byte[40]; // byte size
using (var crypto = new RNGCryptoServiceProvider())
  crypto.GetBytes(bytes);

var base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

In case you want to Prepend with a Guid:

var result = Guid.NewGuid().ToString("N") + base64;
Console.WriteLine(result);

A cleaner alphanumeric string:

result = Regex.Replace(result,"[^A-Za-z0-9]","");
Console.WriteLine(result);

Better way to cast object to int

Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.

So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.

Instead another simple way, but really performance costing is to cast before in dynamic.

(int)(dynamic)myObject.

You can try it in the Interactive window of VS.

public class Test
{
  public static implicit operator int(Test v)
  {
    return 12;
  }
}

(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass

Count number of rows within each group

A solution using sqldf package:

library(sqldf)
sqldf("SELECT Year, Month, COUNT(*) as Freq
       FROM df1
       GROUP BY Year, Month")

Call a python function from jinja2

If you are doing it with Django, you can just pass the function with the context:

context = {
    'title':'My title',
    'str': str,
}
...
return render(request, 'index.html', context)

Now you will be able to use the str function in jinja2 template

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

SpringApplication.run main method

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

Application.java

@SpringBootApplication
public class Application {

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

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

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

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

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

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

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

Selecting multiple items in ListView

It's very simple,

listViewRequests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    **AppCompatCheckedTextView checkBox = (AppCompatCheckedTextView) view;**
                    Log.i("CHECK",checkBox.isChecked()+""+checkBox.getText().toString());**

               }
            });

How do I get a list of all the duplicate items using pandas in python?

With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])

In [3]: df
Out[3]: 
       0
    0  a
    1  b
    2  c
    3  d
    4  a
    5  b

In [4]: df[df.duplicated(keep=False)]
Out[4]: 
       0
    0  a
    1  b
    4  a
    5  b

How does python numpy.where() work?

Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.

so:

>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
       65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
       82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
       99]),)
>>> np.where(a == 90)
(array([90]),)

a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
       94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040

I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

New Answer It seems that the person was asking something more fundamental.

The question was how could YOU implement something that allows a function (such as where) to know what was requested.

First note that calling any of the comparison operators do an interesting thing.

a > 1000
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True`,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)`

This is done by overloading the "__gt__" method. For instance:

>>> class demo(object):
    def __gt__(self, item):
        print item


>>> a = demo()
>>> a > 4
4

As you can see, "a > 4" was valid code.

You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html

Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!

How do I empty an array in JavaScript?

A.splice(0);

I just did this on some code I am working on. It cleared the array.

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

Add string in a certain position in Python

If you want many inserts

from rope.base.codeanalyze import ChangeCollector

c = ChangeCollector(code)
c.add_change(5, 5, '<span style="background-color:#339999;">')
c.add_change(10, 10, '</span>')
rend_code = c.get_changed()

Javascript: Load an Image from url and display

First, I strongly suggest to use a Library or Framework to do your Javascript. But just for something very very simple, or for the fun to learn, it is ok. (you can use jquery, underscore, knockoutjs, angular)

Second, it is not advised to bind directly to onclick, my first suggestion goes in that way too.

That's said What you need is to modify the src of a img in your page.

In the place where you want your image displayed, you should insert a img tag like this:

Next, you need to modify the onclick to update the src attribute. The easiest way I can think of is like his

onclick=""document.getElementById('image-placeholder').src = 'http://webpage.com/images/' + document.getElementById('imagename').value + '.png"

Then again, it is not the best way to do it, but it is a start. I recommend you to try jQuery and see how can you accomplish the same whitout using onclick (tip... check the section on jquery about events)

I did a simple fiddle as a example of your poblem using some google logos... type 4 o 3 in the box and you'll two images of different size. (sorry.. I have no time to search for better images as example)

http://jsfiddle.net/HsnSa/

What is DOM element?

To find out concept of DOM element it is essential to understand concept of Dynamic HTML and DOM. Everything is started from the time that requirements of all stockholders of web pages are enhanced. They wanted the Web pages that can be more interactive, dynamic and lively. In addition, to reach this goal, developers required the tools and mechanisms that via them the presentation and content of each section of web page can be modified or manipulated. Therefore the concept of Dynamic HTML is created. To understand it, a great definition for Dynamic HTML is accessible in Wikipedia:

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated websites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM).

So, writing standard DHTML web pages are standardized in three fields, including client-side scripting language (such as JavaScript), a presentation definition language (such as CSS) and uniform programming interface(API) to access and modify the Web page (Document Object Model). This activity is performed by W3C and others. Also to solve the problem of cross browser, W3C tried to reach a general consensus (with different browser vendors) about scripts to access and manipulate HTML and XML documents via Document Object Model (DOM) as a standard application programming interface (API).

But the main question is that how they designed the structure of Document Object Model to meet their needs. Their solution was simple but wonderful. They used a hierarchical structure such as tree which at the root of the tree you can find document object, also each node is equivalent of a HTML elements (DOM element). This abstraction of your web page give you a great facility to access any HTML element, style sheets, and ... . To understand it better you can map each indent of your HTML code to each level of DOM tree. Please pay attention to this example:

Your HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p>...</p>
        <ul>
            <li>...</li>
        </ul>
        <table>
            <tr>...</tr>
        </table>
    </body>
</html> 

DOM Structure:

    document
      |    .    
    <html>    .
    /   \         .
 <head> <body>  styleSheets
        /  \  \
      <p> <ul> <table>
      /     \       \
    text    <li>    <tr>  

So, each node of this hierarchical structure (DOM tree) refers to a DOM element. To learn more use tis reference

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

How to style UITextview to like Rounded Rect text field?

You can create a Text Field that doesn't accept any events on top of a Text View like this:

CGRect frameRect = descriptionTextField.frame;
frameRect.size.height = 50;
descriptionTextField.frame = frameRect;
descriptionTextView.frame = frameRect;
descriptionTextField.backgroundColor = [UIColor clearColor];
descriptionTextField.enabled = NO;
descriptionTextView.layer.cornerRadius = 5;
descriptionTextView.clipsToBounds = YES;

How do I install PIL/Pillow for Python 3.6?

Pillow is released with installation wheels on Windows:

We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included

https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation

Update: Python 3.6 is now supported by Pillow. Install with pip install pillow and check https://pillow.readthedocs.io/en/latest/installation.html for more information.


However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).

https://travis-ci.org/python-pillow/Pillow/jobs/155605577

If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:

https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source

And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):

https://github.com/python-pillow/Pillow/tree/master/winbuild

Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.

Retrieving Property name from lambda expression

I have done the INotifyPropertyChanged implementation similar to the method below. Here the properties are stored in a dictionary in the base class shown below. It is of course not always desirable to use inheritance, but for view models I think it is acceptable and gives very clean property references in the view model classes.

public class PhotoDetailsViewModel
    : PropertyChangedNotifierBase<PhotoDetailsViewModel>
{
    public bool IsLoading
    {
        get { return GetValue(x => x.IsLoading); }
        set { SetPropertyValue(x => x.IsLoading, value); }
    }

    public string PendingOperation
    {
        get { return GetValue(x => x.PendingOperation); }
        set { SetPropertyValue(x => x.PendingOperation, value); }
    }

    public PhotoViewModel Photo
    {
        get { return GetValue(x => x.Photo); }
        set { SetPropertyValue(x => x.Photo, value); }
    }
}

The somewhat more complex base class is shown below. It handles the translation from lambda expression to property name. Note that the properties are really pseudo properties since only the names are used. But it will appear transparent to the view model and references to the properties on the view model.

public class PropertyChangedNotifierBase<T> : INotifyPropertyChanged
{
    readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

    protected U GetValue<U>(Expression<Func<T, U>> property)
    {
        var propertyName = GetPropertyName(property);

        return GetValue<U>(propertyName);
    }

    private U GetValue<U>(string propertyName)
    {
        object value;

        if (!_properties.TryGetValue(propertyName, out value))
        {
            return default(U);
        }

        return (U)value;
    }

    protected void SetPropertyValue<U>(Expression<Func<T, U>> property, U value)
    {
        var propertyName = GetPropertyName(property);

        var oldValue = GetValue<U>(propertyName);

        if (Object.ReferenceEquals(oldValue, value))
        {
            return;
        }
        _properties[propertyName] = value;

        RaisePropertyChangedEvent(propertyName);
    }

    protected void RaisePropertyChangedEvent<U>(Expression<Func<T, U>> property)
    {
        var name = GetPropertyName(property);
        RaisePropertyChangedEvent(name);
    }

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private static string GetPropertyName<U>(Expression<Func<T, U>> property)
    {
        if (property == null)
        {
            throw new NullReferenceException("property");
        }

        var lambda = property as LambdaExpression;

        var memberAssignment = (MemberExpression) lambda.Body;
        return memberAssignment.Member.Name;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Restore a deleted file in the Visual Studio Code Recycle Bin

  1. Go to your computer's Recycle Bin.
  2. Search for the specific file that got deleted.
  3. Right click on that file. Go to Restore in the drop-down list.

Voila! The file is restored and is back in your folder. Happy Coding!

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

How do I run msbuild from the command line using Windows SDK 7.1?

To enable msbuild in Command Prompt, you simply have to add the directory of the msbuild.exe install on your machine to the PATH environment variable.

You can access the environment variables by:

  1. Right clicking on Computer
  2. Click Properties
  3. Then click Advanced system settings on the left navigation bar
  4. On the next dialog box click Environment variables
  5. Scroll down to PATH
  6. Edit it to include your path to the framework (don't forget a ";" after the last entry in here).

For reference, my path was C:\Windows\Microsoft.NET\Framework\v4.0.30319

Path Updates:

As of MSBuild 12 (2013)/VS 2013/.NET 4.5.1+ and onward MSBuild is now installed as a part of Visual Studio.

For VS2015 the path was %ProgramFiles(x86)%\MSBuild\14.0\Bin

For VS2017 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin

For VS2019 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin

Image UriSource and Data Binding

you may use

ImageSourceConverter class

to get what you want

    img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");

Factorial using Recursion in Java

Your confusion, I believe, comes from the fact that you think there is only one result variable, whereas actually there is a result variable for each function call. Therefor, old results aren't replaced, but returned.

TO ELABORATE:

int fact(int n)
{
    int result;

   if(n==1)
     return 1;

   result = fact(n-1) * n;
   return result;
}

Assume a call to fact(2):

int result;
if ( n == 1 ) // false, go to next statement
result = fact(1) * 2; // calls fact(1):
|    
|fact(1)
|    int result;  //different variable
|    if ( n == 1 )  // true
|        return 1;  // this will return 1, i.e. call to fact(1) is 1
result = 1 * 2; // because fact(1) = 1
return 2;

Hope it's clearer now.

How to set the locale inside a Debian/Ubuntu Docker container?

Rather than resetting the locale after the installation of the locales package you can answer the questions you would normally get asked (which is disabled by noninteractive) before installing the package so that the package scripts setup the locale correctly, this example sets the locale to english (British, UTF-8):

RUN echo locales locales/default_environment_locale select en_GB.UTF-8 | debconf-set-selections
RUN echo locales locales/locales_to_be_generated select "en_GB.UTF-8 UTF-8" | debconf-set-selections

RUN \
  apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
  rm -rf /var/lib/apt/lists/*

Access to Image from origin 'null' has been blocked by CORS policy

A solution to this is to serve your code, and make it run on a server, you could use web server for chrome to easily serve your pages.

What is the difference between explicit and implicit cursors in Oracle?

A cursor is a SELECTed window on an Oracle table, this means a group of records present in an Oracle table, and satisfying certain conditions. A cursor can SELECT all the content of a table, too. With a cursor you can manipulate Oracle columns, aliasing them in the result. An example of implicit cursor is the following:

BEGIN
   DECLARE
      CURSOR C1
      IS
         SELECT DROPPED_CALLS FROM ALARM_UMTS;

      C1_REC   C1%ROWTYPE;
   BEGIN
      FOR C1_REC IN C1
      LOOP
         DBMS_OUTPUT.PUT_LINE ('DROPPED CALLS: ' || C1_REC.DROPPED_CALLS);
      END LOOP;
   END;
END;
/

With FOR ... LOOP... END LOOP you open and close the cursor authomatically, when the records of the cursor have been all analyzed.

An example of explicit cursor is the following:

BEGIN
   DECLARE
      CURSOR C1
      IS
         SELECT DROPPED_CALLS FROM ALARM_UMTS;

      C1_REC   C1%ROWTYPE;
   BEGIN
      OPEN c1;

      LOOP
         FETCH c1 INTO c1_rec;

         EXIT WHEN c1%NOTFOUND;

         DBMS_OUTPUT.PUT_LINE ('DROPPED CALLS: ' || C1_REC.DROPPED_CALLS);
      END LOOP;

      CLOSE c1;
   END;
END;
/

In the explicit cursor you open and close the cursor in an explicit way, checking the presence of records and stating an exit condition.

Anonymous method in Invoke call

myControl.Invoke(new MethodInvoker(delegate() {...}))

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

IntelliJ and Tomcat.. Howto..?

NOTE: Community Edition doesn't support JEE.

First, you will need to install a local Tomcat server. It sounds like you may have already done this.

Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.

From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.

CSS: How to position two elements on top of each other, without specifying a height?

Here's some reusable css that will preserve the height of each element without using position: absolute:

.stack {
    display: grid;
}
.stack > * {
    grid-row: 1;
    grid-column: 1;
}

The first element in your stack is the background, and the second is the foreground.

What's the difference between "static" and "static inline" function?

By default, an inline definition is only valid in the current translation unit.

If the storage class is extern, the identifier has external linkage and the inline definition also provides the external definition.

If the storage class is static, the identifier has internal linkage and the inline definition is invisible in other translation units.

If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.

As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static and static inline function definitions.

The inline specifier (like the register storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.

inline and register are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register-qualified variables.

Personally, I use the convention to mark static function definitions within headers also inline, as the main reason for putting function definitions in header files is to make them inlinable.

In general, I only use static inline function and static const object definitions in addition to extern declarations within headers.

I've never written an inline function with a storage class different from static.

Angular JS update input field after change

You just need to correct the format of your html

<form>
    <li>Number 1: <input type="text" ng-model="one"/> </li>
    <li>Number 2: <input type="text" ng-model="two"/> </li>
        <li>Total <input type="text" value="{{total()}}"/>  </li>      
    {{total()}}

</form>

http://jsfiddle.net/YUza7/105/

CSS for grabbing cursors (drag & drop)

In case anyone else stumbles across this question, this is probably what you were looking for:

.grabbable {
    cursor: move; /* fallback if grab cursor is unsupported */
    cursor: grab;
    cursor: -moz-grab;
    cursor: -webkit-grab;
}

 /* (Optional) Apply a "closed-hand" cursor during drag operation. */
.grabbable:active {
    cursor: grabbing;
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
}

Use -notlike to filter out multiple strings in PowerShell

$listOfUsernames = @("user1", "user2", "etc", "and so on")
Get-EventLog -LogName Security | 
    where { $_.Username -notmatch (
        '(' + [string]::Join(')|(', $listOfUsernames) + ')') }

It's a little crazy I'll grant you, and it fails to escape the usernames (in the unprobable case a username uses a Regex escape character like '\' or '(' ), but it works.

As "slipsec" mentioned above, use -notcontains if possible.

Making button go full-width?

Why not use the Bootstrap predefined class input-block-level that does the job?

<a href="#" class="btn input-block-level">Full-Width Button</a> <!-- BS2 -->
<a href="#" class="btn form-control">Full-Width Button</a> <!-- BS3 -->

<!-- And let's join both for BS# :) -->
<a href="#" class="btn input-block-level form-control">Full-Width Button</a>

Learn more here in the Control Sizing^ section.

how to align text vertically center in android

Try to put android:gravity="center_vertical|right" inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true" inside your scrollView.

UTF-8 text is garbled when form is posted as multipart/form-data

You also have to make sure that your encoding filter (org.springframework.web.filter.CharacterEncodingFilter) in your web.xml is mapped before the multipart filter (org.springframework.web.multipart.support.MultipartFilter).

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

An App ID with Identifier '' is not available. Please enter a different string

TARGETS->General->Identity

At first, modify the value of 'Bundle Identifier', so that it is different from the previous value.Then team chose 'None'. Xcode6~Xcode7.3.1

enter image description here

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

How to fix "ImportError: No module named ..." error in Python?

Do you have a file called __init__.py in the foo directory? If not then python won't recognise foo as a python package.

See the section on packages in the python tutorial for more information.

jQuery addClass onClick

It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:

function addClassByClick(button){
  $(button).addClass("active")
}

A better overall solution would be unobtrusive script, for example:

<asp:Button ID="Button" runat="server" class="clickable"/>

Then in jquery:

$(function() {                       //run when the DOM is ready
  $(".clickable").click(function() {  //use a class, since your ID gets mangled
    $(this).addClass("active");      //add the class to the clicked element
  });
});

getting the screen density programmatically in android?

Here are some density constants, source:

enter image description here

There are, in addition to the standard densities, 5 Intermediate ones. Taking into account this fact, the following code will be a complete working example:

float density = getResources().getDisplayMetrics().density;

if (density == 0.75f)
{
    // LDPI
}
else if (density >= 1.0f && density < 1.5f)
{
    // MDPI
}
else if (density == 1.5f)
{
    // HDPI
}
else if (density > 1.5f && density <= 2.0f)
{
    // XHDPI
}
else if (density > 2.0f && density <= 3.0f)
{
    // XXHDPI
}
else
{
    // XXXHDPI 
}

Alternatively, you can find density constants using the densityDpi:

int densityDpi = getResources().getDisplayMetrics().densityDpi;

switch (densityDpi)
{
    case DisplayMetrics.DENSITY_LOW:
        // LDPI
        break;

    case DisplayMetrics.DENSITY_MEDIUM:
        // MDPI
        break;

    case DisplayMetrics.DENSITY_TV:
    case DisplayMetrics.DENSITY_HIGH:
        // HDPI
        break;

    case DisplayMetrics.DENSITY_XHIGH:
    case DisplayMetrics.DENSITY_280:
        // XHDPI
        break;

    case DisplayMetrics.DENSITY_XXHIGH:
    case DisplayMetrics.DENSITY_360:
    case DisplayMetrics.DENSITY_400:
    case DisplayMetrics.DENSITY_420:
        // XXHDPI
        break;

    case DisplayMetrics.DENSITY_XXXHIGH:
    case DisplayMetrics.DENSITY_560:
        // XXXHDPI
        break;
}

Filter values only if not null using lambda in Java8

Leveraging the power of java.util.Optional#map():

List<Car> requiredCars = cars.stream()
  .filter (car -> 
    Optional.ofNullable(car)
      .map(Car::getName)
      .map(name -> name.startsWith("M"))
      .orElse(false) // what to do if either car or getName() yields null? false will filter out the element
    )
  .collect(Collectors.toList())
;

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:

SQL> grant dba to UserName; //Put This username which user show this error message.

Grant succeeded.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

You have to add the android:screenOrientation="portrait" directive in your AndroidManifest.xml. This is to be done in your <activity> tag.

In addition, the Android Developers guide states that :

[...] you should also explicitly declare that your application requires either portrait or landscape orientation with the element. For example, <uses-feature android:name="android.hardware.screen.portrait" />.

How to concatenate two layers in keras?

You can experiment with model.summary() (notice the concatenate_XX (Concatenate) layer size)

# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

You can view notebook here for detail: https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
  abstract erubis activesupport mime-types mail text-hyphen text-format   \
  thor i18n rake bundler arel railties rails --prerelease --force

How to change sa password in SQL Server 2008 express?

If you want to change your 'sa' password with SQL Server Management Studio, here are the steps:

  1. Login using Windows Authentication and ".\SQLExpress" as Server Name
  2. Change server authentication mode - Right click on root, choose Properties, from Security tab select "SQL Server and Windows Authentication mode", click OK Change server authentication mode

  3. Set sa password - Navigate to Security > Logins > sa, right click on it, choose Properties, from General tab set the Password (don't close the window) Set sa password

  4. Grant permission - Go to Status tab, make sure the Grant and Enabled radiobuttons are chosen, click OK Grant permission

  5. Restart SQLEXPRESS service from your local services (Window+R > services.msc)

Change the bullet color of list

You have to use image

.listStyle {
    list-style: none;
    background: url(bullet.jpg) no-repeat left center;
    padding-left: 40px;
}

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

How to print a percentage value in python?

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)
'33.3%'

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

How do I use CSS with a ruby on rails application?

Put the CSS files in public/stylesheets and then use:

<%= stylesheet_link_tag "filename" %>

to link to the stylesheet in your layouts or erb files in your views.

Similarly you put images in public/images and javascript files in public/javascripts.

How do I upload a file with metadata using a REST web service?

Just because you're not wrapping the entire request body in JSON, doesn't meant it's not RESTful to use multipart/form-data to post both the JSON and the file(s) in a single request:

curl -F "metadata=<metadata.json" -F "[email protected]" http://example.com/add-file

on the server side:

class AddFileResource(Resource):
    def render_POST(self, request):
        metadata = json.loads(request.args['metadata'][0])
        file_body = request.args['file'][0]
        ...

to upload multiple files, it's possible to either use separate "form fields" for each:

curl -F "metadata=<metadata.json" -F "[email protected]" -F "[email protected]" http://example.com/add-file

...in which case the server code will have request.args['file1'][0] and request.args['file2'][0]

or reuse the same one for many:

curl -F "metadata=<metadata.json" -F "[email protected]" -F "[email protected]" http://example.com/add-file

...in which case request.args['files'] will simply be a list of length 2.

or pass multiple files through a single field:

curl -F "metadata=<metadata.json" -F "[email protected],some-other-file.tar.gz" http://example.com/add-file

...in which case request.args['files'] will be a string containing all the files, which you'll have to parse yourself — not sure how to do it, but I'm sure it's not difficult, or better just use the previous approaches.

The difference between @ and < is that @ causes the file to get attached as a file upload, whereas < attaches the contents of the file as a text field.

P.S. Just because I'm using curl as a way to generate the POST requests doesn't mean the exact same HTTP requests couldn't be sent from a programming language such as Python or using any sufficiently capable tool.

How do I prompt for Yes/No/Cancel input in a Linux shell script?

In my case I needed to read from a downloaded script i.e. curl -Ss https://example.com/installer.sh | sh

The line read yesno < /dev/tty made it

echo -n "These files will be uploaded. Is this ok? (y/n) "
read yesno < /dev/tty

if [ "x$yesno" = "xy" ];then
   
   # Yes
else

   # No
fi

Convert file to byte array and vice versa

You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream

OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...

Alternative to file_get_contents?

Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.

If it's part of your site then refer to it with the file system path, not the web URL. /var/www/..., rather than http://domain.tld/....

Check if an array is empty or exists

You can use jQuery's isEmptyObject() to check whether the array contains elements or not.

var testArray=[1,2,3,4,5]; 
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true 

Source: https://api.jquery.com/jQuery.isEmptyObject/

SQL Server using wildcard within IN

  1. I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z

  2. I had to write a script to pull the current user (declare them) and pull the masks for the declared user.

  3. Create some temporary tables just basic ones to rank the row numbers for this current user

  4. loop through each result (YOUR Or this Or that etc...)

  5. Insert into the test Table.

Here is the script I used:

Drop Table #UserMasks 
Drop Table #TESTUserMasks 

Create Table #TESTUserMasks (
    [User] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

Create Table #UserMasks (
    [RN] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

DECLARE @User INT
SET @User = 74054

Insert Into #UserMasks 
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
       REPLACE(mask,'?','') Mask
from dbo.Access_Masks 
where prontouserid = @User

DECLARE @TopFlag INT
SET @TopFlag = 1

WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
    Insert Into #TestUserMasks 
    select (@User),Code from dbo.MaskArrayLookupTable 
    where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)

    SET @TopFlag = @TopFlag + 1
END
GO

select * from #TESTUserMasks

Extract substring using regexp in plain bash

Quick 'n dirty, regex-free, low-robustness chop-chop technique

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

How to convert string to double with proper cultureinfo

You can change your UI culture to anything you want, but you should change the number separator like this:

CultureInfo info = new CultureInfo("fa-IR");
info.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = info;
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

With this, your strings converts like this: "12.49" instead of "12,49" or "12/49"

Getting the index of the returned max or min item using max()/min() on a list

Why bother to add indices first and then reverse them? Enumerate() function is just a special case of zip() function usage. Let's use it in appropiate way:

my_indexed_list = zip(my_list, range(len(my_list)))

min_value, min_index = min(my_indexed_list)
max_value, max_index = max(my_indexed_list)

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Probably you didn't add your room class to child RoomDatabase child class in @Database(entities = {your_classes})

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

How to find the duration of difference between two dates in java?

The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides utility methods to do that:

Date startDate = // Set start date
Date endDate   = // Set end date

long duration  = endDate.getTime() - startDate.getTime();

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

HTML / CSS table with GRIDLINES

Via css. Put this inside the <head> tag.

<style type="text/css" media="screen">

table{
border-collapse:collapse;
border:1px solid #FF0000;
}

table td{
border:1px solid #FF0000;
}
</style>

Axios handling errors

if u wanna use async await try

export const post = async ( link,data ) => {
const option = {
    method: 'post',
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};

try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but 'request'
    console.log(errorObject);
}

How to sort a List<Object> alphabetically using Object name field

Using a selection Sort

for(int i = list.size() - 1; i > 0; i--){

  int max = i

  for(int j = 0; j < i; j++){
      if(list.get(j).getName().compareTo(list.get(j).getName()) > 0){
            max= j;
      }
  }

  //make the swap
  Object temp = list.get(i);
  list.get(i) = list.get(max);
  list.get(max) = temp;

}

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How do you configure HttpOnly cookies in tomcat / java webapps?

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}

Why does Google prepend while(1); to their JSON responses?

This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.

A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

Multiprocessing a for loop?

Alternatively

with Pool() as pool: 
    pool.map(fits.open, [name + '.fits' for name in datainput])

Android Studio: Where is the Compiler Error Output Window?

For Android Studio 3.1, select the icon below the Build one in the Build window.

Android Studio 3.1 raw log toggle button

By Android Studio 3.3 (possibly in 3.2.1), the icon has changed, though the location is the same:

Android Studio 3.3 raw log toggle button

The build window should open when you run a build action (e.g. from the Build menu). If you don't see it, you can try the "Build" button along the bottom of the window (also visible in the above screenshots), or through the menus View ? Tool Windows ? Build.

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

The Get-ChildItem cmdlet has an -Exclude parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:

function GetFiles($path = $pwd, [string[]]$exclude) 
{ 
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        if (Test-Path $item.FullName -PathType Container) 
        {
            $item 
            GetFiles $item.FullName $exclude
        } 
        else 
        { 
            $item 
        }
    } 
}

Android Studio Gradle Configuration with name 'default' not found

Your build.gradle for the module/library could be as simple as:

apply plugin: 'java'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

If your module is just a collection of .java POJO classes.

If it's model / entity classes and you're using annotations and have some dependencies you could add those in:

apply plugin: 'java'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.j256.ormlite:ormlite-core:4.48'
    compile 'com.j256.ormlite:ormlite-android:4.48'
    compile 'com.j256.ormlite:ormlite-jdbc:4.48'
}

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

Can a PDF file's print dialog be opened with Javascript?

Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:

this.print({bUI: false, bSilent: true, bShrinkToFit: true});

This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.

Auto-printing PDF!

Unsupported major.minor version 52.0

You need to upgrade your Java version to Java 8.

Download latest Java archive

Download latest Java SE Development Kit 8 release from its official download page or use following commands to download from the shell.

For 64 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-x64.tar.gz"

 # tar xzf jdk-8u51-linux-x64.tar.gz

For 32 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-i586.tar.gz"

  # tar xzf jdk-8u51-linux-i586.tar.gz

Note: If the above wget command doesn’t not work for you, watch this example video to download the Java source archive using the terminal.

Install Java with alternatives

After extracting the archive file, use the alternatives command to install it. The alternatives command is available in the chkconfig package.

 # cd /opt/jdk1.8.0_51/

 # alternatives --install /usr/bin/java java /opt/jdk1.8.0_51/bin/java 2

 # alternatives --config java

At this point Java 8 has been successfully installed on your system. We also recommend to setup javac and jar commands path using alternatives:

 # alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_51/bin/jar 2

 # alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_51/bin/javac 2

 # alternatives --set jar /opt/jdk1.8.0_51/bin/jar

 # alternatives --set javac /opt/jdk1.8.0_51/bin/javac

Check installed Java version

Check the installed version of Java using the following command.

root@tecadmin ~# java -version

java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

Configuring Environment Variables

Most of Java-based applications use environment variables to work. Set the Java environment variables using the following commands:

Setup JAVA_HOME Variable

# export JAVA_HOME=/opt/jdk1.8.0_51
Setup JRE_HOME Variable

# export JRE_HOME=$JAVA_HOME/jre
Setup PATH Variable

# export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

Note that the change to the PATH variable put the new Java bin folders first so that they override any existing java/bins in the path. It is a bit sloppy to leave two java/bin folders in your path so you should be advised to clean those up as a separate task.

Also, put all above environment variables in the /etc/environment file for auto loading on system boot.

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

Divide a number by 3 without using *, /, +, -, % operators

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

int main(int argc, char *argv[])
{

    int num = 1234567;
    int den = 3;
    div_t r = div(num,den); // div() is a standard C function.
    printf("%d\n", r.quot);

    return 0;
}

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

database vs. flat files

This is an answer I've already given some time ago:

It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.

Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.

If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.

On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.

There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.

If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.

As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.

Write to rails console

In addition to already suggested p and puts — well, actually in most cases you do can write logger.info "blah" just as you suggested yourself. It works in console too, not only in server mode.

But if all you want is console debugging, puts and p are much shorter to write, anyway.

Best way to format if statement with multiple conditions

I prefer Option A

bool a, b, c;

if( a && b && c )
{
   //This is neat & readable
}

If you do have particularly long variables/method conditions you can just line break them

if( VeryLongConditionMethod(a) &&
    VeryLongConditionMethod(b) &&
    VeryLongConditionMethod(c))
{
   //This is still readable
}

If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement

bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);

if( aa && bb && cc)
{
   //This is again neat & readable
   //although you probably need to sanity check your method names ;)
}

IMHO The only reason for option 'B' would be if you have separate else functions to run for each condition.

e.g.

if( a )
{
    if( b )
    {
    }
    else
    {
        //Do Something Else B
    }
}
else
{
   //Do Something Else A
}

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

How do I format currencies in a Vue component?

I used the custom filter solution proposed by @Jess but in my project we are using Vue together with TypeScript. This is how it looks like with TypeScript and class decorators:

import Component from 'vue-class-component';
import { Filter } from 'vue-class-decorator';

@Component
export default class Home extends Vue {

  @Filter('toCurrency')
  private toCurrency(value: number): string {
    if (isNaN(value)) {
        return '';
    }

    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 0
    });
    return formatter.format(value);
  }
}

In this example the filter can only be used inside the component. I haven't tried to implement it as a global filter, yet.

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

Error converting data types when importing from Excel to SQL Server 2008

Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:

  1. Paste from excel into Notepad and save as normal (.txt file).
  2. From within excel, open said .txt file.
  3. Select next as it is obviously tab delimited.
  4. Select "none" for text qualifier, then next again.
  5. Select the first row, hold shift, select the last row, and select the text radial button. Click Finish

It will open, check it to make sure it's accurate and then save as an excel file.

LaTeX table positioning

In my case I was having an issue where the table was not being displayed right after the paragraph I inserted it, so I simply changed

\begin{table}[]

to

\begin{table}[ht]

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

ASP.NET Button to redirect to another page

You can use PostBackUrl="~/Confirm.aspx"

For example:

In your .aspx file

<asp:Button ID="btnConfirm" runat="server" Text="Confirm" PostBackUrl="~/Confirm.aspx" />

or in your .cs file

btnConfirm.PostBackUrl="~/Confirm.aspx"

Format JavaScript date as yyyy-mm-dd

I modified Samit Satpute's response as follows:

_x000D_
_x000D_
var newstartDate = new Date();_x000D_
// newstartDate.setDate(newstartDate.getDate() - 1);_x000D_
var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format_x000D_
console.log(startDate);
_x000D_
_x000D_
_x000D_

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

How do I print a double value with full precision using cout?

Most portably...

#include <limits>

using std::numeric_limits;

    ...
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;

Xcode 6: Keyboard does not show up in simulator

If keyboard do not shown up automatically in simulator, just press [Command+K]

or Hardware -> Keyboard -> Toggle Software Keyboard

Open multiple Eclipse workspaces on the Mac

EDIT: Milhous's answer seems to be the officially supported way to do this as of 10.5. Earlier version of OS X and even 10.5 and up should still work using the following instructions though.


  1. Open the command line (Terminal)

  2. Navigate to your Eclipse installation folder, for instance:

    • cd /Applications/eclipse/
    • cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse
    • cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse
    • cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS
  3. Launch Eclipse: ./eclipse &

This last command will launch eclipse and immediately background the process.

Rinse and repeat to open as many unique instances of Eclipse as you want.


Warning

You might have to change the Tomcat server ports in order to run your project in different/multiple Tomcat instances, see Tomcat Server Error - Port 8080 already in use

get next and previous day with PHP

just in case if you want next day or previous day from today's date

date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));

just change the "-1" to the "+1" regards, Yosafat

How to uncommit my last commit in Git

Just a note - if you're using ZSH and see the error

zsh: no matches found: HEAD^

You need to escape the ^

git reset --soft HEAD\^

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.

Constructer functions

There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:

function Box (Width, Height, fill) {  
  this.width = Width;  // The width of the box 
  this.height = Height;  // The height of the box 
  this.fill = true;  // Is it filled or not?
}  

and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:

var newBox = new Box(8, 12, true);  

Object literals

Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:

var person = { 
    name: "Alireza",
    surname: "Dezfoolian"
    nose: 1,  
    feet: 2,  
    hands: 2,
    cash: null
};  

Prototyping

After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:

Box.prototype.colour = 'red';

Using Mockito to mock classes with generic parameters

I agree that one shouldn't suppress warnings in classes or methods as one could overlook other, accidentally suppressed warnings. But IMHO it's absolutely reasonable to suppress a warning that affects only a single line of code.

@SuppressWarnings("unchecked")
Foo<Bar> mockFoo = mock(Foo.class);

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

This Error mainly came when the SQL Service is stopped.You need to Restart the service.To go to this window you have to search the Services like this- enter image description here

Then Search for SQLSERVER(MSSQLSERVER) and Restart the service.

enter image description here

Hope this will work.

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

How to create a project from existing source in Eclipse and then find it?

There are several ways to add files to an existing Java project in Eclipse. So lets assume you have already created the Java project in Eclipse (e.g. using File -> New -> Project... - and select Java project).

To get Java files into the new project you can do any of the following. Note that there are other ways as well. The sequence is my preference.

  • Drag the files into the Navigator view directly from the native file manager. You must create any needed Java packages first. This method is best for a few files in an existing Java package.
  • Use File -> Import... - select File System. Here you can then select exactly which files to import into the new project and in which Java package to put them. This is extremely handy if you want to import many files or there are multiple Java packages.
  • Copy the fires directly to the folder/directory in the workspace and then use File -> Refresh to refresh the Eclipse view of the native system. Remember to select the new project before the refresh.

The last one is what you did - minus the refresh...

How to override and extend basic Django admin templates?

With django 1.5 (at least) you can define the template you want to use for a particular modeladmin

see https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options

You can do something like

class Myadmin(admin.ModelAdmin):
    change_form_template = 'change_form.htm'

With change_form.html being a simple html template extending admin/change_form.html (or not if you want to do it from scratch)

How to get substring from string in c#?

it's easy to rewrite this code in C#...

This method works if your value it's between 2 substrings !

for example:

stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"

calls should be:

myNameValue = SplitStringByASubstring(stringContent , "[myName]")

colorValue = SplitStringByASubstring(stringContent , "[color]")

etcValue = SplitStringByASubstring(stringContent , "[etc]")

npm install hangs

For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213

You'd run these commands

echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536

Then try npm install once more.

Search for "does-not-contain" on a DataFrame in pandas

You can use Apply and Lambda to select rows where a column contains any thing in a list. For your scenario :

df[df["col"].apply(lambda x:x not in [word1,word2,word3])]

Loop through list with both content and index

enumerate is what you want:

for i, s in enumerate(S):
    print s, i

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

First off, you should be wary of urls that throw SSL errors. That being said, you can suppress certificate errors in curl with

curl -k https://insecure.url/content-i-really-really-trust

Android OnClickListener - identify a button

In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.

Can you use if/else conditions in CSS?

CSS has a feature: Conditional Rules. This feature of CSS is applied based on a specific condition. Conditional Rules are:

  • @supports
  • @media
  • @document

Syntax:

@supports ("condition") {

   /* your css style */

}

Example code snippet:

_x000D_
_x000D_
<!DOCTYPE html> 
<html> 
<head> 
    <title>Supports Rule</title> 
    <style>      
        @supports (display: block) { 
            section h1 { 
                background-color: pink; 
                color: white; 
            } 
            section h2 { 
                background-color: pink; 
                color: black; 
            } 
        } 
    </style> 
</head> 
<body> 
    <section> 
        <h1>Stackoverflow</h1> 
        <h2>Stackoverflow</h2> 
    </section> 
</body> 
</html> 
_x000D_
_x000D_
_x000D_

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Numpy - add row to array

well u can do this :

  newrow = [1,2,3]
  A = numpy.vstack([A, newrow])