Programs & Examples On #Correlated subquery

Correlated sub-query is a sub-query (a query nested inside another query) that uses values from the outer query.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Also if you want to make something similar to

enter image description here

You need

1.Set horizontal and vertical alignment for button to

enter image description here

  1. Find all required values and set UIImageEdgeInsets

            CGSize buttonSize = button.frame.size;
            NSString *buttonTitle = button.titleLabel.text;
            CGSize titleSize = [buttonTitle sizeWithAttributes:@{ NSFontAttributeName : [UIFont camFontZonaProBoldWithSize:12.f] }];
            UIImage *buttonImage = button.imageView.image;
            CGSize buttonImageSize = buttonImage.size;
    
            CGFloat offsetBetweenImageAndText = 10; //vertical space between image and text
    
            [button setImageEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 - offsetBetweenImageAndText,
                                                        (buttonSize.width - buttonImageSize.width) / 2,
                                                        0,0)];                
            [button setTitleEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 + buttonImageSize.height + offsetBetweenImageAndText,
                                                        titleSize.width + [button imageEdgeInsets].left > buttonSize.width ? -buttonImage.size.width  +  (buttonSize.width - titleSize.width) / 2 : (buttonSize.width - titleSize.width) / 2 - buttonImage.size.width,
                                                        0,0)];
    

This will arrange your title and image on button.

Also please note update this on each relayout


Swift

import UIKit

extension UIButton {
    // MARK: - UIButton+Aligment

    func alignContentVerticallyByCenter(offset:CGFloat = 10) {
        let buttonSize = frame.size

        if let titleLabel = titleLabel,
            let imageView = imageView {

            if let buttonTitle = titleLabel.text,
                let image = imageView.image {
                let titleString:NSString = NSString(string: buttonTitle)
                let titleSize = titleString.sizeWithAttributes([
                    NSFontAttributeName : titleLabel.font
                    ])
                let buttonImageSize = image.size

                let topImageOffset = (buttonSize.height - (titleSize.height + buttonImageSize.height + offset)) / 2
                let leftImageOffset = (buttonSize.width - buttonImageSize.width) / 2
                imageEdgeInsets = UIEdgeInsetsMake(topImageOffset,
                                                   leftImageOffset,
                                                   0,0)

                let titleTopOffset = topImageOffset + offset + buttonImageSize.height
                let leftTitleOffset = (buttonSize.width - titleSize.width) / 2 - image.size.width

                titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset,
                                                   leftTitleOffset,
                                                   0,0)
            }
        }
    }
}

How to merge lists into a list of tuples?

You can use map lambda

a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)

This will also work if there lengths of original lists do not match

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<button>
  <a href="https://accounts.google.com/ServiceLogin?continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Den-ha-apac-in-bk-refresh14&service=mail&dsh=-3966619600017513905"
     style="cursor:default">sign in</a>
</button>

Difference between Mutable objects and Immutable objects

Immutable Object's state cannot be altered.

for example String.

String str= "abc";//a object of string is created
str  = str + "def";// a new object of string is created and assigned to str

What is the difference between procedural programming and functional programming?

I've never seen this definition given elsewhere, but I think this sums up the differences given here fairly well:

Functional programming focuses on expressions

Procedural programming focuses on statements

Expressions have values. A functional program is an expression who's value is a sequence of instructions for the computer to carry out.

Statements don't have values and instead modify the state of some conceptual machine.

In a purely functional language there would be no statements, in the sense that there's no way to manipulate state (they might still have a syntactic construct named "statement", but unless it manipulates state I wouldn't call it a statement in this sense). In a purely procedural language there would be no expressions, everything would be an instruction which manipulates the state of the machine.

Haskell would be an example of a purely functional language because there is no way to manipulate state. Machine code would be an example of a purely procedural language because everything in a program is a statement which manipulates the state of the registers and memory of the machine.

The confusing part is that the vast majority of programming languages contain both expressions and statements, allowing you to mix paradigms. Languages can be classified as more functional or more procedural based on how much they encourage the use of statements vs expressions.

For example, C would be more functional than COBOL because a function call is an expression, whereas calling a sub program in COBOL is a statement (that manipulates the state of shared variables and doesn't return a value). Python would be more functional than C because it allows you to express conditional logic as an expression using short circuit evaluation (test && path1 || path2 as opposed to if statements). Scheme would be more functional than Python because everything in scheme is an expression.

You can still write in a functional style in a language which encourages the procedural paradigm and vice versa. It's just harder and/or more awkward to write in a paradigm which isn't encouraged by the language.

Node Version Manager install - nvm command not found

Not directly connected to the question, but there is a similar problem that may happen, take a look at this question: Can't execute nvm from new bash


Here's my answer on that post, just for the reference:

If you are running from a new bash instance, and you HAVE the initialization code at your ~/.bashrc, ~/.bash_profile, etc, then you need to check this initialization file for conditionals.

On Ubuntu 14, there is a:

case $- in
    *i*) ;;
      *) return;;
esac

At line 6, that will halt it's execution if bash is not being ran with the "-i" (interactive) flag. So you would need to run:

bash -i

Also, at the end of the file, there is a

[ -z "$PS1" ] && return

That will halt it's execution if not being ran with $PS1 set (like on a remote ssh session).

If you do not wish to add any env vars or flags, you will need to remove those conditionals from your initialization file.

Hope that's helpful.

Get int value from enum in C#

If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question, to use for example in a method, you can simply do this I wrote in this example:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

This will change the window title to 4, because the variable Geselecteerd is Talen.Nederlands. If I change it to Talen.Portugees and call the method again, the text will change to 3.

Instantly detect client disconnection from server socket

You can also check the .IsConnected property of the socket if you were to poll.

Java Ordered Map

Since Java 6 there is also non-blocking thread-safe alternative to TreeMap. See ConcurrentSkipListMap.

How to get a value from a Pandas DataFrame and not the index and object type

import pandas as pd

dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])

>>> values[0]
'item_0'

edit:

actually, you can just index the dataset like any old array.

import pandas as pd

dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]

>>> print(first_value)
'item_0'

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Sharing my case, hope that will help.

In my situation inside MY_PROJ.Database->MY_PROJ.Database.sqlproj I had to put this:

<Build Include="dbo\Tables\MyTableGeneratingScript.sql" />

.NET Core vs Mono

This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:

  • APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
    different; type shape differs in key cases). These differences
    currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
    include more of the .NET Framework BCL APIs over time.
  • Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
    programming model. For example, Code Access Security (CAS) is not
    supported, while reflection is supported.

If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

Linq and Entity framework are included in .NET Core, so you are safe to take a shot.

Calculate time difference in Windows batch file

Fixed Gynnad's leading 0 Issue. I fixed it with the two Lines

SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%

Full Script ( CalculateTime.cmd ):

@ECHO OFF

:: F U N C T I O N S

:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0

:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
SET /A DURATION=%ENDTIME%-%STARTTIME%
IF %DURATION% == 0 SET TIMEDIFF=00:00:00,00 && EXIT /B 0
IF %ENDTIME% LSS %STARTTIME% SET /A DURATION=%STARTTIME%-%ENDTIME%
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
SET /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
SET /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=0%DURATIONH%
IF %DURATIONM% LSS 10 SET DURATIONM=0%DURATIONM%
IF %DURATIONS% LSS 10 SET DURATIONS=0%DURATIONS%
IF %DURATIONHS% LSS 10 SET DURATIONHS=0%DURATIONHS%
SET TIMEDIFF=%DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
EXIT /B 0

:: U S A G E

:: Start Measuring
CALL :__START_TIME_MEASURE

:: Print Message on Screen without Linefeed
ECHO|SET /P=Execute Job... 

:: Some Time pending Jobs here
:: '> NUL 2>&1' Dont show any Messages or Errors on Screen
MyJob.exe > NUL 2>&1

:: Stop Measuring
CALL :__STOP_TIME_MEASURE

:: Finish the Message 'Execute Job...' and print measured Time
ECHO [Done] (%TIMEDIFF%)

:: Possible Result
:: Execute Job... [Done] (00:02:12,31)
:: Between 'Execute Job... ' and '[Done] (00:02:12,31)' the Job will be executed

regular expression to match exactly 5 digits

No need to care of whether before/after this digit having other type of words

To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression (?<!\d)\d{5}(?!\d).

Sample JavaScript codes:

var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g); 
    var matches = yourstring.match(regexp);
    if (matches && matches.length > 0) {
        for (var i = 0, len = matches.length; i < len; i++) {
            // ... ydo something with matches[i] ...
        } 
    }

Here's some quick results.

  • abc12345xyz (?)

  • 12345abcd (?)

  • abcd12345 (?)

  • 0000aaaa2 (?)

  • a1234a5 (?)

  • 12345 (?)

  • <space>12345<space>12345 (??)

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I would try Scott's CLR function first but add a WHERE clause to reduce the number of records updated.

UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) 
WHERE phonenumber like '%[^0-9]%'

