Programs & Examples On #Eclipse cdt

CDT is an Eclipse component that provides an IDE for C and C++. Use this tag for questions which are specific to CDT.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

The video link below illustrate these steps in more detail:

  1. Create Empty project
  2. Choose linux Gcc compiler
  3. Right click on project choose " source folder "
  4. Name it " src "
  5. Right click on src folder choose " source file "
  6. Start coding
  7. Save project
  8. Build project
  9. Run project

https://www.youtube.com/watch?v=wtyBvagV-_A

Eclipse CDT: Symbol 'cout' could not be resolved

I tried the marked solution here first. It worked but it is kind hacky, and you need to redo it every time you update the gcc. I finally find a better solution by doing the followings:

  1. Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc.
  2. Providers -> CDT GCC built-in compiler settings
  3. Uncheck Use global provider shared between projects (you can also modify the global provider if it fits your need)
  4. In Command to get compiler specs, add -std=c++11 at the end
  5. Index->Rebuild

Voila, easy and simple. Hopefully this helps.

Note: I am on Kepler. I am not sure if this works on earlier Eclipse.

How to see my Eclipse version?

Help -> About Eclipse Platform

For Eclipse Mars - you can check Eclipse -> About Eclipse or Help -> Installation Details, then you should see the version:

enter image description here

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message when trying "hello world" like things with Qt. The problems went away by correctly running the qt moc (meta object compiler) and compiling+including these moc-generated files correctly.

Work on a remote project with Eclipse via SSH

Try the Remote System Explorer (RSE). It's a set of plug-ins to do exactly what you want.

RSE may already be included in your current Eclipse installation. To check in Eclipse Indigo go to Window > Open Perspective > Other... and choose Remote System Explorer from the Open Perspective dialog to open the RSE perspective.

To create an SSH remote project from the RSE perspective in Eclipse:

  1. Define a new connection and choose SSH Only from the Select Remote System Type screen in the New Connection dialog.
  2. Enter the connection information then choose Finish.
  3. Connect to the new host. (Assumes SSH keys are already setup.)
  4. Once connected, drill down into the host's Sftp Files, choose a folder and select Create Remote Project from the item's context menu. (Wait as the remote project is created.)

If done correctly, there should now be a new remote project accessible from the Project Explorer and other perspectives within eclipse. With the SSH connection set-up correctly passwords can be made an optional part of the normal SSH authentication process. A remote project with Eclipse via SSH is now created.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

How to force Eclipse to ask for default workspace?

Starting eclipse with eclipse -clean did wonders for me.