If you know that the great majority of your records have non-numeric characters it might not help though.

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

How to tell if a string contains a certain character in JavaScript?

String's search function is useful too. It searches for a character as well as a sub_string in a given string.

'apple'.search('pl') returns 2

'apple'.search('x') return -1

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Count textarea characters

    $(document).ready(function(){ 
    $('#characterLeft').text('140 characters left');
    $('#message').keydown(function () {
        var max = 140;
        var len = $(this).val().length;
        if (len >= max) {
            $('#characterLeft').text('You have reached the limit');
            $('#characterLeft').addClass('red');
            $('#btnSubmit').addClass('disabled');            
        } 
        else {
            var ch = max - len;
            $('#characterLeft').text(ch + ' characters left');
            $('#btnSubmit').removeClass('disabled');
            $('#characterLeft').removeClass('red');            
        }
    });    
});

Find an element in DOM based on an attribute value

you could use getAttribute:

 var p = document.getElementById("p");
 var alignP = p.getAttribute("align");

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

How do you resize a form to fit its content automatically?

If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.

this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);

How to use greater than operator with date?

I have tried but above not working after research found below the solution.

SELECT * FROM my_table where DATE(start_date) > '2011-01-01';

Ref

How do I reference a cell range from one worksheet to another using excel formulas?

You can put an equal formula, then copy it so reference the whole range (one cell goes into one cell)

=Sheet2!A1

If you need to concatenate the results, you'll need a longer formula, or a user-defined function (i.e. macro).

=Sheet2!A1&Sheet2!B1&Sheet2!C1&Sheet2!D1&Sheet2!E1&Sheet2!F1

Postgresql tables exists, but getting "relation does not exist" when querying

The error can be caused by access restrictions. Solution:

GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

Why is using the JavaScript eval function a bad idea?

Two points come to mind:

  1. Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)

  2. Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

JavaScript equivalent of PHP's in_array()

There is now Array.prototype.includes:

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

Syntax

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Table relationships vs. entity relationships

In a relational database system, there can be only three types of table relationships:

  • one-to-many (via a Foreign Key column)
  • one-to-one (via a shared Primary Key)
  • many-to-many (via a link table with two Foreign Keys referencing two separate parent tables)

So, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

So, you have two sides that can change the entity association:

  • By adding an entry in the comments child collection, a new post_comment row should be associated with the parent post entity via its post_id column.
  • By setting the post property of the PostComment entity, the post_id column should be updated as well.

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy (a.k.a the inverse side)

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

It's called the inverse side because it references the child entity property that manages this table relationship.

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

How to "add existing frameworks" in Xcode 4?

Follow below 5 steps to add framework in your project.

  1. Click on Project Navigator.
  2. Select Targets (Black arrow in the below image).
  3. Select Build phases ( Blue arrow in the below image).
  4. Click on + Button (Green arrow in below image).
  5. Select your framework from list.

Framework

Here is the official Apple Link

Specified argument was out of the range of valid values. Parameter name: site

For me, it was happening because I had switched over to "Run as Administrator". Just one instance of VS was running, but running it as admin threw this error. Switching back fixed me right up.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

Stylesheet not loaded because of MIME-type

How I solved this. For Node.js applications, you need to set your **public** folder configuration.

// Express js
app.use(express.static(__dirname + '/public'));

Otherwise, you need to do like href="public/css/style.css".

<link href="public/assets/css/custom.css">
<script src="public/assets/js/scripts.js"></script>

Note: It will work for http://localhost:3000/public/assets/css/custom.css. But couldn't work after build. You need to set app.use(express.static(__dirname + '/public')); for Express

How do I convert a C# List<string[]> to a Javascript array?

I would say it's more a problem of the way you're modeling your data. Instead of using string arrays for addresses, it would be much cleaner and easier to do something like this:

Create a class to represent your addresses, like this:

public class Address
{
    public string Address1 { get; set; }
    public string CityName { get; set; }
    public string StateCode { get; set; }
    public string ZipCode { get; set; }
}

Then in your view model, you can populate those addresses like this:

public class ViewModel
{
    public IList<Address> Addresses = new List<Address>();

    public void PopulateAddresses()
    {
        foreach(DataRow row in AddressTable.Rows)
        {
            Address address = new Address
                {
                    Address1 = row["Address1"].ToString(),
                    CityName = row["CityName"].ToString(),
                    StateCode = row["StateCode"].ToString(),
                    ZipCode = row["ZipCode"].ToString()
                };
            Addresses.Add(address);
        }

        lAddressGeocodeModel.Addresses = JsonConvert.SerializeObject(Addresses);
    }
}

Which will give you JSON that looks like this:

[{"Address1" : "123 Easy Street", "CityName": "New York", "StateCode": "NY", "ZipCode": "12345"}]

Anchor links in Angularjs?

I don't know if that answers your question, but yes, you can use angularjs links, such as:

<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>

There is a good example on the AngularJS website:

http://docs.angularjs.org/api/ng.directive:ngHref

UPDATE: The AngularJS documentation was a bit obscure and it didn't provide a good solution for it. Sorry!

You can find a better solution here: How to handle anchor hash linking in AngularJS

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

Quoting the doc:

Some attributes do not apply to all data types. AUTO_INCREMENT applies only to integer and floating-point types. DEFAULT does not apply to the BLOB or TEXT types.

In your case, you're trying to apply AUTO_INCREMENT modifier to char column. To solve this, either drop AUTO_INCREMENT altogether (that means you'll have to generate a unique id on the application level) or just change topic_id type to the relevant integer one.

As a sidenote, it makes little sense using char(36) to store the posts count, so that column's type probably has to be changed as well. It looks like you're going this way to prevent integer overflow - but if you're dealing with more than 18446744073709551615 posts (the biggest number that can be stored in BIGINT UNSIGNED column) in a single topic, you have far bigger problem on your side probably. )

Text not wrapping in p tag

For others that find themselves here, the css I was looking for was

overflow-wrap: break-word;

Which will only break a word if it needs to (the length of the single word is greater than the width of the p), unlike word-break: break-all which can break the last word of every line.

overflow-wrap demo

Python int to binary string?

Python's string format method can take a format spec.

>>> "{0:b}".format(37)
'100101'

Format spec docs for Python 2

Format spec docs for Python 3

How to submit a form using Enter key in react.js?

I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!

const { useEffect } = require("react");

const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
    useEffect(() => {
        //https://stackoverflow.com/a/59147255/828184
        const listener = (event) => {
            if (event.code === "Enter" || event.code === "NumpadEnter") {
                handlePressEnter();
            }
        };

        document.addEventListener("keydown", listener);

        return () => {
            document.removeEventListener("keydown", listener);
        };
    }, []);

    const handlePressEnter = () => {
        //https://stackoverflow.com/a/54316368/828184
        const mouseClickEvents = ["mousedown", "click", "mouseup"];
        function simulateMouseClick(element) {
            mouseClickEvents.forEach((mouseEventType) =>
                element.dispatchEvent(
                    new MouseEvent(mouseEventType, {
                        view: window,
                        bubbles: true,
                        cancelable: true,
                        buttons: 1,
                    })
                )
            );
        }

        var element = document.querySelector(querySelectorToExecuteClick);
        simulateMouseClick(element);
    };
};

export default useEnterKeyListener;

This is how you use it:

useEnterKeyListener({
    querySelectorToExecuteClick: "#submitButton",
});

https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407

How can I control the speed that bootstrap carousel slides in items?

For Twitter Bootstrap 3:

You must change the CSS transition as specified in the other answer:

.carousel-inner > .item {
    position: relative;
    display: none;
    -webkit-transition: 0.6s ease-in-out left;
    -moz-transition: 0.6s ease-in-out left;
    -o-transition: 0.6s ease-in-out left;
    transition: 0.6s ease-in-out left;
}

From 0.6 seconds to 1.5 seconds (for example).

But also, there is some Javascript to change. In the bootstrap.js there is a line:

.emulateTransitionEnd(600)

This should be changed to the corresponding amount of milliseconds. So for 1.5 seconds you would change the number to 1500:

.emulateTransitionEnd(1500)

How to convert a byte to its binary string representation

A simple answer could be:

System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 0
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); // 1
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0})); // 256
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0})); // 65536
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0})); // 16777216
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0})); // 4294967296
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0})); // 1099511627776
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0})); // 281474976710656
System.out.println(new BigInteger(new byte[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0})); // 72057594037927936
System.out.println(new BigInteger(new byte[]{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})); // 18446744073709551616
System.out.println(new BigInteger(new byte[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 4722366482869645213696
System.out.println(new BigInteger(new byte[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 1208925819614629174706176
System.out.println(Long.MAX_VALUE);                                              // 9223372036854775807

Read from file or stdin

Note that what you want is to know if stdin is connected to a terminal or not, not if it exists. It always exists but when you use the shell to pipe something into it or read a file, it is not connected to a terminal.

You can check that a file descriptor is connected to a terminal via the termios.h functions:

#include <termios.h>
#include <stdbool.h>

bool stdin_is_a_pipe(void)
{
    struct termios t;
    return (tcgetattr(STDIN_FILENO, &t) < 0);
}

This will try to fetch the terminal attributes of stdin. If it is not connected to a pipe, it is attached to a tty and the tcgetattr function call will succeed. In order to detect a pipe, we check for tcgetattr failure.

Python list sort in descending order

This will give you a sorted version of the array.

sorted(timestamps, reverse=True)

If you want to sort in-place:

timestamps.sort(reverse=True)

How can I remove a button or make it invisible in Android?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try This Code

Visibility works fine in this code

How to restart counting from 1 after erasing table in MS Access?

In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.

How to right-align form input boxes?

Use some tag, to aligning the input element. So

<form>
   <div>
     <input>
     <br />
     <input>
    </div>
</form>

    .mydiv
     {
        width: 500px;
        height: 250px;
        display: table;
        text-align: right;
     }

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

Android basically works on two thread types namely UI thread and background thread. According to android documentation -

Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)  
View.post(Runnable)  
View.postDelayed(Runnable, long)

Now there are various methods to solve this problem. I will explain it by code sample

runOnUiThread

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new runnable()
        {
            public void run()
            {
                //Do your UI operations like dialog opening or Toast here
            }
        });
    }
}.start();

LOOPER

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }

AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

public void onClick(View v) {
    new CustomTask().execute((Void[])null);
}


private class CustomTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... param) {
        //Do some work
        return null;
    }

    protected void onPostExecute(Void param) {
        //Print Toast or open dialog
    }
}

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Message msg = new Message();


    new Thread()
    {
        public void run()
        {
            msg.arg1=1;
            handler.sendMessage(msg);
        }
    }.start();



    Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg1==1)
            {
                //Print Toast or open dialog        
            }
            return false;
        }
    });

Why do I need to configure the SQL dialect of a data source?

A dialect is a form of the language that is spoken by a particular group of people.

Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.

The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.

The dialect of hibernate can be configured using below property:

hibernate.dialect

Here, is a complete list of hibernate dialects.

Note: The dialect property of hibernate is not mandatory.

Different ways of adding to Dictionary

One is assigning a value while the other is adding to the Dictionary a new Key and Value.

Xcode project not showing list of simulators

Just check your Deployment Target where XCode support it or not.

Create File If File Does Not Exist

You can simply call

using (StreamWriter w = File.AppendText("log.txt"))

It will create the file if it doesn't exist and open the file for appending.

Edit:

This is sufficient:

string path = txtFilePath.Text;               
using(StreamWriter sw = File.AppendText(path))
{
  foreach (var line in employeeList.Items)                 
  {                    
    Employee e = (Employee)line; // unbox once
    sw.WriteLine(e.FirstName);                     
    sw.WriteLine(e.LastName);                     
    sw.WriteLine(e.JobTitle); 
  }                
}     

But if you insist on checking first, you can do something like this, but I don't see the point.

string path = txtFilePath.Text;               


using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))                 
{                      
    foreach (var line in employeeList.Items)                     
    {                         
      sw.WriteLine(((Employee)line).FirstName);                         
      sw.WriteLine(((Employee)line).LastName);                         
      sw.WriteLine(((Employee)line).JobTitle);                     
    }                  
} 

Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList, then unbox the object once and use the reference.

However, I perfer to use List<> for my collections:

public class EmployeeList : List<Employee>

Pandas DataFrame to List of Dictionaries

Edit

As John Galt mentions in his answer , you should probably instead use df.to_dict('records'). It's faster than transposing manually.

In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop

In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop

Original answer

Use df.T.to_dict().values(), like below:

In [1]: df
Out[1]:
   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

Set JavaScript variable = null, or leave undefined?

I declare them as undefined when I don't assign a value because they are undefined after all.

npm install error - unable to get local issuer certificate

Try

npm config set strict-ssl false

This is a alternative shared in this url https://github.com/nodejs/node/issues/3742

android edittext onchange listener

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Is it fine to have foreign key as primary key?

Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.

Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.

The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.

How to properly stop the Thread in Java?

You should always end threads by checking a flag in the run() loop (if any).

Your thread should look like this:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean execute;

    @Override
    public void run() {
        this.execute = true;
        while (this.execute) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                this.execute = false;
            }
        }
    }

    public void stopExecuting() {
        this.execute = false;
    }
}

Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

To avoid waiting for 15 seconds, you can split up the sleep like this:

        ...
        try {
            LOGGER.debug("Sleeping...");
            for (int i = 0; (i < 150) && this.execute; i++) {
                Thread.sleep((long) 100);
            }

            LOGGER.debug("Processing");
        } catch (InterruptedException e) {
        ...

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The docker run command has a --ulimit flag you can use this flag to set the open file limit in your docker container.

Run the following command when spinning up your container to set the open file limit.

docker run --ulimit nofile=<softlimit>:<hardlimit> the first value before the colon indicates the soft file limit and the value after the colon indicates the hard file limit. you can verify this by running your container in interactive mode and executing the following command in your containers shell ulimit -n

PS: check out this blog post for more clarity

Keyboard shortcut to comment lines in Sublime Text 3

In my notebook keyboard, a ABNT 2, I can use the CTRL+; shortcut as the default comment action for blocks and lines. The same shortcut to uncomment.

How can I set the default timezone in node.js?

As of Node 13, you can now repeatedly set process.env.TZ and it will be reflected in the timezone of new Date objects. I don't know if I'd use this in production code but it would definitely be useful in unit tests.

> process.env.TZ = 'Europe/London';
'Europe/London'
> (new Date().toString())
'Fri Mar 20 2020 09:39:59 GMT+0000 (Greenwich Mean Time)'

> process.env.TZ = 'Europe/Amsterdam';
'Europe/Amsterdam'
> (new Date().toString())
'Fri Mar 20 2020 10:40:07 GMT+0100 (Central European Standard Time)'

Python truncate a long string

info = (data[:75] + '..') if len(data) > 75 else data

How can I compare strings in C using a `switch` statement?

To add to Phimueme's answer above, if your string is always two characters, then you can build a 16-bit int out of the two 8-bit characters - and switch on that (to avoid nested switch/case statements).

This Handler class should be static or leaks might occur: IncomingHandler

With the help of @Sogger's answer, I created a generic Handler:

public class MainThreadHandler<T extends MessageHandler> extends Handler {

    private final WeakReference<T> mInstance;

    public MainThreadHandler(T clazz) {
        // Remove the following line to use the current thread.
        super(Looper.getMainLooper());
        mInstance = new WeakReference<>(clazz);
    }

    @Override
    public void handleMessage(Message msg) {
        T clazz = mInstance.get();
        if (clazz != null) {
            clazz.handleMessage(msg);
        }
    }
}

The interface:

public interface MessageHandler {

    void handleMessage(Message msg);

}

I'm using it as follows. But I'm not 100% sure if this is leak-safe. Maybe someone could comment on this:

public class MyClass implements MessageHandler {

    private static final int DO_IT_MSG = 123;

    private MainThreadHandler<MyClass> mHandler = new MainThreadHandler<>(this);

    private void start() {
        // Do it in 5 seconds.
        mHandler.sendEmptyMessageDelayed(DO_IT_MSG, 5 * 1000);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case DO_IT_MSG:
                doIt();
                break;
        }
    }

    ...

}

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

How to remove duplicate values from an array in PHP

<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];    
print_r(arr_unique($arr1));


function arr_unique($arr) {
  sort($arr);
  $curr = $arr[0];
  $uni_arr[] = $arr[0];
  for($i=0; $i<count($arr);$i++){
      if($curr != $arr[$i]) {
        $uni_arr[] = $arr[$i];
        $curr = $arr[$i];
      }
  }
  return $uni_arr;
}

Difference between `constexpr` and `const`

I don't think any of the answers really make it clear exactly what side effects it has, or indeed, what it is.

constexpr and const at namespace/file-scope are identical when initialised with a literal or expression; but with a function, const can be initialised by any function, but constexpr initialised by a non-constexpr (a function that isn't marked with constexpr or a non constexpr expression) will generate a compiler error. Both constexpr and const are implicitly internal linkage for variables (well actually, they don't survive to get to the linking stage if compiling -O1 and stronger, and static doesn't force the compiler to emit an internal (local) linker symbol for const or constexpr when at -O1 or stronger; the only time it does this is if you take the address of the variable. const and constexpr will be an internal symbol unless expressed with extern i.e. extern constexpr/const int i = 3; needs to be used). On a function, constexpr makes the function permanently never reach the linking stage (regardless of extern or inline in the definition or -O0 or -Ofast), whereas const never does, and static and inline only have this effect on -O1 and above. When a const/constexpr variable is initialised by a constexpr function, the load is always optimised out with any optimisation flag, but it is never optimised out if the function is only static or inline, or if the variable is not a const/constexpr.

Standard compilation (-O0)

#include<iostream>
constexpr int multiply (int x, int y)
{

  return x * y;
}

extern const int val = multiply(10,10);
int main () {
  std::cout << val;
} 

compiles to

val:
        .long   100  //extra external definition supplied due to extern

main:
        push    rbp
        mov     rbp, rsp
        mov     esi, 100 //substituted in as an immediate
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     eax, 0
        pop     rbp
        ret

__static_initialization_and_destruction_0(int, int):
        . 
        . 
        . 

However

#include<iostream>
const int multiply (int x, int y)
{

  return x * y;
}

const int val = multiply(10,10); //constexpr is an error
int main () {
  std::cout << val;
}

Compiles to

multiply(int, int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        mov     eax, DWORD PTR [rbp-4]
        imul    eax, DWORD PTR [rbp-8]
        pop     rbp
        ret

main:
        push    rbp
        mov     rbp, rsp
        mov     eax, DWORD PTR val[rip]
        mov     esi, eax
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     eax, 0
        pop     rbp
        ret

__static_initialization_and_destruction_0(int, int):
        . 
        . 
        . 
        mov     esi, 10
        mov     edi, 10
        call    multiply(int, int)
        mov     DWORD PTR val[rip], eax

This clearly shows that constexpr causes the initialisation of the const/constexpr file-scope variable to occur at compile time and produce no global symbol, whereas not using it causes initialisation to occur before main at runtime.

Compiling using -Ofast

Even -Ofast doesn't optimise out the load! https://godbolt.org/z/r-mhif, so you need constexpr


constexpr functions can also be called from inside other constexpr functions for the same result. constexpr on a function also prevents use of anything that can't be done at compile time in the function; for instance, a call to the << operator on std::cout.

constexpr at block scope behaves the same in that it produces an error if initialised by a non-constexpr function; the value is also substituted in immediately.

In the end, its main purpose is like C's inline function, but it is only effective when the function is used to initialise file-scope variables (which functions cannot do on C, but they can on C++ because it allows dynamic initialisation of file-scope variables), except the function cannot export a global/local symbol to the linker as well, even using extern/static, which you could with inline on C; block-scope variable assignment functions can be inlined simply using an -O1 optimisation without constexpr on C and C++.

How to get the Mongo database specified in connection string in C#

Update:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

var _server = new MongoClient(connectionString).GetServer();

It's easy. You should first take database name from connection string and then get database by name. Complete example:

var connectionString = "mongodb://localhost:27020/mydb";

//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);

//and then get database by database name:
_server.GetDatabase(_databaseName);

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

Regex for not empty and not whitespace

Most regular expression engines support "counter part" escape sequences. That is, for \s (white-space) there's its counter part \S (non-white-space).

Using this, you can check, if there is at least one non-white-space character with ^\S+$.

PCRE for PHP has several of these escape sequences.

What database does Google use?

As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.

The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.

Split string into array of character strings

Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

Combined with an ArrayList<String> for example you can get your array of individual characters.

How do I disable a href link in JavaScript?

The easiest way to disable a link is simply not to show it. Run this function whenever you want to test if your condition is met to hide the Previous button (replace if (true) with your condition):

var testHideNav = function() {
    var aTags = document.getElementsByTagName('a'),
        atl = aTags.length,
        i;

    for (i = 0; i < atl; i++) {
        if (aTags[i].innerText == "Previous") {
            if (true) { // your condition to disable previous
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        } else if (aTags[i].innerText == "Next") {
            if (false) { // your condition to disable next
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        }
    }
};

Then run testHideNav() whenever you need to make the check if your condition has changed.

Save plot to image file instead of displaying it using Matplotlib

When using matplotlib.pyplot, you must first save your plot and then close it using these 2 lines:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

HTML5 Video not working in IE 11

It was due to IE Document-mode version too low. Press 'F12' and using higher version( My case, above version 9 is OK)

Only local connections are allowed Chrome and Selenium webdriver

For me, updating the chromedriver and selenium version removed this message.

However, this is not an actual error and just an informational message. If your program is still passing with exit code 0 at the end even when this message is printed, it means the execution went fine.

How to select a column name with a space in MySQL

To each his own but the right way to code this is to rename the columns inserting underscore so there are no gaps. This will ensure zero errors when coding. When printing the column names for public display you could search-and-replace to replace the underscore with a space.

Refresh Page C# ASP.NET

To refresh the whole page, but it works normally:

Response.Redirect(url,bool) 

MySQL JOIN ON vs USING?

Database tables

To demonstrate how the USING and ON clauses work, let's assume we have the following post and post_comment database tables, which form a one-to-many table relationship via the post_id Foreign Key column in the post_comment table referencing the post_id Primary Key column in the post table:

SQL USING vs ON clauses table relationship

The parent post table has 3 rows:

| post_id | title     |
|---------|-----------|
| 1       | Java      |
| 2       | Hibernate |
| 3       | JPA       |

and the post_comment child table has the 3 records:

| post_comment_id | review    | post_id |
|-----------------|-----------|---------|
| 1               | Good      | 1       |
| 2               | Excellent | 1       |
| 3               | Awesome   | 2       |

The JOIN ON clause using a custom projection

Traditionally, when writing an INNER JOIN or LEFT JOIN query, we happen to use the ON clause to define the join condition.

For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:

SELECT
   post.post_id,
   title,
   review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

And, we get back the following result set:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The JOIN USING clause using a custom projection

When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:

SELECT
  post_id,
  title,
  review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

And, the result set for this particular query is identical to the previous SQL query that used the ON clause:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.

The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.

SQL JOIN ON clause with SELECT *

Now, if we change the previous ON clause query to select all columns using SELECT *:

SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

We are going to get the following result set:

| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |

As you can see, the post_id is duplicated because both the post and post_comment tables contain a post_id column.

SQL JOIN USING clause with SELECT *

On the other hand, if we run a SELECT * query that features the USING clause for the JOIN condition:

SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

We will get the following result set:

| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |

You can see that this time, the post_id column is deduplicated, so there is a single post_id column being included in the result set.

Conclusion

If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.

Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.

php var_dump() vs print_r()

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Example:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)

More Info

Is nested function a good approach when required by only one function?

Function In function python

def Greater(a,b):
    if a>b:
        return a
    return b

def Greater_new(a,b,c,d):
    return Greater(Greater(a,b),Greater(c,d))

print("Greater Number is :-",Greater_new(212,33,11,999))

How to pass variable as a parameter in Execute SQL Task SSIS?

Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes

https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

In your manifest file package attribute is set to com.test.helloworld however your activity class is under different package. Change your MyActivity class package to com.example.helloworld

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

How to move a git repository into another directory and make that directory a git repository?

I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

What is an OS kernel ? How does it differ from an operating system?

It seems that the original metaphor that got us the word "kernel" for this in the first place has been forgotten. The metaphor is that an operating system is a seed. The "kernel" of the seed is the core of the operating system, providing operating system services to applications programs, which is surrounded by the "shell" of the seed that is what users see from the outside.

Some people want to tie "kernel" (and, indeed, "shell") down to be more specific than that. But in truth there's a lot of variation across operating systems. Not the least these variations is what constitutes a "shell" (which can range from Solaris' sh through Netware's Console Command Interpreter to OS/2's Workplace Shell and Windows NT's Explorer), but there's also a lot of variance from one operating system to another in what is, and isn't, a part of a "kernel" (which may or may not include disk I/O, for example).

It's best to remember that these terms are metaphors.

Further reading

How to get week number of the month from the date in sql server 2008

Here you go....

Im using the code below..

DATEPART(WK,@DATE_INSERT) - DATEPART(WK,DATEADD(DAY,1,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@DATE_INSERT),0)))) + 1

How to change the MySQL root account password on CentOS7?

Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this

mysqld_safe --skip-grant-tables

its may work properly

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

Maximum length for MD5 input/output

Append Length

A 64-bit representation of b (the length of the message before the padding bits were added) is appended to the result of the previous step. In the unlikely event that b is greater than 2^64, then only the low-order 64 bits of b are used.

  • The hash is always 128 bits. If you encode it as a hexdecimal string you can encode 4 bits per character, giving 32 characters.
  • MD5 is not encryption. You cannot in general "decrypt" an MD5 hash to get the original string.

See more here.

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

How can I make a clickable link in an NSAttributedString?

The quick answer is using UITextView instead of UILabel. You need to enable Selectable and disable Editable.

Then disable scroll indicators and bounces.

Screen Shot

Screen Shot

My solution using NSMutableAttributedString from html string NSHTMLTextDocumentType

NSString *s = @"<p><a href='https://itunes.apple.com/us/app/xxxx/xxxx?mt=8'>https://itunes.apple.com/us/app/xxxx/xxxx?mt=8</a></p>";

NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
                                           initWithData: [s dataUsingEncoding:NSUnicodeStringEncoding]
                                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                           documentAttributes: nil
                                           error: nil
                                           ];

cell.content.attributedText = text;

how to show only even or odd rows in sql server 2008?