undefined reference to `WinMain@16'

My situation was that I did not have a main function.

Launch Failed. Binary not found. CDT on Eclipse Helios

You must build an executable file before you can run it. So if you don't “BUILD” your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.

So basically right click on the Project -> Build Project -> Run As Local C/C++ Application should do the trick

Eclipse CDT: no rule to make target all

Sometimes if you are making a target via make files double check that all c files are named correctly with correct file structure.

How to enable C++11/C++0x support in Eclipse CDT?

I found this article in the Eclipse forum, just followed those steps and it works for me. I am using Eclipse Indigo 20110615-0604 on Windows with a Cygwin setup.

  • Make a new C++ project
  • Default options for everything
  • Once created, right-click the project and go to "Properties"
  • C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put -std=c++0x (or for newer compiler version -std=c++11 at the end . ... instead of GCC C++ Compiler I have also Cygwin compiler
  • C/C++ General -> Paths and Symbols -> Symbols -> GNU C++. Click "Add..." and paste __GXX_EXPERIMENTAL_CXX0X__ (ensure to append and prepend two underscores) into "Name" and leave "Value" blank.
  • Hit Apply, do whatever it asks you to do, then hit OK.

There is a description of this in the Eclipse FAQ now as well: Eclipse FAQ/C++11 Features.

Eclipse image setting

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Trying with a different version of gcc worked for me - gcc 4.9 in my case.

Eclipse C++: Symbol 'std' could not be resolved

I do not know whether you have solved this problem but I want to post my solution for those might ran into the same problem.

  1. First, make sure that you have the "Includes" folder in your Project Explorer. If you do not have it, go to second step. If you have it, go to third step.

  2. Second, Window -> Preferences-> C/C++- > Build >Environment: Create two environment variables:

    a) Name: C_INCLUDE_PATH Value: /usr/include

    b) Name: CPLUS_INCLUDE_PATH Value: /usr/include/c++

Go to Cygwin/usr/include/, if you cannot find folder "c++", copy it from \cygwin\lib\gcc\i686-pc-cygwin\X.X.X\include and Then restart your Eclipse.

  1. Third, Right Click your project in Project Explorer -> Properties -> C/C++ General -> Paths and Symbols -> Includes -> Languages:GNU C++ If you can find some C++ folders in the "Include directories" then click Apply and OK. Change a bit your codes, and save it.

You will find there will be not symbol could not be resolved problems.

I documented my solution, hoping someone might get benefits.

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

How to toggle font awesome icon on click?

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

Simple PHP form: Attachment to email (code golf)

A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:

$attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); 

where $tmp_file = $_FILES['userfile']['tmp_name'];

and send it as an attachment like the rest of the example.

All in one file / self contained:

<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>

I think its a quick exercise to get what you need working based on the above two available examples.

P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.

Update index after sorting data-frame

You can set new indices by using set_index:

df2.set_index(np.arange(len(df2.index)))

Output:

   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

Convert int to a bit array in .NET

To convert the int 'x'

int x = 3;

One way, by manipulation on the int :

string s = Convert.ToString(x, 2); //Convert to binary in a string

int[] bits= s.PadLeft(8, '0') // Add 0's from left
             .Select(c => int.Parse(c.ToString())) // convert each char to int
             .ToArray(); // Convert IEnumerable from select to Array

Alternatively, by using the BitArray class-

BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();

Eclipse error ... cannot be resolved to a type

Project -> Build Path -> Configure Build Path
Select Java Build path on the left menu, and select "Source"
 click on Excluded and then Include(All) and then click OK
    Cause : The issue might because u might have deleted the CLASS files 
 or dependencies on the project

For maven users:

Right click on the project

Maven

Update Project

How to change the button text of <input type="file" />?

You can simply add some css trick. you don't need javascript or more input files and i keep existing value attribute. you need to add only css. you can try this solution.

_x000D_
_x000D_
.btn-file-upload{_x000D_
     width: 187px;_x000D_
     position:relative;_x000D_
 }_x000D_
_x000D_
.btn-file-upload:after{_x000D_
    content:  attr(value);_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;    _x000D_
    width: 48%;_x000D_
    background: #795548;_x000D_
    color: white;_x000D_
    border-radius: 2px;_x000D_
    text-align: center;_x000D_
    font-size: 12px;_x000D_
    line-height: 2;_x000D_
 }
_x000D_
<input type="file" class="btn-file-upload" value="Uploadfile" />
_x000D_
_x000D_
_x000D_

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

Checking if a string can be converted to float in Python

TL;DR:

  • If your input is mostly strings that can be converted to floats, the try: except: method is the best native Python method.
  • If your input is mostly strings that cannot be converted to floats, regular expressions or the partition method will be better.
  • If you are 1) unsure of your input or need more speed and 2) don't mind and can install a third-party C-extension, fastnumbers works very well.

There is another method available via a third-party module called fastnumbers (disclosure, I am the author); it provides a function called isfloat. I have taken the unittest example outlined by Jacob Gabrielson in this answer, but added the fastnumbers.isfloat method. I should also note that Jacob's example did not do justice to the regex option because most of the time in that example was spent in global lookups because of the dot operator... I have modified that function to give a fairer comparison to try: except:.


def is_float_try(str):
    try:
        float(str)
        return True
    except ValueError:
        return False

import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$").match
def is_float_re(str):
    return True if _float_regexp(str) else False

def is_float_partition(element):
    partition=element.partition('.')
    if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
        return True
    else:
        return False

from fastnumbers import isfloat


if __name__ == '__main__':
    import unittest
    import timeit

    class ConvertTests(unittest.TestCase):

        def test_re_perf(self):
            print
            print 're sad:', timeit.Timer('ttest.is_float_re("12.2x")', "import ttest").timeit()
            print 're happy:', timeit.Timer('ttest.is_float_re("12.2")', "import ttest").timeit()

        def test_try_perf(self):
            print
            print 'try sad:', timeit.Timer('ttest.is_float_try("12.2x")', "import ttest").timeit()
            print 'try happy:', timeit.Timer('ttest.is_float_try("12.2")', "import ttest").timeit()

        def test_fn_perf(self):
            print
            print 'fn sad:', timeit.Timer('ttest.isfloat("12.2x")', "import ttest").timeit()
            print 'fn happy:', timeit.Timer('ttest.isfloat("12.2")', "import ttest").timeit()


        def test_part_perf(self):
            print
            print 'part sad:', timeit.Timer('ttest.is_float_partition("12.2x")', "import ttest").timeit()
            print 'part happy:', timeit.Timer('ttest.is_float_partition("12.2")', "import ttest").timeit()

    unittest.main()

On my machine, the output is:

fn sad: 0.220988988876
fn happy: 0.212214946747
.
part sad: 1.2219619751
part happy: 0.754667043686
.
re sad: 1.50515985489
re happy: 1.01107215881
.
try sad: 2.40243887901
try happy: 0.425730228424
.
----------------------------------------------------------------------
Ran 4 tests in 7.761s

OK

As you can see, regex is actually not as bad as it originally seemed, and if you have a real need for speed, the fastnumbers method is quite good.

Using different Web.config in development and production environment

This is one of the huge benefits of using the machine.config. At my last job, we had development, test and production environments. We could use the machine.config for things like connection strings (to the appropriate, dev/test/prod SQL machine).

This may not be a solution for you if you don't have access to the actual production machine (like, if you were using a hosting company on a shared host).

compare differences between two tables in mysql

 select t1.user_id,t2.user_id 
 from t1 left join t2 ON t1.user_id = t2.user_id 
 and t1.username=t2.username 
 and t1.first_name=t2.first_name 
 and t1.last_name=t2.last_name

try this. This will compare your table and find all matching pairs, if any mismatch return NULL on left.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

How do I select a random value from an enumeration?

Adapted as a Random class extension:

public static class RandomExtensions
{   
    public static T NextEnum<T>(this Random random)
    {
        var values = Enum.GetValues(typeof(T));
        return (T)values.GetValue(random.Next(values.Length));
    }
}

Example of usage:

var random = new Random();
var myEnumRandom = random.NextEnum<MyEnum>();

Eclipse can't find / load main class

I had the same problem.I solved with following command maven:

mvn eclipse:eclipse -Dwtpversion=2.0

PS: My project is WTP plugin

Making HTML page zoom by default

Solved it as follows,

in CSS

#my{
zoom: 100%;
}

Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.

Though this is not the best way to do it, there is another effective solution

Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.

Style input element to fill remaining width of its container

you can try this :

_x000D_
_x000D_
div#panel {_x000D_
    border:solid;_x000D_
    width:500px;_x000D_
    height:300px;_x000D_
}_x000D_
div#content {_x000D_
 height:90%;_x000D_
 background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
 width:100%;_x000D_
 height:10%;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
 -webkit-box-sizing: border-box;_x000D_
       -moz-box-sizing: border-box;_x000D_
            box-sizing: border-box;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
  <div id="content"></div>_x000D_
  <input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

String.Format like functionality in T-SQL?

One more idea.

Although this is not a universal solution - it is simple and works, at least for me :)

For one placeholder {0}:

create function dbo.Format1
(
    @String  nvarchar(4000),
    @Param0  sql_variant
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';

    return replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));    
end

For two placeholders {0} and {1}:

create function dbo.Format2
(
    @String  nvarchar(4000),
    @Param0  sql_variant,
    @Param1  sql_variant
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';

    set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
       return     replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000))); 
end

For three placeholders {0}, {1} and {2}:

create function dbo.Format3
(
    @String  nvarchar(4000),
    @Param0  sql_variant,
    @Param1  sql_variant,
    @Param2  sql_variant
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';

    set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
    set @String = replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000))); 
       return     replace(@String, N'{2}', cast(isnull(@Param2, @Null) as nvarchar(4000)));
end

and so on...

Such an approach allows us to use these functions in SELECT statement and with parameters of nvarchar, number, bit and datetime datatypes.

For example:

declare @Param0 nvarchar(10) = N'IPSUM' ,
        @Param1 int          = 1234567  ,
        @Param2 datetime2(0) = getdate();

select dbo.Format3(N'Lorem {0} dolor, {1} elit at {2}', @Param0, @Param1, @Param2);  

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Java Security: Illegal key size or default parameters?

There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:

Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

Usage of @see in JavaDoc?

A good example of a situation when @see can be useful would be implementing or overriding an interface/abstract class method. The declaration would have javadoc section detailing the method and the overridden/implemented method could use a @see tag, referring to the base one.

Related question: Writing proper javadoc with @see?

Java SE documentation: @see

C# - using List<T>.Find() with custom objects

It's easy, just use list.Find(x => x.name == "stringNameOfObjectToFind");

How does DateTime.Now.Ticks exactly work?

I had a similar problem.

I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.

About half-way down is an answer by "Robert P" with some extension functions I found useful.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

Take the content of a list and append it to another list

You can simply concatnate two lists, e.g:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


UITableView load more when scrolling to bottom like Facebook application

Just wanna share this approach:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"%@", [[YourTableView indexPathsForVisibleRows] lastObject]);
    [self estimatedTotalData];
}

- (void)estimatedTotalData
{
    long currentRow = ((NSIndexPath *)[[YourTableView indexPathsForVisibleRows] lastObject]).row;

    long estimateDataCount = 25;

    while (currentRow > estimateDataCount)
    {
        estimateDataCount+=25;
    }

    dataLimit = estimateDataCount;

    if (dataLimit == currentRow+1)
    {
        dataLimit+=25;
    }

    NSLog(@"dataLimit :%ld", dataLimit);

    [self requestForData];

    // this answers the question..
    //
    if(YourDataSource.count-1 == currentRow)
    {
        NSLog(@"LAST ROW"); //loadMore data
    }
}

NSLog(...); output would be something like:

<NSIndexPath: 0xc0000000002e0016> {length = 2, path = 0 - 92}
dataLimit :100
<NSIndexPath: 0xc000000000298016> {length = 2, path = 0 - 83}
dataLimit :100
<NSIndexPath: 0xc000000000278016> {length = 2, path = 0 - 79}
dataLimit :100
<NSIndexPath: 0xc000000000238016> {length = 2, path = 0 - 71}
dataLimit :75
<NSIndexPath: 0xc0000000001d8016> {length = 2, path = 0 - 59}
dataLimit :75
<NSIndexPath: 0xc0000000001c0016> {length = 2, path = 0 - 56}
dataLimit :75
<NSIndexPath: 0xc000000000138016> {length = 2, path = 0 - 39}
dataLimit :50
<NSIndexPath: 0xc000000000120016> {length = 2, path = 0 - 36}
dataLimit :50
<NSIndexPath: 0xc000000000008016> {length = 2, path = 0 - 1}
dataLimit :25
<NSIndexPath: 0xc000000000008016> {length = 2, path = 0 - 1}
dataLimit :25

This is good for displaying data stored locally. Initially I declare the dataLimit to 25, that means uitableview will have 0-24 (initially).

If the user scrolled to the bottom and the last cell is visible dataLimit will be added with 25...

Note: This is more like a UITableView data paging, :)

I/O error(socket error): [Errno 111] Connection refused

I previously had this problem with my EC2 instance (I was serving couchdb to serve resources -- am considering Amazon's S3 for the future).

One thing to check (assuming Ec2) is that the couchdb port is added to your open ports within your security policy.

I specifically encountered

"[Errno 111] Connection refused"

over EC2 when the instance was stopped and started. The problem seems to be a pidfile race. The solution for me was killing couchdb (entirely and properly) via:

pkill -f couchdb

and then restarting with:

/etc/init.d/couchdb restart

Permutations between two lists of unequal length

May be simpler than the simplest one above:

>>> a = ["foo", "bar"]
>>> b = [1, 2, 3]
>>> [(x,y) for x in a for y in b]  # for a list
[('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
>>> ((x,y) for x in a for y in b)  # for a generator if you worry about memory or time complexity.
<generator object <genexpr> at 0x1048de850>

without any import

What's the difference between HEAD^ and HEAD~ in Git?

The difference between HEAD^ and HEAD~ is well described by the illustration (by Jon Loeliger) found on http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html.

This documentation can be a bit obscure to beginners so I've reproduced that illustration below:

G   H   I   J
 \ /     \ /
  D   E   F
   \  |  / \
    \ | /   |
     \|/    |
      B     C
       \   /
        \ /
         A
A =      = A^0
B = A^   = A^1     = A~1
C = A^2
D = A^^  = A^1^1   = A~2
E = B^2  = A^^2
F = B^3  = A^^3
G = A^^^ = A^1^1^1 = A~3
H = D^2  = B^^2    = A^^^2  = A~2^2
I = F^   = B^3^    = A^^3^
J = F^2  = B^3^2   = A^^3^2

jQuery.each - Getting li elements inside an ul

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

How do I vertically align text in a paragraph?

User vertical-align: middle; along with text-align: center property

<!DOCTYPE html>
<html>
<head>
<style>
.center {
  border: 3px solid green;
  text-align: center;
}

.center p {
  display: inline-block;
  vertical-align: middle;
}
</style>
</head>
<body>

<h2>Centering</h2>
<p>In this example, we use the line-height property with a value that is equal to the height property to center the div element:</p>

<div class="center">
  <p>I am vertically and horizontally centered.</p>
</div>

</body>
</html>

Truncate Two decimal places without rounding

Here is an extension method:

public static decimal? TruncateDecimalPlaces(this decimal? value, int places)
    {
        if (value == null)
        {
            return null;
        }

        return Math.Floor((decimal)value * (decimal)Math.Pow(10, places)) / (decimal)Math.Pow(10, places);

    } // end

How to change Navigation Bar color in iOS 7?

self.navigationBar.barTintColor = [UIColor blueColor];
self.navigationBar.tintColor = [UIColor whiteColor];
self.navigationBar.translucent = NO;

// *barTintColor* sets the background color
// *tintColor* sets the buttons color

RegEx for matching "A-Z, a-z, 0-9, _" and "."

regex: /^[a-zA-Z0-9_.]$/i

This works

Android get image from gallery into ImageView

import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView);
    }

    public void btn_gallery(View view) {

        Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);

        startActivityForResult(intent,100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==100 && resultCode==RESULT_OK)
        {
            Uri uri = data.getData();
            img.setImageURI(uri);
        }
    }
}

How can I check if my python object is a number?

That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

TypeError: a bytes-like object is required, not 'str'

A bit of encoding can solve this:

Client Side:

message = input("->")
clientSocket.sendto(message.encode('utf-8'), (address, port))

Server Side:

data = s.recv(1024)
modifiedMessage, serverAddress = clientSocket.recvfrom(message.decode('utf-8'))

TypeError: coercing to Unicode: need string or buffer

You're trying to pass file objects as filenames. Try using

infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'

at the top of your code.

(Not only does the doubled usage of open() cause that problem with trying to open the file again, it also means that infile and outfile are never closed during the course of execution, though they'll probably get closed once the program ends.)

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

How to simulate key presses or a click with JavaScript?

you can raise the click event on an element by doing

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.click();

Example here

Using 'make' on OS X

In addition, if you have migrated your user files and applications from one mac to another, you need to install Apple Developer Tools all over again. The migration assistant does not account for the developer tools installation.

How to read xml file contents in jQuery and display in html elements?

Simply you can read XML file as dataType: "xml", it will retuen xml object already parsed. you can use it as jquery object and find anything or loop throw it…etc.

$(document).ready(function(){
   $.ajax({
    type: "GET" ,
    url: "sampleXML.xml" ,
    dataType: "xml" ,
    success: function(xml) {

    //var xmlDoc = $.parseXML( xml );   <------------------this line
    //if single item
    var person = $(xml).find('person').text();  

    //but if it's multible items then loop
    $(xml).find('person').each(function(){
     $("#temp").append('<li>' + $(this).text() + '</li>');  
    }); 
    }       
});
});

jQuery docs for parseXML

How to implement "select all" check box in HTML?

To make it deselect:

$('#select_all').click(function(event) {
  if(this.checked) {
      // Iterate each checkbox
      $(':checkbox').each(function() {
          this.checked = true;
      });
  }
  else {
    $(':checkbox').each(function() {
          this.checked = false;
      });
  }
});

Sorting an array in C?

I'd like to make some changes: In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
   int int_a = * ( (int*) a );
   int int_b = * ( (int*) b );

   // an easy expression for comparing
   return (int_a > int_b) - (int_a < int_b);
}

qsort( a, 6, sizeof(int), compare )

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

Meaning of *& and **& in C++

Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"

Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.

Difference between == and === in JavaScript

=== and !== are strict comparison operators:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]

Comparison Operators - MDC

How to convert a string from uppercase to lowercase in Bash?

If you are using bash 4 you can use the following approach:

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

Use only one , or ^ to make the first letter lowercase or uppercase.

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I had trouble for a number of days and was hacking around. This link proved out to be extremely helpful for me. It helped me to do a successful upgrade of the SSL on MAC OS X 9.

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

How to update gradle in android studio?

after release of android studio v 3.0(stable), It will show popup, If gradle update is available

OR

Manually, just change version of gradle in top-level(project-level) build.gradle file to latest,

   buildscript {
      ...
      dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
      }
    }

check below chart

The Android Gradle Plugin and Gradle

 Android Gradle Plugin            Requires Gradle
 1.0.0 - 1.1.3                    2.2.1 - 2.3
 1.2.0 - 1.3.1                    2.2.1 - 2.9
 1.5.0   2.2.1+                   2.2.1 - 2.13
 2.0.0 - 2.1.2                    2.10  - 2.13
 2.1.3 - 2.2.3                    2.14.1+
 2.3.0+                           3.3+
 3.0.0+                           4.1+    
 3.1.0+                           4.4+    
 3.2.0 - 3.2.1                    4.6+    
 3.3.0 - 3.3.1                    4.10.1+ 
 3.4.0 - 3.4.1                    5.1.1+
 3.5.0                            5.4.1+

check gradle revisions

JFrame background image

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Take a look at Performing Custom Painting and 2D Graphics for more details

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

What is the difference between static func and class func in Swift?

This is called type methods, and are called with dot syntax, like instance methods. However, you call type methods on the type, not on an instance of that type. Here’s how you call a type method on a class called SomeClass:

Remove all special characters, punctuation and spaces from string

import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)

and you shall see your result as

'askhnlaskdjalsdk

How to create timer events using C++ 11?

Use RxCpp,

std::cout << "Waiting..." << std::endl;
auto values = rxcpp::observable<>::timer<>(std::chrono::seconds(1));
values.subscribe([](int v) {std::cout << "Called after 1s." << std::endl;});

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Firstly you can find duplicate rows and find count of rows is used how many times and order it by number like this;

_x000D_
_x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

after that create a table and insert result to it.

_x000D_
_x000D_
create table CopyTable _x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

Finally, delete dublicate rows.No is start 0. Except fist number of each group delete all dublicate rows.

_x000D_
_x000D_
delete from  CopyTable where No!= 0;
_x000D_
_x000D_
_x000D_

Error inflating class android.support.design.widget.NavigationView

Well So I was trying to fix this error. And none worked for me. I was not able to figure out solution. Scenario:

I was just going to made a Navigation Drawer Project inside Android Studio 2.1.2 And when I try to change the default Android icon in nav_header_main.xml I was getting some weird errors. I figured out that I was droping my PNG logo into the ...\app\src\main\res\drawable-21. When I try to put my PNG logo in ...\app\src\main\res\drawable bam! All weird errors go away.

Following are some of stack trace when I was putting PNG into drawable-21 folder:

08-17 17:29:56.237 6644-6678/myAppName  E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.Restarter.getActivities
08-17 17:30:01.674 6644-6644/myAppName E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{myAppName.MainActivity}: android.view.InflateException: Binary XML file line #16: Error inflating class <unknown>
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
                                                                             at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956)
                                                                             at android.app.ActivityThread.access$700(ActivityThread.java:169)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                             at android.os.Looper.loop(Looper.java:194)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5433)
                                                                             at java.lang.reflect.Method.invokeNative(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:525)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
                                                                             at dalvik.system.NativeStart.main(Native Method)
                                                                          Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class <unknown>
                                                                             at android.view.LayoutInflater.createView(LayoutInflater.java:613)
                                                                             at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
                                                                             at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                                             at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                             at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                             at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22)
                                                                             at android.app.Activity.performCreate(Activity.java:5179)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
                                                                             at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956) 
                                                                             at android.app.ActivityThread.access$700(ActivityThread.java:169) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:107) 
                                                                             at android.os.Looper.loop(Looper.java:194) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5433) 
                                                                             at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                             at java.lang.reflect.Method.invoke(Method.java:525) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691) 
                                                                             at dalvik.system.NativeStart.main(Native Method) 
                                                                          Caused by: java.lang.reflect.InvocationTargetException
                                                                             at java.lang.reflect.Constructor.constructNative(Native Method)
                                                                             at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
                                                                             at android.view.LayoutInflater.createView(LayoutInflater.java:587)
                                                                             at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) 
                                                                             at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
                                                                             at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280) 
                                                                             at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
                                                                             at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22) 
                                                                             at android.app.Activity.performCreate(Activity.java:5179) 
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146) 
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336) 
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
                                                                             at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956) 
                                                                             at android.app.ActivityThread.access$700(ActivityThread.java:169) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:107) 
                                                                             at android.os.Looper.loop(Looper.java:194) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5433) 
                                                                             at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                             at java.lang.reflect.Method.invoke(Method.java:525) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691) 
                                                                             at dalvik.system.NativeStart.main(Native Method) 
                                                                          Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class ImageView
                                                                             at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                                             at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.support.design.internal.NavigationMenuPresenter.inflateHeaderView(NavigationMenuPresenter.java:189)
at android.support.design.widget.NavigationView.inflateHeaderView(NavigationView.java:262)
at android.support.design.widget.NavigationView.<init>(NavigationView.java:173)
at android.support.design.widget.NavigationView.<init>(NavigationView.java:95)
at java.lang.reflect.Constructor.constructNative(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 
at android.view.LayoutInflater.createView(LayoutInflater.java:587) 
                                                                             at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) 
                                                                             at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
                                                                             at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
                                                                             at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280) 
                                                                             at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
                                                                             at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22) 
                                                                             at android.app.Activity.performCreate(Activity.java:5179) 
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146) 
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336) 
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
                                                                             at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956) 
                                                                             at android.app.ActivityThread.access$700(ActivityThread.java:169) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:107) 
                                                                             at android.os.Looper.loop(Looper.java:194) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5433) 
                                                                             at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                             at java.lang.reflect.Method.invoke(Method.java:525) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691) 
                                                                             at dalvik.system.NativeStart.main(Native Method) 
                                                                          Caused by: java.lang.NullPointerException
                                                                             at android.content.res.ResourcesEx.getThemeDrawable(ResourcesEx.java:459)
                                                                             at android.content.res.ResourcesEx.loadDrawable(ResourcesEx.java:435)
                                                                             at android.content.res.TypedArray.getDrawable(TypedArray.java:609)
                                                                             at android.widget.ImageView.<init>(ImageView.java:120)
                                                                             at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:57)
                                                                             at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:53)
                                                                             at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                                             at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:980)
                                                                             at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1039)
                                                                             at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                                            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:

As you can see the above Stack Trace include:

android.support.design.widget.NavigationView.inflateHeaderView(NavigationView.java:262) at android.support.design.widget.NavigationView.(NavigationView.java:173) at android.support.design.widget.NavigationView.(NavigationView.java:95)

How to disable an Android button?

WRONG WAY IN LISTENER TO USE VARIABLE INSTEAD OF PARAMETER!!!

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

RIGHT WAY:

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        /** check given view  by assertion or cast as u wish */
        if(v instance of Button) {

            /** cast */
            Button button = (Button) v;

            /** we can perform some check up */
            if(button.getId() == EXPECTED_ID) {

                /** disable view */
                button.setEnabled(false)            
                button.setClickable(false); 
            }

        } else {

             /** you can for example find desired view by root view  */
             Button bt = (Button) v.getRootView().findViewById(R.id.btId);

             /*check for button */
             if(bt!=null) {

                 /** disable button view */
                 ...
             } else {
                 /** according to @jeroen-bollen remark
                   * we made assumption that we expected a view
                   * of type button here in other any case  
                   */
                  throw new IllegalArgumentException("Wrong argument: " +
                         "View passed to method is not a Button type!");
             }
          }
       }
    });

EDIT: In reply to @jeroen-bollen

 View.OnClickListener 

is Interface definition for a callback to be invoked when a view is clicked.

with method definition

void onClick(View v);

when the view is clicked the View class object makes callback to method onClick() sending as parameter itself, so null view parameter should not occur if it does it's an Assertion Error it could happen for example when View object class was destroyed in meanwhile (for example collected by GC) or method was tampered due to hack

little about instanceof & null

JLS / 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException.

Otherwise the result is false.


three words from the Author

IF U ASK WHY ?

MOSTLY TO AVOID NullPointerException

Little more code will save your time on later bug tracking in your code & reduces the occurrence of abnomalies.

consider following example:

View.OnClickListener listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)  

Reading an Excel file in PHP

I have used following code to read "xls and xlsx" :

    include 'PHPExcel/IOFactory.php';

    $location='sample-excel-files.xlsx';

    $objPHPExcel = PHPExcel_IOFactory::load($location);
    $sheet = $objPHPExcel->getSheet(0);
    $total_rows = $sheet->getHighestRow();
    $total_columns = $sheet->getHighestColumn();
    $set_excel_query_all=array();
    for($row =2; $row <= $total_rows; $row++) {
        $singlerow = $sheet->rangeToArray('A' . $row . ':' . $total_columns . $row, NULL, TRUE, FALSE);
        $single_row=$singlerow[0];
        $set_excel_query['store_id']=$single_row[0];
        $set_excel_query['employee_uid']=$single_row[1];
        $set_excel_query['opus_id']=$single_row[2];
        $set_excel_query['item_description']=$single_row[3];
        if($single_row[4])
        {
            $set_excel_query['opus_transaction_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[4]));
        }
        $set_excel_query['opus_transaction_num']=$single_row[5];
        $set_excel_query['opus_invoice_num']=$single_row[6];
        $set_excel_query['customer_name']=$single_row[7];
        $set_excel_query['mobile_num']=$single_row[8];
        $set_excel_query['opus_amount']=$single_row[9];
        $set_excel_query['rq4_amount']=$single_row[10];
        $set_excel_query['difference']=$single_row[11];
        $set_excel_query['ocomment']=$single_row[12];
        $set_excel_query['mark_delete']=$single_row[13];
        if($single_row[14])
        {
            $set_excel_query['upload_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[14]));
        }
        $set_excel_query_all[]=$set_excel_query;
    }

   print_r($set_excel_query_all); 

PHP: How to remove specific element from an array?

I would prefer to use array_key_exists to search for keys in arrays like:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

I think it will help someone.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.

Anyway, anyone who is interested can find it on PyPi; the documentation is available on Read The Docs.

What would be the Unicode character for big bullet in the middle of the character?

You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.

Beware that few fonts contain these characters.

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

Laravel 5 route not defined, while it is?

I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.

For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.

A bit overkill, but I decided to reset all my cache at the same time using the following commands:

php artisan route:clear
php artisan view:clear
php artisan cache:clear

The main one here is the first command which will delete the bootstrap/cache/routes.php file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache folder.
Finally, the last command will clear the application cache.

How can I save a screenshot directly to a file in Windows?

Is this possible:

  1. Press Alt PrintScreen
  2. Open a folder
  3. Right click -> paste screenshot

Example:

Benchmark result window is open, take a screenshot. Open C:\Benchmarks Right click -> Paste screenshot A file named screenshot00x.jpg appears, with text screenshot00x selected. Type Overclock5

Thats it. No need to open anything. If you do not write anything, default name stays.

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Why is the <center> tag deprecated in HTML?

The <center> element was deprecated because it defines the presentation of its contents — it does not describe its contents.

One method of centering is to set the margin-left and margin-right properties of the element to auto, and then set the parent element’s text-align property to center. This guarantees that the element will be centered in all modern browsers.

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I had a similar problem, for me I had to create a new user with name that I needed, in your case you should create some like this:

USE [master]

GO

/****** Object:  Login [Manoj_2]    Script Date: 9/5/2019 12:16:14 PM ******/
CREATE LOGIN [Manoj_2] FROM WINDOWS WITH DEFAULT_DATABASE=[master],
DEFAULT_LANGUAGE=[us_english]

GO

ALTER SERVER ROLE [sysadmin] ADD MEMBER [Manoj_2]
GO

Redirect from asp.net web api post action

    [HttpGet]
    public RedirectResult Get()
    {
        return RedirectPermanent("https://www.google.com");
    }

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Parsing date string in Go

As answered but to save typing out "2006-01-02T15:04:05.000Z" for the layout, you could use the package's constant RFC3339.

str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

https://play.golang.org/p/Dgu2ZvHwTh

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

List all liquibase sql types

This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:

boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT

tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT

int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT

mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT

bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT

float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT

double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE

decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL

number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric

blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY

function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION

UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN

datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime

time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time

timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp

date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date

char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR

varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR

nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR

nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR

clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR

currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY

uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER

For reference, this is the groovy script I've used to generate this output:

@Grab('org.liquibase:liquibase-core:3.5.1')

import liquibase.database.core.*
import liquibase.datatype.core.*

def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
    def datatype = it.newInstance()
    datatype.finishInitialization("")
    println datatype.name
    databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
    println ''
}

Find UNC path of a network drive?

$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName

OR

$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName

What's the safest way to iterate through the keys of a Perl hash?

Using the each syntax will prevent the entire set of keys from being generated at once. This can be important if you're using a tie-ed hash to a database with millions of rows. You don't want to generate the entire list of keys all at once and exhaust your physical memory. In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.

So, the only place "each" is of real use is when the hash is very large (compared to the memory available). That is only likely to happen when the hash itself doesn't live in memory itself unless you're programming a handheld data collection device or something with small memory.

If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.

How to customize the background color of a UITableViewCell?

vlado.grigorov has some good advice - the best way is to create a backgroundView, and give that a colour, setting everything else to the clearColor. Also, I think that way is the only way to correctly clear the colour (try his sample - but set 'clearColor' instead of 'yellowColor'), which is what I was trying to do.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

C# switch on type

I did it one time with a workaround, hope it helps.

string fullName = typeof(MyObj).FullName;

switch (fullName)
{
    case "fullName1":
    case "fullName2":
    case "fullName3":
}

How to return a file (FileContentResult) in ASP.NET WebAPI

I am not exactly sure which part to blame, but here's why MemoryStream doesn't work for you:

As you write to MemoryStream, it increments it's Position property. The constructor of StreamContent takes into account the stream's current Position. So if you write to the stream, then pass it to StreamContent, the response will start from the nothingness at the end of the stream.

There's two ways to properly fix this:

1) construct content, write to stream

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    // ...
    // stream.Write(...);
    // ...
    return response;
}

2) write to stream, reset position, construct content

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    // ...
    // stream.Write(...);
    // ...
    stream.Position = 0;

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return response;
}

2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0

Getting mouse position in c#

To answer your specific example:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

Don't forget to add using System.Windows.Forms;, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.

The supported functionality:

  • multiple databases which can be selected at connection definition
  • CRUD operations like query tables
  • scheme operations
  • basic modelling support: show tables without pk, fk, connections

Not supported functionalities:

  • no table or field completion
  • no indexes are shown in a tab
  • no constraints are shown in a tab like: fk, pk-s, unique, or others
  • no table or field completions in the editor
  • no functions, packages,triggers, views are shown

The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;

MySQL: Insert record if not exists in table

INSERT IGNORE INTO `mytable`
SET `field0` = '2',
`field1` = 12345,
`field2` = 12678;

Here the mysql query, that insert records if not exist and will ignore existing similar records.

----Untested----

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

How to remove the bottom border of a box with CSS

Just add in: border-bottom: none;

#index-03 {
    position:absolute;
    border: .1px solid #900;
    border-bottom: none;
    left:0px;
    top:102px;
    width:900px;
    height:27px;
}

How does Access-Control-Allow-Origin header work?

Simply paste the following code in your web.config file.

Noted that, you have to paste the following code under <system.webServer> tag

    <httpProtocol>  
    <customHeaders>  
     <add name="Access-Control-Allow-Origin" value="*" />  
     <add name="Access-Control-Allow-Headers" value="Content-Type" />  
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />  
    </customHeaders>  
  </httpProtocol>  

Getting the class name from a static method in Java

In Java 7+ you can do this in static method/fields:

MethodHandles.lookup().lookupClass()

Load HTML file into WebView

In this case, using WebView#loadDataWithBaseUrl() is better than WebView#loadUrl()!

webView.loadDataWithBaseURL(url, 
        data,
        "text/html",
        "utf-8",
        null);

url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example

More info: WebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

passing several arguments to FUN of lapply (and others *apply)

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}

x is a vector or a list and myfun in lapply(x, myfun) is called for each element of x separately.

Option 1

If you'd like to use whole arg1 in each myfun call (myfun(x[1], arg1), myfun(x[2], arg1) etc.), use lapply(x, myfun, arg1) (as stated above).

Option 2

If you'd however like to call myfun to each element of arg1 separately alongside elements of x (myfun(x[1], arg1[1]), myfun(x[2], arg1[2]) etc.), it's not possible to use lapply. Instead, use mapply(myfun, x, arg1) (as stated above) or apply:

 apply(cbind(x,arg1), 1, myfun)

or

 apply(rbind(x,arg1), 2, myfun).

How to use type: "POST" in jsonp ajax call

Here is the JSONP I wrote to share with everyone:

the page to send req
http://c64.tw/r20/eqDiv/fr64.html

please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt

or embedded the code in your page:

function callbackForJsonp(resp) {

var elemDivResp = $("#idForDivResp");
elemDivResp.empty();

try {

    elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
    elemDivResp.append(" = " + resp.ans + "<br/>");
    elemDivResp.append(" = " + resp.ans2 + "<br/>");

} catch (e) {

    alert("callbackForJsonp=" + e);

}

}

$(document).ready(function() {

var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";

$(document.body).prepend("post to " + testUrl + "<br/><br/>");

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

    $.ajax({

        url : testUrl,
        type : "POST",

        data : {
            f1 : $("#idForF1").val(),
            f2 : $("#idForF2").val(),
            op : "add"
        },

        dataType : "jsonp",
        crossDomain : true,
        //jsonpCallback : "callbackForJsonp",
        success : callbackForJsonp,

        //success : function(resp) {

        //console.log("Yes, you success");
        //callbackForJsonp(resp);

        //},

        error : function(XMLHttpRequest, status, err) {

            console.log(XMLHttpRequest.status + "\n" + err);
            //alert(XMLHttpRequest.status + "\n" + err);

        }

    });

});

});

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

I had this issue on a REST API that was created using Spring framework. Adding a @ResponseBody annotation (to make the response JSON) resolved it.

must appear in the GROUP BY clause or be used in an aggregate function

The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).

However, there is a workaround: make the required field aggregated as well. In posgres, this should work:

SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

Phone number validation Android

You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.

Unable to add window -- token null is not valid; is your activity running?

I was getting this error while trying to show DatePicker from Fragment.

I changed

val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)

to

val datePickerDialog = DatePickerDialog(requireContext(), ...)

and it worked just fine.

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Compare two folders which has many files inside contents

Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.

 -b              Ignores trailing blanks  (spaces  and  tabs)
                 and   treats  other  strings  of  blanks  as
                 equivalent.

 -i              Ignores the case of  letters.  For  example,
                 `A' will compare equal to `a'.
 -t              Expands <TAB> characters  in  output  lines.
                 Normal or -c output adds character(s) to the
                 front of each line that may adversely affect
                 the indentation of the original source lines
                 and  make  the  output  lines  difficult  to
                 interpret.  This  option  will  preserve the
                 original source's indentation.

 -w              Ignores all blanks (<SPACE> and <TAB>  char-
                 acters)  and  treats  all  other  strings of
                 blanks   as   equivalent.    For    example,
                 `if ( a == b )'   will   compare   equal  to
                 `if(a==b)'.