SELECT *
  FROM   
  ( 
     SELECT rownum rn, empno, ename
     FROM emp
  ) temp
  WHERE  MOD(temp.rn,2) = 1

Is there a way to get version from package.json in nodejs code?

I made a useful code to get the parent module's package.json

function loadParentPackageJson() {
    if (!module.parent || !module.parent.filename) return null
    let dir = path.dirname(module.parent.filename)
    let maxDepth = 5
    let packageJson = null
    while (maxDepth > 0) {
        const packageJsonPath = `${dir}/package.json`
        const exists = existsSync(packageJsonPath)
        if (exists) {
            packageJson = require(packageJsonPath)
            break
        }
        dir = path.resolve(dir, '../')
        maxDepth--
    }
    return packageJson
}

receiving json and deserializing as List of object at spring mvc controller

This is not possible the way you are trying it. The Jackson unmarshalling works on the compiled java code after type erasure. So your

public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map) 

is really only

public @ResponseBody ModelMap setTest(@RequestBody List refunds, ModelMap map) 

(no generics in the list arg).

The default type Jackson creates when unmarshalling a List is a LinkedHashMap.

As mentioned by @Saint you can circumvent this by creating your own type for the list like so:

class TestSList extends ArrayList<TestS> { }

and then modifying your controller signature to

public @ResponseBody ModelMap setTest(@RequestBody TestSList refunds, ModelMap map) {

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related request.

The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.

You can check RFC 2387 specification for more in-depth details.

Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.

Example:

POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]

--xyz
Content-Type: application/json; charset=UTF-8

{
    "name": "Sample image",
    "desc": "...",
    ...
}

--xyz
Content-Type: image/jpeg

[image data]
[image data]
[image data]
...
--foo_bar_baz--

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

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

How do I check whether a checkbox is checked in jQuery?

There are many ways to check if a checkbox is checked or not:

Way to check using jQuery

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

Check example or also document:

Generating Unique Random Numbers in Java

Choose n unique random numbers from 0 to m-1.

int[] uniqueRand(int n, int m){
    Random rand = new Random();
    int[] r = new int[n];
    int[] result = new int[n];
    for(int i = 0; i < n; i++){
        r[i] = rand.nextInt(m-i);
        result[i] = r[i];
        for(int j = i-1; j >= 0; j--){
            if(result[i] >= r[j])
                result[i]++;
        }
    }
    return result;
}

Imagine a list containing numbers from 0 to m-1. To choose the first number, we simply use rand.nextInt(m). Then remove the number from the list. Now there remains m-1 numbers, so we call rand.nextInt(m-1). The number we get represents the position in the list. If it is less than the first number, then it is the second number, since the part of list prior to the first number wasn't changed by the removal of the first number. If the position is greater than or equal to the first number, the second number is position+1. Do some further derivation, you can get this algorithm.

Explanation

This algorithm has O(n^2) complexity. So it is good for generating small amount of unique numbers from a large set. While the shuffle based algorithm need at least O(m) to do the shuffle.

Also shuffle based algorithm need memory to store every possible outcome to do the shuffle, this algorithm doesn’t need.

How to loop through elements of forms with JavaScript?

You can iterate named fields somehow like this:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

CSS Box Shadow Bottom Only

try this to get the box-shadow under your full control.

    <html>

    <head>
        <style> 
            div {
                width:300px;
                height:100px;
                background-color:yellow;
                box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
           }
        </style>
    </head>
    <body>
        <div>
        </div>
    </body>

    </html>

this would apply to outer box-shadow as well.

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

How to compare 2 files fast using .NET?

If you d_o_ decide you truly need a full byte-by-byte comparison (see other answers for discussion of hashing), then the easiest solution is:


• for `System.String` path names:
public static bool AreFileContentsEqual(String path1, String path2) =>
              File.ReadAllBytes(path1).SequenceEqual(File.ReadAllBytes(path2));

• for `System.IO.FileInfo` instances:
public static bool AreFileContentsEqual(FileInfo fi1, FileInfo fi2) =>
    fi1.Length == fi2.Length &&
    (fi1.Length == 0 || File.ReadAllBytes(fi1.FullName).SequenceEqual(
                        File.ReadAllBytes(fi2.FullName)));

Unlike some other posted answers, this is conclusively correct for any kind of file: binary, text, media, executable, etc., but as a full binary comparison, files that that differ only in "unimportant" ways (such as BOM, line-ending, character encoding, media metadata, whitespace, padding, source-code comments, etc.) will always be considered not-equal.

This code loads both files into memory entirely, so it should not be used for comparing truly gigantic files. Beyond that important caveat, full loading isn't really a penalty given the design of the .NET GC (because it's fundamentally optimized to keep small, short-lived allocations extremely cheap), and in fact could even be optimal when file sizes are expected to be less than 85K, because using a minimum of user code (as shown here) implies maximally delegating file performance issues to the CLR, BCL, and JIT to benefit from (e.g.) the latest design technology, system code, and adaptive runtime optimizations.

Furthermore, for such workaday scenarios, concerns about the performance of byte-by-byte comparison via LINQ enumerators (as shown here) are moot, since hitting the disk a_t_ a_l_l_ for file I/O will dwarf, by several orders of magnitude, the benefits of the various memory-comparing alternatives. For example, even though SequenceEqual does in fact give us the "optimization" of abandoning on first mismatch, this hardly matters after having already fetched the files' contents, each fully necessary to confirm the match.

cast class into another class or convert class to another

You could change your class structure to:

public class maincs : sub1
{
   public int d; 
}

public class sub1
{
   public int a;
   public int b;
   public int c;
}

Then you could keep a list of sub1 and cast some of them to mainc.

Import Excel spreadsheet columns into SQL Server database

The import wizard does offer that option. You can either use the option to write your own query for the data to import, or you can use the copy data option and use the "Edit Mappings" button to ignore columns you do not want to import.

How to control size of list-style-type disc in CSS?

try to use diffrent font-size for li and a

.farParentDiv ul li {
   list-style-type: disc;
   font-size:20px;
}

.farParentDiv ul li a {
   font-size:10px;
}

this saved me from using images

Java: Array with loop

To populate the array:

int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
    numbers[i] = i+1;
}

and then to sum it:

int ans = 0;
for (int i = 0; i < numbers.length; i++) {
    ans += numbers[i];
}

or in short, if you want the sum from 1 to n:

( n ( n +1) ) / 2

How do I set log4j level on the command line?

As part of your jvm arguments you can set -Dlog4j.configuration=file:"<FILE_PATH>". Where FILE_PATH is the path of your log4j.properties file.

Please note that as of log4j2, the new system variable to use is log4j.configurationFile and you put in the actual path to the file (i.e. without the file: prefix) and it will automatically load the factory based on the extension of the configuration file:

-Dlog4j.configurationFile=/path/to/log4jconfig.{ext}

Live search through table rows

Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.

See live demo and source code here.

http://purpledesign.in/blog/to-create-a-live-search-like-google/

Create a search box, may be an input field like this.

<input type="text" id="search" autocomplete="off">

Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.

Suppose we have the html like this. We have an input field and a list to display the results.

 <div class="icon"></div>
 <input type="text" id="search" autocomplete="off">
 <ul id="results"></ul>

We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.

Here is the JQuery.

$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    //Listen for the event
    $("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $("ul#results").fadeOut();
        $('h4#results-text').fadeOut();
    }else{
        $("ul#results").fadeIn();
        $('h4#results-text').fadeIn();
        $(this).data('timer', setTimeout(search, 100));
    };
});


// Live Search
// On Search Submit and Get Results
function search() {
    var query_value = $('input#search').val();
    $('b#search-string').html(query_value);
    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "search_st.php",
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);

            }
        });
    }return false;    
}

}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.

Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.

//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();

$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = "SELECT *
        FROM animals
        WHERE type REGEXP '^".$search_string."'
        UNION ALL SELECT *
        FROM birf
        WHERE type REGEXP '^".$search_string."'"
        ;

$result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
        $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Description
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);



            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output
        echo($output);
    }
}

Find stored procedure by name

Assuming you're in the Object Explorer Details (F7) showing the list of Stored Procedures, click the Filters button and enter the name (or partial name).

alt text

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

How to set bot's status

Bumping this all the way from 2018, sorry not sorry. But the newer users questioning how to do this need to know that game does not work anymore for this task.