and there are many more.

Sqlite convert string to date

This is for fecha(TEXT) format date YYYY-MM-dd HH:mm:ss for instance I want all the records of Ene-05-2014 (2014-01-05):

SELECT 
 fecha 
FROM 
 Mytable 
WHERE 
 DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN 
 DATE(20140105) 
AND 
 DATE(20140105);

What’s the difference between Response.Write() andResponse.Output.Write()?

See this:

The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.

In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);} 

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; } 

Which means you can do the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method aka String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);

But internally, of course, this is happening:

public virtual void Write(string format, params object[] arg)
{ 
this.Write(string.Format(format, arg)); 
}

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

How to add data to DataGridView

LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

Generating random numbers in C

You should call srand() before calling rand to initialize the random number generator.

Either call it with a specific seed, and you will always get the same pseudo-random sequence

#include <stdlib.h>

int main ()
{
  srand ( 123 );
  int random_number = rand();
  return 0;
}

or call it with a changing sources, ie the time function

#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) );
  int random_number = rand();
  return 0;
}

In response to Moon's Comment rand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)

You can then map this value to a smaller range, e.g.

int random_value = rand(); //between 0 and RAND_MAX

//you can mod the result
int N = 33;
int rand_capped = random_value % N;  //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82

//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)

This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1.

Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).