bot.user.setStatus('available')
bot.user.setPresence({
    game: {
        name: 'with depression',
        type: "STREAMING",
        url: "https://www.twitch.tv/monstercat"
    }
}

does not work anymore. You will now need to do this:

bot.user.setPresence({
    status: 'online',
    activity: {
        name: 'with depression',
        type: 'STREAMING',
        url: 'https://www.twitch.tv/monstercat'
    }
})

This is referenced here as "game" is not a valid property of setPresence anymore. Read the PresenceData Documentation for more information about this.

What's a good, free serial port monitor for reverse-engineering?

Portmon from sysinternals (now MSFT) is probably the best monitor.

I haven't found a good free tool that will emulate a port and record/replay comms. The commercial ones were expensive and either so limited or so complex if you want to respond to commands that I ended up using expect and python on a second machine.

Is there a git-merge --dry-run option?

I made an alias for doing this and works like a charm, I do this:

 git config --global alias.mergetest '!f(){ git merge --no-commit --no-ff "$1"; git merge --abort; echo "Merge aborted"; };f '

Now I just call

git mergetest <branchname>

To find out if there are any conflicts.

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

Error in Python script "Expected 2D array, got 1D array instead:"?

I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

The API used to allow scalar value but now you need to give a 2D array.

Programmatically register a broadcast receiver

In your onCreate method you can register a receiver like this:

private BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState){

  // your oncreate code should be

  IntentFilter filter = new IntentFilter();
  filter.addAction("SOME_ACTION");
  filter.addAction("SOME_OTHER_ACTION");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //do something based on the intent's action
    }
  };
     registerReceiver(receiver, filter);
}

Remember to run this in the onDestroy method:

 @Override
 protected void onDestroy() {
  if (receiver != null) {
   unregisterReceiver(receiver);
   receiver = null;
  }
  super.onDestroy();
 }

Get single row result with Doctrine NativeQuery

To fetch single row

$result = $this->getEntityManager()->getConnection()->fetchAssoc($sql)

To fetch all records

$result = $this->getEntityManager()->getConnection()->fetchAll($sql)

Here you can use sql native query, all will work without any issue.

Easiest way to convert a List to a Set in Java

I agree with sepp2k, but there are some other details that might matter:

new HashSet<Foo>(myList);

will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)

An alternative that gives a sorted set is:

new TreeSet<Foo>(myList);

This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:

Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);

This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).

How to avoid warning when introducing NAs by coercion

I have slightly modified the jangorecki function for the case where we may have a variety of values that cannot be converted to a number. In my function, a template search is performed and if the template is not found, FALSE is returned.! before gperl, it means that we need those vector elements that do not match the template. The rest is similar to the as.num function. Example:

as.num.pattern <- function(x, pattern){
  stopifnot(is.character(x))
  na = !grepl(pattern, x)
  x[na] = -Inf
  x = as.numeric(x)
  x[na] = NA_real_
  x
}

as.num.pattern(c('1', '2', '3.43', 'char1', 'test2', 'other3', '23/40', '23, 54 cm.'))

[1] 1.00 2.00 3.43   NA   NA   NA   NA   NA

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Using intents to pass data between activities

I like to use this clean code to pass one value only:

startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));

This make more simple to write and understandable code.

How do I get the full url of the page I am on in C#

Here is a list I normally refer to for this type of information:

Request.ApplicationPath :   /virtual_dir
Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx
Request.FilePath :  /virtual_dir/webapp/page.aspx
Request.Path :  /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host :  localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port :  80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme :    http
Request.Url.Segments :  /
    virtual_dir/
    webapp/
    page.aspx

Hopefully you will find this useful!

How to load a xib file in a UIView

[Swift Implementation]

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

Makefile: How to correctly include header file and its directory?

This is not a question about make, it is a question about the semantic of the #include directive.

The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include directive "StdCUtil/split.h".

To fix this, just use -I.. instead of -I../StdCUtil.

How to correctly iterate through getElementsByClassName

I had a similar issue with the iteration and I landed here. Maybe someone else is also doing the same mistake I did.

In my case, the selector was not the problem at all. The problem was that I had messed up the javascript code: I had a loop and a subloop. The subloop was also using i as a counter, instead of j, so because the subloop was overriding the value of i of the main loop, this one never got to the second iteration.

var dayContainers = document.getElementsByClassName('day-container');
for(var i = 0; i < dayContainers.length; i++) { //loop of length = 2
        var thisDayDiv = dayContainers[i];
        // do whatever

        var inputs = thisDayDiv.getElementsByTagName('input');

        for(var j = 0; j < inputs.length; j++) { //loop of length = 4
            var thisInput = inputs[j];
            // do whatever

        };

    };

array_push() with key value pair

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

How can I delete using INNER JOIN with SQL Server?

Here's what I currently use for deleting or even, updating:

DELETE           w
FROM             WorkRecord2   w,
                 Employee      e
WHERE            w.EmployeeRun = e.EmployeeNo
             AND w.Company = '1' 
             AND w.Date = '2013-05-06'

What is the use of printStackTrace() method in Java?

I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:

try {
    throw new NullPointerException();
}
catch (NullPointerException e) {
    System.out.println(e);
}

try {
    throw new IOException();
}
catch (IOException e) {
    e.printStackTrace();
}
System.exit(0);

Calling println(e):

java.lang.NullPointerException

Calling e.printStackTrace():

java.io.IOException
      at package.Test.main(Test.java:74)

Best way to Bulk Insert from a C# DataTable

string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
    connection.Open();
    bulkCopy.DestinationTableName = "TableName";
    try {
        bulkCopy.WriteToServer(dataTableName);
    } catch (Exception e) {
        Console.Write(e.Message);
    }
}

Please note that the structure of the database table and the table name should be the same or it will throw an exception.

How do I copy a hash in Ruby?

Hash can create a new hash from an existing hash:

irb(main):009:0> h1 = {1 => 2}
=> {1=>2}
irb(main):010:0> h2 = Hash[h1]
=> {1=>2}
irb(main):011:0> h1.object_id
=> 2150233660
irb(main):012:0> h2.object_id
=> 2150205060

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0

Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".

Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"

public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
    var currentIPaddress = ipInfo.Address.ToString();
    var currentSubnetMask = ipInfo.IPv4Mask.ToString();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

public bool SetDHCP(string networkInterfaceName)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (isDHCPenabled)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

Succeeded installing but could not start apache 2.4 on my windows 7 system

I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45 There is another way to fix that error.

In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;

  1. Connect to MySQL as root

    mysql -u root -p
    

    then enter your MySQL root password;

  2. Select database;

    use mysql;
    
  3. Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;

  4. Create additional record for root user with Host='127.0.0.1' if it's not there;

        SET @s = CONCAT('INSERT INTO mysql.user SELECT ',
                REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME) 
                         FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
                ,"Host","'127.0.0.1'"),
                ' FROM mysql.user WHERE User="root"'); 
    
         PREPARE stmt FROM @s; 
         EXECUTE stmt;
    
  5. Additionally to that you can execute mysql_upgrade -u -p to see if everything is ok.

Remove ALL white spaces from text

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'')

How to do a newline in output

Use "\n" instead of '\n'

How come I can't remove the blue textarea border in Twitter Bootstrap?

This works 100%.

textarea:focus, input[type="text"]:focus,textarea[type="text"]:focus,   input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus,  input[type="color"]:focus, .uneditable-input:focus, .form-control:focus {  
border-color: (your color) or none;
box-shadow:(your color) or none;
outline: (your color) or none;}

Script not served by static file handler on IIS7.5

cmd -> right click -> Run as administrator

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

Custom UITableViewCell from nib in Swift

Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.

enter image description here

For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.

enter image description here

and

enter image description here

Now, in your view controller, you can delegate the tableView as you normally would, like so

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...

To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"

enter image description here enter image description here

Create your subclass with whatever outlets you need like so

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

Finally... back in your View Controller, you can load and display the entire thing like so

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}

The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.

Hope this helps!!!

CSS3 background image transition

This can be achieved with greater cross-browser support than the accepted answer by using pseudo-elements as exemplified by this answer: https://stackoverflow.com/a/19818268/2602816

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

try

_x000D_
_x000D_
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
_x000D_
<div id="date">23/05/2013</div>
_x000D_
_x000D_
_x000D_

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

How to use bootstrap-theme.css with bootstrap 3?

As stated by others, the filename bootstrap-theme.css is very confusing. I would have chosen something like bootstrap-3d.css or bootstrap-fancy.css which would be more descriptive of what it actually does. What the world sees as a "Bootstrap Theme" is a thing you can get from BootSwatch which is a totally different beast.

With that said, the effects are quite nice - gradients and shadows and such. Unfortunately this file will wreak havoc on BootSwatch Themes, so I decided to dig into what it would take to make it play nice with them.

LESS

Bootstrap-theme.css is generated from the theme.less file in the Bootstrap source. The affected elements are (as of Bootstrap v3.2.0):

  • List items
  • Buttons
  • Images
  • Dropdowns
  • Navbars
  • Alerts
  • Progress bars
  • List Groups
  • Panels
  • Wells

The theme.less file depends on:

@import "variables.less";
@import "mixins.less";

The code uses colors defined in variables.less in several places, for example:

// Give the progress background some depth
.progress {
    #gradient > .vertical(@start-color: darken(@progress-bg, 4%); @end-color: @progress-bg)
}

This why bootstrap-theme.css totally messes up BootSwatch Themes. The good news is that BootSwatch Themes are also created from variables.less files, so you can simply build a bootstrap-theme.css for your BootSwatch Theme.

Building bootstrap-theme.css