http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.

Also, I am not aware of arc4rand() or random() so I cannot comment.

the MySQL service on local computer started and then stopped

This error happened in my case when secure-file-priv was pointing to unexistent folder, make sure it exists and readable.

The line of code example in my.ini: secure-file-priv="D:/MySQL/uploads"

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

What's the difference between "super()" and "super(props)" in React when using es6 classes?

When you pass props to super, the props get assigned to this. Take a look at the following scenario:

constructor(props) {
    super();
    console.log(this.props) //undefined
}

How ever when you do :

constructor(props) {
    super(props);
    console.log(this.props) //props will get logged.
}

Convert JS object to JSON string

convert str => obj

const onePlusStr = '[{"brand":"oneplus"},{"model":"7T"}]';

const onePLusObj = JSON.parse(onePlusStr);

convert obj => str

const onePLusObjToStr = JSON.stringify(onePlusStr);

References of JSON parsing in JS:
JSON.parse() : click
JSON.stringify() : click

Javascript search inside a JSON object

Use PaulGuo's jSQL, a SQL like database using javascript. For example:

var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
    return o.name == 'Jacking';
}).listAll();

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

Why am I getting this error Premature end of file?

For those who reached this post for Answer:

This happens mainly because the InputStream the DOM parser is consuming is empty

So in what I ran across, there might be two situations:

  1. The InputStream you passed into the parser has been used and thus emptied.
  2. The File or whatever you created the InputStream from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream.

How does JavaScript .prototype work?

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

1- How JavaScript functions actually work:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Let's say we want to create a Person object model. but in this step I'm gonna be trying to do the same exact thing without using prototype and new keyword.

So in this step functions, objects and this keyword, are all we have.

The first question would be how this keyword could be useful without using new keyword.

So to answer that let's say we have an empty object, and two functions like:

var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

a. first way is just to call the function as a regular function:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

b. We can attach them to an object, as its properties

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"

and now the person object is like:

Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).


as you see using any of these two way this would exactly point to the person object.

c. JavaScript has another way to provide the function with this, which is using call or apply to invoke the function.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");

or

//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.


2- How does the new keyword work?

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

a. first of all it makes an empty object, basically an empty hash like:

var newObject = {};

b. the next step that JavaScript takes is to attach the all prototype objects to the newly created object

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.


a. & b. Instead of these two steps you can have the exact same result by doing:

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"

now we can call the getName function in our my_person_prototype:

newObject.getName();

c. then it gives that object to the constructor,

we can do this with our sample like:

Person.call(newObject, "George");

or

Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}


Summary:

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

The prototype chain

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