The right way to do it is to update the Theme build process, but here here is the quick and dirty way. Replace the variables.less file in the Bootstrap source with the one from your Bootswatch Theme and build it and voila you have a bootstrap-theme.css file for your Bootswatch Theme.

Building Bootstrap itself

Building Bootstrap may sound daunting, but it is actually very simple:

  1. Download the Bootstrap source code
  2. Download and install NodeJS
  3. Open a command prompt and navigate to the bootstrap source folder. Type "npm install". This will add the "node_modules" folder to the project and download all the Node stuff you need.
  4. Install grunt globally (the -g option) by typing "npm install -g grunt-cli"
  5. Rename the "dist" folder to "dist-orig" then rebuild it by typing "grunt dist". Now check that there is a new "dist" folder which contains all you need to use your custom Bootstrap build.

Done. See, that was easy, wasn't it?

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

AngularJS custom filter function

You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.

template:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

scope:

$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return item.name === criteria.name;
  };
};

How to find sum of several integers input by user using do/while, While statement or For statement

Do note that if you're adding stuff, you might always want to check that you're not going beyond the limits of int (especially in homework exercises). Also, int main () should return an int.

Using a "do .. while" loop:

#include<iostream>
using namespace std; 
int main () 
{

  int sum = 0;
  int previous = 0;
  int number;
  int numberitems;
  int count = 0;

  cout << "Enter number of items: ";
  cin >> numberitems;

  if ( numberitems <= 0 ) 
  {
    //no request to perform sum
    cout << "Quitting without summing.\n\n";
    return 0;
  }

  do
  {
    cout << "Enter number to add : ";
    cin >> number; 

    sum+=number;

    // check here that the addition didn't break anything.
    // Negative + negative should stay negative, positive + postive should stay positive
    if ((number > 0 && previous > 0 && sum < 0) || (number < 0 && previous < 0 && sum > 0))
    {
      cout << "Error: Beyond int limits !!";
      return 1;
    }

    count++;
    previous = sum;

  }
  while ( count < numberitems);

  cout<<"sum is: "<< sum<<endl;

  return 0;
} 

Set the default value in dropdownlist using jQuery

jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");

How to split an integer into an array of digits?

Splitting a single number to it's digits (as answered by all):

>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]

But, to get digits from a list of numbers:

>>> [int(d) for d in ''.join(str(x) for x in [12, 34, 5])]
[1, 2, 3, 4, 5]

So like to know, if we can do the above, more efficiently.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

When using Object.keys, the following works:

Object.keys(this)
    .forEach(key => {
      console.log(this[key as keyof MyClass]);
    });

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

how to create Socket connection in Android?

Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.

You have to create two application to test below code.

In both application's manifest file, add below permission

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

1st App code: Client Socket

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableRow
        android:id="@+id/tr_send_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="11dp">

        <EditText
            android:id="@+id/edt_send_message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:hint="Enter message"
            android:inputType="text" />

        <Button
            android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Send" />
    </TableRow>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tr_send_message"
        android:layout_marginTop="25dp"
        android:id="@+id/scrollView2">

        <TextView
            android:id="@+id/tv_reply_from_server"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>
</RelativeLayout>

MainActivity.java

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Girish Bhalerao on 5/4/2017.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mTextViewReplyFromServer;
    private EditText mEditTextSendMessage;

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

        Button buttonSend = (Button) findViewById(R.id.btn_send);

        mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
        mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);

        buttonSend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_send:
                sendMessage(mEditTextSendMessage.getText().toString());
                break;
        }
    }

    private void sendMessage(final String msg) {

        final Handler handler = new Handler();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    //Replace below IP with the IP of that device in which server socket open.
                    //If you change port then change the port number in the server side code also.
                    Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);

                    OutputStream out = s.getOutputStream();

                    PrintWriter output = new PrintWriter(out);

                    output.println(msg);
                    output.flush();
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    final String st = input.readLine();

                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            String s = mTextViewReplyFromServer.getText().toString();
                            if (st.trim().length() != 0)
                                mTextViewReplyFromServer.setText(s + "\nFrom Server : " + st);
                        }
                    });

                    output.close();
                    out.close();
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }
}

2nd App Code - Server Socket

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_stop_receiving"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="STOP Receiving data"
        android:layout_alignParentTop="true"
        android:enabled="false"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btn_stop_receiving"
        android:layout_marginTop="35dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:id="@+id/tv_data_from_client"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:id="@+id/btn_start_receiving"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="START Receiving data"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp" />
</RelativeLayout>

MainActivity.java

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Girish Bhalerao on 5/4/2017.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    final Handler handler = new Handler();

    private Button buttonStartReceiving;
    private Button buttonStopReceiving;
    private TextView textViewDataFromClient;
    private boolean end = false;

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

        buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
        buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
        textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);

        buttonStartReceiving.setOnClickListener(this);
        buttonStopReceiving.setOnClickListener(this);

    }

    private void startServerSocket() {

        Thread thread = new Thread(new Runnable() {

            private String stringData = null;

            @Override
            public void run() {

                try {

                    ServerSocket ss = new ServerSocket(9002);

                    while (!end) {
                        //Server is waiting for client here, if needed
                        Socket s = ss.accept();
                        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        PrintWriter output = new PrintWriter(s.getOutputStream());

                        stringData = input.readLine();
                        output.println("FROM SERVER - " + stringData.toUpperCase());
                        output.flush();

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        updateUI(stringData);
                        if (stringData.equalsIgnoreCase("STOP")) {
                            end = true;
                            output.close();
                            s.close();
                            break;
                        }

                        output.close();
                        s.close();
                    }
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
        thread.start();
    }

    private void updateUI(final String stringData) {

        handler.post(new Runnable() {
            @Override
            public void run() {

                String s = textViewDataFromClient.getText().toString();
                if (stringData.trim().length() != 0)
                    textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_start_receiving:

                startServerSocket();
                buttonStartReceiving.setEnabled(false);
                buttonStopReceiving.setEnabled(true);
                break;

            case R.id.btn_stop_receiving:

                //stopping server socket logic you can add yourself
                buttonStartReceiving.setEnabled(true);
                buttonStopReceiving.setEnabled(false);
                break;
        }
    }
}

How to access random item in list?

You can do:

list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()

how to extract only the year from the date in sql server 2008?

You can use year() function in sql to get the year from the specified date.

Syntax:

YEAR ( date )

For more information check here

What does the ELIFECYCLE Node.js error mean?

I had the same error code when I was running npm run build inside node docker container.

Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM

how to change color of TextinputLayout's label and edittext underline android

With the Material Components Library you can use the com.google.android.material.textfield.TextInputLayout.

You can apply a custom style to change the colors.

To change the hint color you have to use these attributes:
hintTextColor and android:textColorHint.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    <!-- The color of the label when it is collapsed and the text field is active -->
    <item name="hintTextColor">?attr/colorPrimary</item>

    <!-- The color of the label in all other text field states (such as resting and disabled) -->
    <item name="android:textColorHint">@color/selector_hint_text_color</item>
</style>

You should use a selector for the android:textColorHint. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.6" android:color="?attr/colorOnSurface"/>
</selector>

To change the bottom line color you have to use the attribute: boxStrokeColor.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    ....
    <item name="boxStrokeColor">@color/selector_stroke_color</item>
</style>

Also in this case you should use a selector. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="0.87" android:color="?attr/colorOnSurface" android:state_hovered="true"/>
  <item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>

enter image description here enter image description here

You can also apply these attributes in your layout:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
    app:boxStrokeColor="@color/selector_stroke_color"
    app:hintTextColor="?attr/colorPrimary"
    android:textColorHint="@color/selector_hint_text_color"
    ...>

Print number of keys in Redis

eval "local count = redis.call('scan', 0, 'match', 'key:*:key', 'count', 10000) if count ~= 0 then return #count[2] end " 0

eval "local count = redis.call('sscan', 'key.key:all', 0, 'match', '*', 'count', 1000000) if count ~= 0 then return #count[2] end " 0

how to check which version of nltk, scikit learn installed?

In my machine which is ubuntu 14.04 with python 2.7 installed, if I go here,

/usr/local/lib/python2.7/dist-packages/nltk/

there is a file called

VERSION.

If I do a cat VERSION it prints 3.1, which is the NLTK version installed.

*.h or *.hpp for your class definitions

Bjarne Stroustrup and Herb Sutter have a statement to this question in their C++ Core guidelines found on: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-source which is also refering to the latest changes in the standard extension (C++11, C++14, etc.)

SF.1: Use a .cpp suffix for code files and .h for interface files if your Y project doesn't already follow another convention Reason

It's a longstanding convention. But consistency is more important, so if your project uses something else, follow that. Note

This convention reflects a common use pattern: Headers are more often shared with C to compile as both C++ and C, which typically uses .h, and it's easier to name all headers .h instead of having different extensions for just those headers that are intended to be shared with C. On the other hand, implementation files are rarely shared with C and so should typically be distinguished from .c files, so it's normally best to name all C++ implementation files something else (such as .cpp).

The specific names .h and .cpp are not required (just recommended as a default) and other names are in widespread use. Examples are .hh, .C, and .cxx. Use such names equivalently. In this document, we refer to .h and .cpp > as a shorthand for header and implementation files, even though the actual extension may be different.

Your IDE (if you use one) may have strong opinions about suffices.

I'm not a big fan of this convention because if you are using a popular library like boost, your consistency is already broken and you should better use .hpp.

Resolving require paths with webpack

Webpack >2.0

See wtk's answer.

Webpack 1.0

A more straightforward way to do this would be to use resolve.root.

http://webpack.github.io/docs/configuration.html#resolve-root

resolve.root

The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

In your case:

webpack config

var path = require('path');

// ...

  resolve: {
    root: path.resolve('./mydir'),
    extensions: ['', '.js']
  }

consuming module

require('myfile')

or

require('myfile.js')

see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

Determine device (iPhone, iPod Touch) with iOS

Here's a minor update with new models:

- (NSString *) platformString{
    NSString *platform = [self platform];
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    if ([platform isEqualToString:@"i386"])   return @"iPhone Simulator";
    return platform;
}

CSS blur on background image but not on content

backdrop-filter

Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.

MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter

Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765

From the MDN documentation page:

/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

Is it possible to deserialize XML into List<T>?

I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.

Take a look (it works for me):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

So you can serialize whatever list you want! You don't need to specify the list type every time.

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use

StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64

How to create a localhost server to run an AngularJS project

"Assuming that you have nodejs installed",

mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000 in your project directory And boom! you created a server on port 3000 now go check http://localhost:3000

Note: specifying a port is not required you can simply run mini-http or mh to start the server

Call PHP function from Twig template

Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

JavaScript: Check if mouse button down?

Using jQuery, the following solution handles even the "drag off the page then release case".

$(document).mousedown(function(e) {
    mouseDown = true;
}).mouseup(function(e) {
    mouseDown = false;
}).mouseleave(function(e) {
    mouseDown = false;
});

I don't know how it handles multiple mouse buttons. If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.

Remove blue border from css custom-styled button in Chrome

Simply write outline:none;. No need to use pseudo element focus

Send HTML in email via PHP

Use PHPMailer,

To send HTML mail you have to set $mail->isHTML() only, and you can set your body with HTML tags

Here is a well written tutorial :

rohitashv.wordpress.com/2013/01/19/how-to-send-mail-using-php/

How to implement OnFragmentInteractionListener

Just an addendum:

OnFragmentInteractionListener handle communication between Activity and Fragment using an interface (OnFragmentInteractionListener) and is created by default by Android Studio, but if you dont need to communicate with your activity, you can just get ride of it.

The goal is that you can attach your fragment to multiple activities and still reuse the same communication approach (Every activity could have its own OnFragmentInteractionListener for each fragment).

But and if im sure my fragment will be attached to only one type of activity and i want to communicate with that activity?

Then, if you dont want to use OnFragmentInteractionListener because of its verbosity, you can access your activity methods using:

((MyActivityClass) getActivity()).someMethod()

What's the difference between "Layers" and "Tiers"?

I've found a definition that says that Layers are a logical separation and tiers are a physical separation.

Waiting until two async blocks are executed before starting another block

Use dispatch groups: see here for an example, "Waiting on Groups of Queued Tasks" in the "Dispatch Queues" chapter of Apple's iOS Developer Library's Concurrency Programming Guide

Your example could look something like this:

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block1
    NSLog(@"Block1");
    [NSThread sleepForTimeInterval:5.0];
    NSLog(@"Block1 End");
});


dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block2
    NSLog(@"Block2");
    [NSThread sleepForTimeInterval:8.0];
    NSLog(@"Block2 End");
});

dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block3
    NSLog(@"Block3");
});