Fastest way to set all values of an array?

Use Arrays.fill

  char f = '+';
  char [] c = new char [50];
  Arrays.fill(c, f)

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Iframe transparent background

<style type="text/css">
body {background:none transparent;
}
</style>

that might work (if you put in the iframe) along with

<iframe src="stuff.htm" allowtransparency="true">

When a 'blur' event occurs, how can I find out which element focus went *to*?

Works in Google Chrome v66.x, Mozilla v59.x and Microsoft Edge... Solution with jQuery.

I test in Internet Explorer 9 and not supported.

$("#YourElement").blur(function(e){
     var InputTarget =  $(e.relatedTarget).attr("id"); // GET ID Element
     console.log(InputTarget);
     if(target == "YourId") { // If you want validate or make a action to specfic element
          ... // your code
     }
});

Comment your test in others internet explorer versions.

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

How do you reverse a string in place in C or C++?

#include <algorithm>
std::reverse(str.begin(), str.end());

This is the simplest way in C++.

jQuery Clone table row

Try this code, I used the following code for cloning and removing the cloned element, i have also used new class (newClass) which can be added automatically with the newly cloned html

for cloning..

 $(".tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var newClass='newClass';
    var $clone = $tr.clone().addClass(newClass);
    $clone.find(':text').val('');
    $tr.after($clone);
});

for removing the clone element.

$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
});

html is as followinng

<tr class="tr_clone">
                       <!-- <td>1</td>-->
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span10" readonly>
                        <span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

When to use LinkedList over ArrayList in Java?

When should I use LinkedList? When working with stacks mostly, or when working with buffers. When should I use ArrayList? Only when working with indexes, otherwise you can use HashTable with linked list, then you get:

Hash table + linked list

  • Access by key O(1),
  • Insert by key O(1),
  • Remove by key O(1)
  • and there is a trick to implement RemoveAll / SetAll with O(1) when using versioning

It seems like a good solution, and in most of the cases it is, how ever you should know: HashTable takes a lot of disc space, so when you need to manage 1,000,000 elements list it can become a thing that matters. This can happen in server implementations, in clients it is rarely the case.

Also take a look at Red-Black-Tree

  • Random access Log(n),
  • Insert Log(n),
  • Remove Log(n)

Where does MAMP keep its php.ini?

Probably the fastest way to access the PHP.ini for the currently loaded version of PHP in MAMP PRO (v.4.2.1):

  1. Open MAMP Pro
  2. Click on "PHP" under the "Languages" section on the sidebar
  3. Tap on the arrow button right next to the drop-down that lets you select the "Default Version" of PHP.

How to detect the end of loading of UITableView

Using private API:

@objc func tableViewDidFinishReload(_ tableView: UITableView) {
    print(#function)
    cellsAreLoaded = true
}

Using public API:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // cancel the perform request if there is another section
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];

    // create a perform request to call the didLoadRows method on the next event loop.
    [self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];

    return [self.myDataSource numberOfRowsInSection:section];
}

// called after the rows in the last section is loaded
-(void)tableViewDidLoadRows:(UITableView*)tableView{
    self.cellsAreLoaded = YES;
}

A possible better design is to add the visible cells to a set, then when you need to check if the table is loaded you can instead do a for loop around this set, e.g.

var visibleCells = Set<UITableViewCell>()

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.insert(cell)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.remove(cell)
}

// example property you want to show on a cell that you only want to update the cell after the table is loaded. cellForRow also calls configure too for the initial state.
var count = 5 {
    didSet {
        for cell in visibleCells {
            configureCell(cell)
        }
    }
}

Common elements in two lists

consider two list L1 ans L2

Using Java8 we can easily find it out

L1.stream().filter(L2::contains).collect(Collectors.toList())

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

Is there a limit on how much JSON can hold?

JSON is similar to other data formats like XML - if you need to transmit more data, you just send more data. There's no inherent size limitation to the JSON request. Any limitation would be set by the server parsing the request. (For instance, ASP.NET has the "MaxJsonLength" property of the serializer.)

Why can't DateTime.Parse parse UTC date

Assuming you use the format "o" for your datetime so you have "2016-07-24T18:47:36Z", there is a very simple way to handle this.

Call DateTime.Parse("2016-07-24T18:47:36Z").ToUniversalTime().

What happens when you call DateTime.Parse("2016-07-24T18:47:36Z") is you get a DateTime set to the local timezone. So it converts it to the local time.