// only for non-ARC projects, handled automatically in ARC-enabled projects.
dispatch_release(group);

and could produce output like this:

2012-08-11 16:10:18.049 Dispatch[11858:1e03] Block1
2012-08-11 16:10:18.052 Dispatch[11858:1d03] Block2
2012-08-11 16:10:23.051 Dispatch[11858:1e03] Block1 End
2012-08-11 16:10:26.053 Dispatch[11858:1d03] Block2 End
2012-08-11 16:10:26.054 Dispatch[11858:1d03] Block3

Forcing anti-aliasing using css: Is this a myth?

Using an opacity setting of 99% (through the DXTransform filters) actually forces Internet Explorer to turn off ClearType, at least in Version 7. Source

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

Try adding root path.

app.get('/', function(req, res) {
    res.sendFile('index.html', { root: __dirname });
});

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

Java generics - why is "extends T" allowed but not "implements T"?

Here is a more involved example of where extends is allowed and possibly what you want:

public class A<T1 extends Comparable<T1>>

Creating a selector from a method name with parameters

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);

-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here

-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

A variable modified inside a while loop is not remembered

UPDATED#2

Explanation is in Blue Moons's answer.

Alternative solutions:

Eliminate echo

while read line; do
...
done <<EOT
first line
second line
third line
EOT

Add the echo inside the here-is-the-document

while read line; do
...
done <<EOT
$(echo -e $lines)
EOT

Run echo in background:

coproc echo -e $lines
while read -u ${COPROC[0]} line; do 
...
done

Redirect to a file handle explicitly (Mind the space in < <!):

exec 3< <(echo -e  $lines)
while read -u 3 line; do
...
done

Or just redirect to the stdin:

while read line; do
...
done < <(echo -e  $lines)

And one for chepner (eliminating echo):

arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
...
}

Variable $lines can be converted to an array without starting a new sub-shell. The characters \ and n has to be converted to some character (e.g. a real new line character) and use the IFS (Internal Field Separator) variable to split the string into array elements. This can be done like:

lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr

Result is

first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")

JSON Array iteration in Android/Java

I have done it two different ways,

1.) make a Map

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i=0; i<settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) make a JSONArray of names

    JSONArray names = json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i=0; i<values.length(); i++){
        if (names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if (names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if (names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if (names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if (names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if (names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }

if statement checks for null but still throws a NullPointerException

You can use StringUtils:

import org.apache.commons.lang3.StringUtils;

if (StringUtils.isBlank(str)) {

System.out.println("String is empty");

} else { 

System.out.println("String is not empty");

}

Have a look here also: StringUtils.isBlank() vs String.isEmpty()

isBlank examples:

StringUtils.isBlank(null)      = true
StringUtils.isBlank("")        = true  
StringUtils.isBlank(" ")       = true  
StringUtils.isBlank("bob")     = false  
StringUtils.isBlank("  bob  ") = false

SQL search multiple values in same field

This has been partially answered here: MySQL Like multiple values

I advise against

$search = explode( ' ', $search );

and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;

$search = str_replace('"', "''", search );

But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.

function makeSQL_search_pattern($search) {
    search_pattern = false;
    //escape the special regex chars
    $search = str_replace('"', "''", $search);
    $search = str_replace('^', "\\^", $search);
    $search = str_replace('$', "\\$", $search);
    $search = str_replace('.', "\\.", $search);
    $search = str_replace('[', "\\[", $search);
    $search = str_replace(']', "\\]", $search);
    $search = str_replace('|', "\\|", $search);
    $search = str_replace('*', "\\*", $search);
    $search = str_replace('+', "\\+", $search);
    $search = str_replace('{', "\\{", $search);
    $search = str_replace('}', "\\}", $search);
    $search = explode(" ", $search);
    for ($i = 0; $i < count($search); $i++) {
        if ($i > 0 && $i < count($search) ) {
           $search_pattern .= "|";
        }
        $search_pattern .= $search[$i];
    }
    return search_pattern;
}

$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();

I have not tested this code, but this is what I would do in your case. I hope this helps.

How to exclude rows that don't join with another table?

If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT. In this case, column names can be different as well but data type should be same.

Example:

select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable

compilation error: identifier expected

You have not defined a method around your code.

import java.io.*;

public class details
{
    public static void main( String[] args )
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

How to call a method daily, at specific time, in C#?

Whenever I build applications that require such functionality, I always use the Windows Task Scheduler through a simple .NET library that I found.

Please see my answer to a similar question for some sample code and more explanation.

How can I check if a single character appears in a string?

I'm not sure what the original poster is asking exactly. Since indexOf(...) and contains(...) both probably use loops internally, perhaps he's looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

The other is far less elegant, but completeness...:

/**
 * Works for strings of up to 5 characters
 */
public boolean containsChar(String s, char search) {
    if (s.length() > 5) throw IllegalArgumentException();

    try {
        if (s.charAt(0) == search) return true;
        if (s.charAt(1) == search) return true;
        if (s.charAt(2) == search) return true;
        if (s.charAt(3) == search) return true;
        if (s.charAt(4) == search) return true;
    } catch (IndexOutOfBoundsException e) {
        // this should never happen...
        return false;
    }
    return false;
}

The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you're concerned that that length() uses a loop.