The ToUniversalTime() changes it to a UTC DateTime and converts it back to UTC time.

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I think it's best to explicitly state where the form posts. If you want to be totally safe, enter the same URL the form is on in the action attribute if you want it to submit back to itself. Although mainstream browsers evaluate "" to the same page, you can't guarantee that non-mainstream browsers will.

And of course, the entire URL including GET data like Juddling points out.

Why do we need C Unions?

Low level system programming is a reasonable example.

IIRC, I've used unions to breakdown hardware registers into the component bits. So, you can access an 8-bit register (as it was, in the day I did this ;-) into the component bits.

(I forget the exact syntax but...) This structure would allow a control register to be accessed as a control_byte or via the individual bits. It would be important to ensure the bits map on to the correct register bits for a given endianness.

typedef union {
    unsigned char control_byte;
    struct {
        unsigned int nibble  : 4;
        unsigned int nmi     : 1;
        unsigned int enabled : 1;
        unsigned int fired   : 1;
        unsigned int control : 1;
    };
} ControlRegister;

Where is svn.exe in my machine?

First off, if subversion installed on your machine? if not look at what server your tortoisesvn is setup to connect to.

the default location when subversion is installed is c:\program files\subversion you can find svn.exe in c:\program files\subversion\bin where you can run your cmd line actions.

Batch file to perform start, run, %TEMP% and delete all

@echo off
RD %TEMP%\. /S /Q

::pause
explorer %temp%

This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.

Is JavaScript's "new" keyword considered harmful?

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

  1. Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  2. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
}

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

The apk must be signed with the same certificates as the previous version

Nothing. Read the documentation: Publishing Updates on Android Market

Before uploading the updated application, be sure that you have incremented the android:versionCode and android:versionName attributes in the element of the manifest file. Also, the package name must be the same and the .apk must be signed with the same private key. If the package name and signing certificate do not match those of the existing version, Market will consider it a new application and will not offer it to users as an update.

Run a Java Application as a Service on Linux

You can use Thrift server or JMX to communicate with your Java service.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Maven dependencies are failing with a 501 error

Same issue is also occuring for jcenter.

From 13 Jan 2020 onwards, Jcenter is only available at HTTPS.

Projects getting their dependencies using the same will start facing issues. For quick fixes do the following in your build.gradle

instead of

repositories {
jcenter ()
//others
}

use this:

repositories {
jcenter { url "http://jcenter.bintray.com/"}
//others
}

How can I convert uppercase letters to lowercase in Notepad++

I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.

Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.

Then I realized, that you can create macros easily, so I recorded one doing:

  • mark all
  • paste from clipboard
  • convert to upppercase
  • copy to clipboard

That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)

Jackson JSON: get node name from json-tree

fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

One is by converting it into a map (takes up more space):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
    if(key.equals(foo))
    {
        //code here
    }
}

Another, by using a String iterator:

Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
    String key = it.next();
    if (key.equals(foo))
    {
         //code here
    }
}

Difference between staticmethod and classmethod

Here is a short article on this question

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).

Use of True, False, and None as return values in Python functions

You can directly check that a variable contains a value or not, like if var or not var.

What are Bearer Tokens and token_type in OAuth 2?

token_type is a parameter in Access Token generate call to Authorization server, which essentially represents how an access_token will be generated and presented for resource access calls. You provide token_type in the access token generation call to an authorization server.

If you choose Bearer (default on most implementation), an access_token is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand, if you choose Mac and sign_type (default hmac-sha-1 on most implementation), the access token is generated and kept as secret in Key Manager as an attribute, and an encrypted secret is sent back as access_token.

Yes, you can use your own implementation of token_type, but that might not make much sense as developers will need to follow your process rather than standard implementations of OAuth.

How to add an object to an array

The way I made object creator with auto list:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};

How to randomly select an item from a list?

If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using random.sample instead.

import random
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 

If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list).

Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.

EDIT: Using Secrets

As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

EDIT: Pythonic One-Liner

If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.

import random
first_random_item, second_random_item = random.sample(group_of_items, 2)

The calling thread must be STA, because many UI components require this

Try to invoke your code from the dispatcher:

Application.Current.Dispatcher.Invoke((Action)delegate{
      // your code
});

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

How do you fix the "element not interactable" exception?

use id of the element except x_path.It will work 100%

How to get a variable name as a string in PHP?

I think you want to know variable name with it's value. You can use an associative array to achieve this.

use variable names for array keys:

$vars = array('FooBar' => 'a string');

When you want to get variable names, use array_keys($vars), it will return an array of those variable names that used in your $vars array as it's keys.

Angular 4 HttpClient Query Parameters

joshrathke is right.

In angular.io docs is written that URLSearchParams from @angular/http is deprecated. Instead you should use HttpParams from @angular/common/http. The code is quite similiar and identical to what joshrathke have written. For multiple parameters that are saved for instance in a object like

{
  firstParam: value1,
  secondParam, value2
}

you could also do

for(let property in objectStoresParams) {
  if(objectStoresParams.hasOwnProperty(property) {
    params = params.append(property, objectStoresParams[property]);
  }
}

If you need inherited properties then remove the hasOwnProperty accordingly.

Compare two objects' properties to find differences?

Type.GetProperties will list each of the properties of a given type. Then use PropertyInfo.GetValue to check the values.

What is a regular expression which will match a valid domain name without a subdomain?

My RegEx is next:

^[a-zA-Z0-9][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$

it's ok for i.oh1.me and for wow.british-library.uk

UPD

Here is updated rule

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

Regular expression visualization

https://www.debuggex.com/r/y4Xe_hDVO11bv1DV

now it check for - or _ in the start or end of domain label.

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

Angular 2 optional route parameter

Ran into another instance of this problem, and in searching for a solution to it came here. My issue was that I was doing the children, and lazy loading of the components as well to optimize things a bit. In short if you are lazy loading the parent module. Main thing was my using '/:id' in the route, and it's complaints about '/' being a part of it. Not the exact problem here, but it applies.

App-routing from parent

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...

Child routes lazy loaded

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...

How to draw border around a UILabel?

Here are some things you can do with UILabel and its borders.

enter image description here

Here is the code for those labels:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // label 1
        label1.layer.borderWidth = 1.0

        // label 2
        label2.layer.borderWidth = 5.0
        label2.layer.borderColor = UIColor.blue.cgColor

        // label 3
        label3.layer.borderWidth = 2.0
        label3.layer.cornerRadius = 8

        // label 4
        label4.backgroundColor = UIColor.cyan

        // label 5
        label5.backgroundColor = UIColor.red
        label5.layer.cornerRadius = 8
        label5.layer.masksToBounds = true

        // label 6
        label6.layer.borderWidth = 2.0
        label6.layer.cornerRadius = 8
        label6.backgroundColor = UIColor.yellow
        label6.layer.masksToBounds = true
    }
}

Note that in Swift there is no need to import QuartzCore.

See also

Command to get nth line of STDOUT

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.

How to save S3 object to a file using boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_download(s3path, destination) directly or the copy-pasted code:

def s3_download(source, destination,
                exists_strategy='raise',
                profile_name=None):
    """
    Copy a file from an S3 source to a local destination.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    destination : str
    exists_strategy : {'raise', 'replace', 'abort'}
        What is done when the destination already exists?
    profile_name : str, optional
        AWS profile

    Raises
    ------
    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    exists_strategies = ['raise', 'replace', 'abort']
    if exists_strategy not in exists_strategies:
        raise ValueError('exists_strategy \'{}\' is not in {}'
                         .format(exists_strategy, exists_strategies))
    session = boto3.Session(profile_name=profile_name)
    s3 = session.resource('s3')
    bucket_name, key = _s3_path_split(source)
    if os.path.isfile(destination):
        if exists_strategy is 'raise':
            raise RuntimeError('File \'{}\' already exists.'
                               .format(destination))
        elif exists_strategy is 'abort':
            return
    s3.Bucket(bucket_name).download_file(key, destination)

from collections import namedtuple

S3Path = namedtuple("S3Path", ["bucket_name", "key"])


def _s3_path_split(s3_path):
    """
    Split an S3 path into bucket and key.

    Parameters
    ----------
    s3_path : str

    Returns
    -------
    splitted : (str, str)
        (bucket, key)

    Examples
    --------
    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
    """
    if not s3_path.startswith("s3://"):
        raise ValueError(
            "s3_path is expected to start with 's3://', " "but was {}"
            .format(s3_path)
        )
    bucket_key = s3_path[len("s3://"):]
    bucket_name, key = bucket_key.split("/", 1)
    return S3Path(bucket_name, key)

Parse JSON response using jQuery

The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].

You have to iterate through that values to get actuall value. Like the following

jQuery provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (linktext, link) {
        console.log(linktext);
        console.log(link);
    });
});

Now just create an Hyperlink using that info.

Display MessageBox in ASP

Here is one way of doing it:

    <%
       Dim message    
       message = "This is my message"
       Response.Write("<script language=VBScript>MsgBox """ + message + """</script>") 
    %>

Error: Jump to case label

The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case.

In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally use the i variable which does exist but probably contains garbage.

switch(foo) {
  case 1:
    int i = 42; // i exists all the way to the end of the switch
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); // i is *also* in scope here, but is not initialized!
}

Wrapping the case in an explicit block solves the problem:

switch(foo) {
  case 1:
    {
        int i = 42; // i only exists within the { }
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123); // Now you cannot use i accidentally
}

Edit

To further elaborate, switch statements are just a particularly fancy kind of a goto. Here's an analoguous piece of code exhibiting the same issue but using a goto instead of a switch:

int main() {
    if(rand() % 2) // Toss a coin
        goto end;

    int i = 42;

  end:
    // We either skipped the declaration of i or not,
    // but either way the variable i exists here, because
    // variable scopes are resolved at compile time.
    // Whether the *initialization* code was run, though,
    // depends on whether rand returned 0 or 1.
    std::cout << i;
}

read.csv warning 'EOF within quoted string' prevents complete reading of file

I too had the similar problem. But in my case, the cause of the issue was due to the presence of apostrophes (i.e. single quotation marks) within some of the text values. This is especially frequent when working with data including texts in French, e.g. «L'autre jour».

So, the solution was simply to adjust the default setting of the quote argument to exclude the «'» symbol, and thus, using quote = "\"" (i.e. double quotation mark only), everything worked fine.

I hope that can help some of you. Cheers.

jQuery scroll to ID from different page

You basically need to do this:

  • include the target hash into the link pointing to the other page (href="other_page.html#section")
  • in your ready handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and call jump() - you'll need to do this asynchronously
  • in jump() if no event is given, make location.hash the target
  • also this technique might not catch the jump in time, so you'll better hide the html,body right away and show it back once you scrolled it back to zero

This is your code with the above added:

var jump=function(e)
{
   if (e){
       e.preventDefault();
       var target = $(this).attr("href");
   }else{
       var target = location.hash;
   }

   $('html,body').animate(
   {
       scrollTop: $(target).offset().top
   },2000,function()
   {
       location.hash = target;
   });

}

$('html, body').hide();

$(document).ready(function()
{
    $('a[href^=#]').bind("click", jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    }else{
        $('html, body').show();
    }
});

Verified working in Chrome/Safari, Firefox and Opera. I don't know about IE though.

Array from dictionary keys in swift

You can use dictionary.map like this:

let myKeys: [String] = myDictionary.map{String($0.key) }

The explanation: Map iterates through the myDictionary and accepts each key and value pair as $0. From here you can get $0.key or $0.value. Inside the trailing closure {}, you can transform each element and return that element. Since you want $0 and you want it as a string then you convert using String($0.key). You collect the transformed elements to an array of strings.

How do I add slashes to a string in Javascript?

var myNewString = myOldString.replace(/'/g, "\\'");

AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

Iterating through a string word by word

for word in string.split():
    print word

Can HTML be embedded inside PHP "if" statement?

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).

Better is to use heredoc syntax. It is the same concept as in other languages (like bash).

 <?php
 if ($condition) {
   echo <<< END_OF_TEXT
     <b>lots of html</b> <i>$variable</i>
     lots of text...
 many lines possible, with any indentation, until the closing delimiter...
 END_OF_TEXT;
 }
 ?>

END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.

Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).

Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

How do I consume the JSON POST data in an Express application

For Express v4+

install body-parser from the npm.

$ npm install body-parser

https://www.npmjs.org/package/body-parser#installation

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

How to convert a python numpy array to an RGB image with Opencv 2.4?

The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50

import cv2 as cv
import numpy as np

black_screen = np.zeros([50,50,3])

black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()

Swap two items in List<T>

List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.

your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.

Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

How to connect to LocalDb

 <add name="Default" connectionString="Data Source=(LocalDb)\MSSqlLocalDB; Initial Catalog=CRM_Default_v1; Integrated Security=True"
      providerName="System.Data.SqlClient"/>

your web.config files in visual studio under connectiionString or Go to View > SQL Server Object Viewer > Add Sql Server> add your server there

How do I implement a progress bar in C#?

If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.

Conditional formatting based on another cell's value

I'm disappointed at how long it took to work this out.

I want to see which values in my range are outside standard deviation.

  1. Add the standard deviation calc to a cell somewhere =STDEV(L3:L32)*2
  2. Select the range to be highlighted, right click, conditional formatting
  3. Pick Format Cells if Greater than
  4. In the Value or Formula box type =$L$32 (whatever cell your stdev is in)

I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.

UIImage resize (Scale proportion)

That's ok not a big problem . thing is u got to find the proportional width and height

like if size is 2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be 722.0 x 480.0

here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y 
=> 
x=(w/h)*y;  

submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)

U can submit in this web page . ARC

Confused ? alright , here is category for UIImage which will do the thing for you.

@interface UIImage (UIImageFunctions)
    - (UIImage *) scaleToSize: (CGSize)size;
    - (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)

- (UIImage *) scaleToSize: (CGSize)size
{
    // Scalling selected image to targeted size
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    if(self.imageOrientation == UIImageOrientationRight)
    {
        CGContextRotateCTM(context, -M_PI_2);
        CGContextTranslateCTM(context, -size.height, 0.0f);
        CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
    }
    else
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);

    CGImageRef scaledImage=CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    UIImage *image = [UIImage imageWithCGImage: scaledImage];

    CGImageRelease(scaledImage);

    return image;
}

- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
    if(self.size.width>self.size.height)
    {
        NSLog(@"LandScape");
        size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
    }
    else
    {
        NSLog(@"Potrait");
        size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
    }

    return [self scaleToSize:size1];
}

@end

-- the following is appropriate call to do this if img is the UIImage instance.

img=[img scaleProportionalToSize:CGSizeMake(320, 480)];

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Fastest way to find second (third...) highest/lowest value in vector or column

Here is an easy way to find the indices of N smallest/largest values in a vector(Example for N = 3):

N <- 3

N Smallest:

ndx <- order(x)[1:N]

N Largest:

ndx <- order(x, decreasing = T)[1:N]

So you can extract the values as:

x[ndx]

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

How to find foreign key dependencies in SQL Server?

I think this script is less expensive:

SELECT f.name AS ForeignKey, OBJECT_NAME(f.parent_object_id) AS TableName,
    COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
    OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
    COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id

Efficiently finding the last line in a text file

with open('output.txt', 'r') as f:
    lines = f.read().splitlines()
    last_line = lines[-1]
    print last_line

How to get child element by ID in JavaScript?

$(selectedDOM).find();

function looking for all dom objects inside the selected DOM. i.e.

<div id="mainDiv">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <div id="innerDiv">
         <a href="#">link</a>
         <p>Paragraph 3</p>
    </div>
</div>

here if you write;

$("#mainDiv").find("p");

you will get tree p elements together. On the other side,

$("#mainDiv").children("p");

Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Can I get JSON to load into an OrderedDict?

Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:

import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))

In py3.5 the resulting order is undefined:

{
    "fiddle": {
        "bar": 2,
        "foo": 1
    },
    "bar": 2,
    "foo": 1
}

In the cPython implementation of python 3.6:

{
    "foo": 1,
    "bar": 2,
    "fiddle": {
        "bar": 2,
        "foo": 1
    }
}

The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html

So the answer to your question now becomes: upgrade to python 3.6! :)

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

So, It seems that the remote script being called cannot have errors within it.

forEach is not a function error with JavaScript array

You can check if you typed forEach correctly, if you typed foreach like in other programming languages it won't work.