Programs & Examples On #Georss

GeoRSS is a standard for encoding location as part of a Web feed. The name "GeoRSS" is derived from RSS, a well known web feed and syndication format.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Wrap text in <td> tag

HTML tables support a "table-layout:fixed" css style that prevents the user agent from adapting column widths to their content. You might want to use it.

jQuery .slideRight effect

If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide(), with additional arguments, as follows:

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this).hide('slide',{direction:'right'},1000);

            });
    });

JS Fiddle demo.


Without using jQuery UI, you could achieve your aim just using animate():

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this)
                    .animate(
                        {
                            'margin-left':'1000px'
                            // to move it towards the right and, probably, off-screen.
                        },1000,
                        function(){
                            $(this).slideUp('fast');
                            // once it's finished moving to the right, just 
                            // removes the the element from the display, you could use
                            // `remove()` instead, or whatever.
                        }
                        );

            });
    });

JS Fiddle demo

If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Export to CSV using jQuery and html

 <a id="export" role='button'>
        Click Here To Download Below Report
    </a>
    <table id="testbed_results" style="table-layout:fixed">
        <thead>
            <tr width="100%" style="color:white" bgcolor="#3195A9" id="tblHeader">
                <th>Name</th>
                <th>Date</th>
                <th>Speed</th>
                <th>Column2</th>
                <th>Interface</th>
                <th>Interface2</th>
                <th>Sub</th>
                <th>COmpany result</th>
                <th>company2</th>
                <th>Gen</th>
            </tr>
        </thead>
        <tbody>
            <tr id="samplerow">
                <td>hello</td>
                <td>100</td>
                <td>200</td>
                <td>300</td>
                <td>html2svc</td>
                <td>ajax</td>
                <td>200</td>
                <td>7</td>
                <td>8</td>
                <td>9</td>
            </tr>
            <tr>
                <td>hello</td>
                <td>100</td>
                <td>200</td>
                <td>300</td>
                <td>html2svc</td>
                <td>ajax</td>
                <td>200</td>
                <td>7</td>
                <td>8</td>
                <td>9</td>
            </tr>
        </tbody>
    </table>

    $(document).ready(function () {
        Html2CSV('testbed_results', 'myfilename','export');
    });



    function Html2CSV(tableId, filename,alinkButtonId) {
        var array = [];
        var headers = [];
        var arrayItem = [];
        var csvData = new Array();
        $('#' + tableId + ' th').each(function (index, item) {
            headers[index] = '"' + $(item).html() + '"';
        });
        csvData.push(headers);
        $('#' + tableId + ' tr').has('td').each(function () {

            $('td', $(this)).each(function (index, item) {
                arrayItem[index] = '"' + $(item).html() + '"';
            });
            array.push(arrayItem);
            csvData.push(arrayItem);
        });




        var fileName = filename + '.csv';
        var buffer = csvData.join("\n");
        var blob = new Blob([buffer], {
            "type": "text/csv;charset=utf8;"
        });
        var link = document.getElementById(alinkButton);

        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            link.setAttribute("href", window.URL.createObjectURL(blob));
            link.setAttribute("download", fileName);
        }
        else if (navigator.msSaveBlob) { // IE 10+
            link.setAttribute("href", "#");
            link.addEventListener("click", function (event) {
                navigator.msSaveBlob(blob, fileName);
            }, false);
        }
        else {
            // it needs to implement server side export
            link.setAttribute("href", "http://www.example.com/export");
        }
    }

</script>

Manually raising (throwing) an exception in Python

For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be AssertionError:

if 0 < distance <= RADIUS:
    #Do something.
elif RADIUS < distance:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'distance'!", distance)

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

Reading large text files with streams in C#

An iterator might be perfect for this type of work:

public static IEnumerable<int> LoadFileWithProgress(string filename, StringBuilder stringData)
{
    const int charBufferSize = 4096;
    using (FileStream fs = File.OpenRead(filename))
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            long length = fs.Length;
            int numberOfChunks = Convert.ToInt32((length / charBufferSize)) + 1;
            double iter = 100 / Convert.ToDouble(numberOfChunks);
            double currentIter = 0;
            yield return Convert.ToInt32(currentIter);
            while (true)
            {
                char[] buffer = br.ReadChars(charBufferSize);
                if (buffer.Length == 0) break;
                stringData.Append(buffer);
                currentIter += iter;
                yield return Convert.ToInt32(currentIter);
            }
        }
    }
}

You can call it using the following:

string filename = "C:\\myfile.txt";
StringBuilder sb = new StringBuilder();
foreach (int progress in LoadFileWithProgress(filename, sb))
{
    // Update your progress counter here!
}
string fileData = sb.ToString();

As the file is loaded, the iterator will return the progress number from 0 to 100, which you can use to update your progress bar. Once the loop has finished, the StringBuilder will contain the contents of the text file.

Also, because you want text, we can just use BinaryReader to read in characters, which will ensure that your buffers line up correctly when reading any multi-byte characters (UTF-8, UTF-16, etc.).

This is all done without using background tasks, threads, or complex custom state machines.

Android: How can I print a variable on eclipse console?

toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...

Controlling Maven final name of jar artifact

You set the finalName property in the plugin configuration section:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <finalName>myJar</finalName>                   
    </configuration>
</plugin>       

As indicated in the official documentation.

Update:

For Maven >= 3

Based on Matthew's comment you can now do it like this:

 <packaging>jar</packaging>
 <build>
   <finalName>WhatEverYouLikey</finalName>
 </build>

See bug report/documentation.

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

Python Pandas Error tokenizing data

I had a similar error and the issue was that I had some escaped quotes in my csv file and needed to set the escapechar parameter appropriately.

How can I generate an ObjectId with mongoose?

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.

You can read more about the Types object at Mongoose#Types documentation.

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Is Constructor Overriding Possible?

It should also be noted that you can't override the constructor in the subclass with the constructor of the superclass's name. The rule of OOPS tells that a constructor should have name as its class name. If we try to override the superclass constructor it will be seen as an unknown method without a return type.

How do I run pip on python for windows?

Maybe you'd like try run pip in Python shell like this:

>>> import pip
>>> pip.main(['install', 'requests'])

This will install requests package using pip.


Because pip is a module in standard library, but it isn't a built-in function(or module), so you need import it.

Other way, you should run pip in system shell(cmd. If pip is in path).

How can I use jQuery to move a div across the screen

Use jQuery

html

<div id="b">&nbsp;</div>

css

div#b {
    position: fixed;
    top:40px;
    left:0;
    width: 40px;
    height: 40px;
    background: url(http://www.wiredforwords.com/IMAGES/FlyingBee.gif) 0 0 no-repeat;
}

script

var b = function($b,speed){


    $b.animate({
        "left": "50%"
    }, speed);
};

$(function(){
    b($("#b"), 5000);
});

see jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/

CSS Margin: 0 is not setting to 0

Try

html, body{
  margin:0 !important;
  padding:0 !important;
}

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Higher ranked answers have a few inherent issues including the use of legacy javascript, incorrect ordering or with only support for 2 duplicated items.

Here's a modern solution which fixes those problems:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

You can also use the npm package array-non-uniq.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

How to show uncommitted changes in Git and some Git diffs in detail

You have already staged the changes (presumably by running git add), so in order to get their diff, you need to run:

git diff --cached

(A plain git diff will only show unstaged changes.)

For example: Example git diff cached use

How can I create a table with borders in Android?

IF you are just trying to have a line in between rows (for example, just above a "Total" row) then there is an easy solution - just add a TableRow with a background color and a specific layout_height such as this:

<TableRow android:layout_height="1px" android:background="#BDBDBD">
   <TextView android:layout_span="2" android:layout_height="1px" 
             android:layout_width="fill_parent" android:text="">
   </TextView>
</TableRow>

Set android:layout_height="1px" or however thick you want the border to be. Fill in as many empty TextView columns as you need to match the rest of your table, or just use one along with android:layout_span as I have demonstrated.

The output will look something like this:

Table Border demonstrated

If you are trying to add more complicated borders then the other answers already posted are more appropriate.

How can I check if string contains characters & whitespace, not just whitespace?

if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

split python source code into multiple files?

Sure!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

How to add composite primary key to table

In Oracle, you could do this:

create table D (
  ID numeric(1),
  CODE varchar(2),
  constraint PK_D primary key (ID, CODE)
);

shorthand c++ if else statement

Yes:

bigInt.sign = !(number < 0);

The ! operator always evaluates to true or false. When converted to int, these become 1 and 0 respectively.

Of course this is equivalent to:

bigInt.sign = (number >= 0);

Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true or false.

Which version of C# am I using

It depends upon the .NET Framework that you use. Check Jon Skeet's answer about Versions.

Here is short version of his answer.

C# 1.0 released with .NET 1.0

C# 1.2 (bizarrely enough); released with .NET 1.1

C# 2.0 released with .NET 2.0

C# 3.0 released with .NET 3.5

C# 4.0 released with .NET 4

C# 5.0 released with .NET 4.5

C# 6.0 released with .NET 4.6

C# 7.0 is released with .NET 4.6.2

C# 7.3 is released with .NET 4.7.2

C# 8.0 is released with NET Core 3.0

C# 9.0 is released with NET 5.0

Linq where clause compare only date value without time value

There is also EntityFunctions.TruncateTime or DbFunctions.TruncateTime in EF 6.0

More than one file was found with OS independent path 'META-INF/LICENSE'

I have read all the answers related to getting this message in Android Studio:

More than one file was found with OS independent path 'META-INF/LICENSE'

but in this case excluding classes is no neccessary, we only need to exclude 'META-INF/DEPENDENCIES', this can be done inside the /app/build.gradle:

android{
    ...
    ...
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }

}

Filtering lists using LINQ

I would just use the FindAll method on the List class. i.e.:

List<Person> filteredResults = 
    people.FindAll(p => return !exclusions.Contains(p));

Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.

Multiple submit buttons in an HTML form

Instead of struggling with multiple submits, JavaScript or anything like that to do some previous/next stuff, an alternative would be to use a carousel to simulate the different pages. Doing this :

  • You don't need multiple buttons, inputs or submits to do the previous/next thing, you have only one input type="submit" in only one form.
  • The values in the whole form are there until the form is submitted.
  • The user can go to any previous page and any next page flawlessly to modify the values.

Example using Bootstrap 5.0.0 :

<div id="carousel" class="carousel slide" data-ride="carousel">
    <form action="index.php" method="post" class="carousel-inner">
        <div class="carousel-item active">
            <input type="text" name="lastname" placeholder="Lastname"/>
        </div>
        <div class="carousel-item">
            <input type="text" name="firstname" placeholder="Firstname"/>
        </div>
        <div class="carousel-item">
            <input type="submit" name="submit" value="Submit"/>
        </div>
    </form>
    <a class="btn-secondary" href="#carousel" role="button" data-slide="prev">Previous page</a>
    <a class="btn-primary" href="#carousel" role="button" data-slide="next">Next page</a>
</div>

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

However, numbering starts at 1, so:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

Also, if you have multiple axes on a figure, such as subplots, use the axes(h) command where h is the handle of the desired axes object to focus on that axes.

(don't have comment privileges yet, sorry for new answer!)

Lodash remove duplicates from array

Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

_.uniqBy(data, 'id');

or

_.uniqBy(data, obj => obj.id);

How to add http:// if it doesn't exist in the URL

At the time of writing, none of the answers used a built-in function for this:

function addScheme($url, $scheme = 'http://')
{
  return parse_url($url, PHP_URL_SCHEME) === null ?
    $scheme . $url : $url;
}

echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"

See also: parse_url()

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

In java how to get substring from a string till a character c?

or you may try something like

"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);

converting a base 64 string to an image and saving it

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

Real time data graphing on a line chart with html5

In order to complete this thread, I would suggest you to look into:

d3.js

This is a library that helps with tons of javascript visualizations. However the learning curve is quite steep.

nvd3.js

A library that makes it easy to create some d3.js visualizations (with limitations, of course).

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Dilemma: when to use Fragments vs Activities:

The one big advantage of a fragment over activity is that , the code which is used for fragment can be used for different activities. So, it provides re-usability of code in application development.

updating Google play services in Emulator

You need install Google play image, Android SDK -> SDK platforms --> check show Package details --> install Google play. enter image description here

Unlink of file Failed. Should I try again?

I was able to solve this by opening Powershell as Administrator and from there git checkout <branch_name>

%i or %d to print integer in C using printf()?

%d seems to be the norm for printing integers, I never figured out why, they behave identically.

How can I set the aspect ratio in matplotlib?

This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.

def forceAspect(ax,aspect=1):
    #aspect is width/height
    scale_str = ax.get_yaxis().get_scale()
    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    if scale_str=='linear':
        asp = abs((xmax-xmin)/(ymax-ymin))/aspect
    elif scale_str=='log':
        asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
    ax.set_aspect(asp)

Obviously you can use any version of log you want, I've used scipy, but numpy or math should be fine.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I modified the accepted answer and now it can get the command including primary key and foreign key in a certain schema.

declare @table varchar(100)
declare @schema varchar(100)
set @table = 'Persons' -- set table name here
set @schema = 'OT' -- set SCHEMA name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into  @sql(s) values ('create table ' + @table + ' (')

-- column list
insert into @sql(s)
select 
    '  '+column_name+' ' + 
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists ( 
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
    ) then
        'IDENTITY(' + 
        cast(ident_seed(@table) as varchar) + ',' + 
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from information_schema.columns where table_name = @table and table_schema = @schema
 order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   '+COLUMN_NAME+',' from information_schema.key_column_usage
        where constraint_name = @pkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end


-- foreign key
declare @fkname varchar(100)
select @fkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='FOREIGN KEY'

if ( @fkname is not null ) begin
    insert into @sql(s) values(',')
    insert into @sql(s) values('  FOREIGN KEY (')
    insert into @sql(s)
        select '   '+COLUMN_NAME+',' from information_schema.key_column_usage
        where constraint_name = @fkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  ) REFERENCES ')
    insert into @sql(s) 
        SELECT  
            OBJECT_NAME(fk.referenced_object_id)
        FROM 
            sys.foreign_keys fk
        INNER JOIN 
            sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
        INNER JOIN
            sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
        INNER JOIN
            sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
        where fk.name = @fkname
    insert into @sql(s) 
        SELECT  
            '('+c2.name+')'
        FROM 
            sys.foreign_keys fk
        INNER JOIN 
            sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
        INNER JOIN
            sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
        INNER JOIN
            sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
        where fk.name = @fkname
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

How to execute a file within the python interpreter?

I'm trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.

Passing a local variable from one function to another

You can very easily use this to re-use the value of the variable in another function.

// Use this in source window.var1= oEvent.getSource().getBindingContext();

// Get value of var1 in destination var var2= window.var1;

Converting Select results into Insert script - SQL Server

In SSMS:

  • Right click on the database > Tasks > Generate Scripts

  • Next

  • Select "Select specific database objects" and check the table you want scripted, Next

  • Click Advanced > in the list of options, scroll down to the bottom and look for the "Types of data to script" and change it to "Data Only" > OK

  • Select "Save to new query window" > Next > Next > Finish

All 180 rows now written as 180 insert statements!

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

How can I find the method that called the current method?

var callingMethod = new StackFrame(1, true).GetMethod();
string source = callingMethod.ReflectedType.FullName + ": " + callingMethod.Name;

Show or hide element in React

Simple hide/show example with React Hooks: (srry about no fiddle)

const Example = () => {

  const [show, setShow] = useState(false);

  return (
    <div>
      <p>Show state: {show}</p>
      {show ? (
        <p>You can see me!</p>
      ) : null}
      <button onClick={() => setShow(!show)}>
    </div>
  );

};

export default Example;

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

In my case, this error occured when creating a new Android Studio (Android studio 3.2.1) Java Project with

    classpath 'com.android.tools.build:gradle:2.0.0-beta6'

So I´ve downgraded to

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

Not the best solution stay at an older version, but maybe it´s just a temporary bug in the beta as the NDK path in local.properties is still the same, but the IDE doesn´t complain anymore

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

How can I make a div not larger than its contents?

OK, in many cases you even don't need to do anything as by default div has height and width as auto, but if it's not your case, applying inline-block display gonna work for you... look at the code I create for you and it's do what you looking for:

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>_x000D_
      <td>Nunc auctor aliquam est ac viverra. Sed enim nisi, feugiat sed accumsan eu, convallis eget felis. Pellentesque consequat eu leo nec pharetra. Aenean interdum enim dapibus diam.</td>_x000D_
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Change the color of a checked menu item in a navigation drawer

One need to set NavigateItem checked true whenever item in NavigateView is clicked

//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);

Add NavigationItemSelectedListener on NavigationView

  @Override
  public boolean onNavigationItemSelected(final MenuItem menuItem) {
    // update highlighted item in the navigation menu
    menuItem.setChecked(true);
    mNavItemId = menuItem.getItemId();

    // allow some time after closing the drawer before performing real navigation
    // so the user can see what is happening
    mDrawerLayout.closeDrawer(GravityCompat.START);
    mDrawerActionHandler.postDelayed(new Runnable() {
      @Override
      public void run() {
        navigate(menuItem.getItemId());
      }
    }, DRAWER_CLOSE_DELAY_MS);
    return true;
  }

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

How to terminate the script in JavaScript?

i use this piece of code to stop execution:

throw new FatalError("!! Stop JS !!");

you will get a console error though but it works good for me.

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

In Angular, how do you determine the active route?

As of Angular 8, this works:

<li routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
    <a [routerLink]="['/']">Home</a>
</li>

{ exact: true } ensures it matches the url.

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

How to change the link color in a specific class for a div CSS

how about something like this ...

a.register:link{
    color:#FFFFFF;
}

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

How to both read and write a file in C#

var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);

...

fs.Close();
//or sw.Close();

The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.

How to import RecyclerView for Android L-preview

This works for me

Define internet permission

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

Add dependency

compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile ('com.squareup.retrofit2:converter-simplexml:2.1.0'){
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
        exclude group: 'xpp3', module: 'xpp3'
    }

In Main Activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class MainActivity extends AppCompatActivity {
    private BreakfastMenu breakfastMenu;
    List<BreakfastMenu> list;
    TextView responseText;
    APIInterface apiInterface;
    String name;
    String price;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        responseText=(TextView)findViewById(R.id.reponseText);
        apiInterface = APIClient.getClient().create(APIInterface.class);


        /**
         GET List Resources
         **/
        Call<BreakfastMenu> call = apiInterface.getBreakfastMenu();
        call.enqueue(new Callback<BreakfastMenu>() {
            @Override
            public void onResponse(Call<BreakfastMenu> call, Response<BreakfastMenu> response) {
               Log.d("TAG", response.code() + "");

                String displayResponse = "";
                BreakfastMenu resource = response.body();
                System.out.println(displayResponse+"display response   ");

                for (Food food : resource.getFoodList())
                {
                    name=food.getName();
                    price=food.getPrice();
                    System.out.println(name+price+"=========================================");
                    displayResponse += food.getName() + " " + food.getPrice()+"\n"+"\n";
                    Toast.makeText(MainActivity.this,name+price,Toast.LENGTH_LONG).show();
                }
                responseText.setText(displayResponse);

            }

            @Override
            public void onFailure(Call<BreakfastMenu> call, Throwable t) {
                call.cancel();
            }
        });

    }
}

Make APIClient.java class

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();


        retrofit = new Retrofit.Builder()
                .baseUrl("https://www.w3schools.com/")
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();



        return retrofit;
    }

}

    enter code here

Make APIInterface.java

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Query;

interface APIInterface {

    @GET("xml/simple.xml")
    @Headers({"Accept: application/xml",
            "User-Agent: Retrofit-Sample-App"})
    Call<BreakfastMenu> getBreakfastMenu();
}

In BreakfastMenu.java

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

import java.util.List;

@Root(name = "breakfast_menu")
public class BreakfastMenu
{

    @ElementList(inline = true)
    private List<Food> foodList;

    public BreakfastMenu()
    {
    }

    public List<Food> getFoodList()
    {
        return foodList;
    }

    public void setFoodList(List<Food> foodList)
    {
        this.foodList = foodList;
    }
}

Make Food.java

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "food")
public class Food
{

    @Element(name = "name")
    private String name;

    @Element(name = "price")
    private String price;

    @Element(name = "description")
    private String description;

    @Element(name = "calories")
    private String calories;

    public Food()
    {
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getPrice()
    {
        return price;
    }

    public void setPrice(String price)
    {
        this.price = price;
    }

    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public String getCalories()
    {
        return calories;
    }

    public void setCalories(String calories)
    {
        this.calories = calories;
    }
}

In activity_main.xml

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

        <TextView
            android:id="@+id/reponseText"
            android:layout_width="match_parent"
            android:layout_height="600dp"
          />


</Linear Layout>

javascript getting my textbox to display a variable

Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.

The HTML

    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla"/></td>
    </tr>
    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla."/></td>
    </tr>

The script

$(document).ready(function(){
                $(".class_name").each(function(){
                    $(this).keyup(function(){
                        calculateSum()
                        ;})
                    ;})
                ;}
                );
            function calculateSum(){
                var sum=0;
                $(".class_name").each(function(){
                    if(!isNaN(this.value) && this.value.length!=0){
                        sum+=parseFloat(this.value);
                    }
                    else if(isNaN(this.value)) {
                        alert("Maybe an alert if they type , instead of .");
                    }
                }
                );
                $("#sum").html(sum.toFixed(2));
                } 

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I kept running into the issue and saw that all my certs were invalidated -- oh no!

It turns out I never deleted the expired cert. It was not showing up for me, until I selected from Keychain Access application:

View->Show Expired Certificates

then

System->All Items

will finally display that gnarly expired cert. Delete that and retry from XCode will pick up the new valid certs.

Just make sure you search "All Items" in the Keychain Access app. The invalidated certs are a result of pointing to the expired certificate that has not been deleted yet.

How do I prevent mails sent through PHP mail() from going to spam?

<?php

$subject = "this is a subject";
$message = "testing a message";




  $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
  $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
  $headers .= "From: The Sender <[email protected]>\r\n";  
  $headers .= "Organization: Sender Organization\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
  $headers .= "X-Priority: 3\r\n";
  $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;



mail("[email protected]", $subject, $message, $headers); 


?> 

jQuery: checking if the value of a field is null (empty)

My Working solution is

var town_code = $('#town_code').val(); 
 if(town_code.trim().length == 0){
    var town_code = 0;
 }

Add Expires headers

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On 

    # Default directive
    ExpiresDefault "access plus 1 month"

    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"

    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"

    # CSS
    ExpiresByType text/css "access plus 1 month"

    # Javascript
    ExpiresByType application/javascript "access plus 1 year"
</IfModule>

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

How can I refresh or reload the JFrame?

Here's a short code that might help.

    <yourJFrameName> main = new <yourJFrameName>();    

    main.setVisible(true);
    this.dispose();

where...

main.setVisible(true);

will run the JFrame again.

this.dispose();

will terminate the running window.

How to install plugin for Eclipse from .zip

This is the easiest way that I found to install a plugin locally at eclipse -

enter image description here

Easiest way to toggle 2 classes in jQuery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

$('body').toggle2classes('a', 'b');

How to access the first property of a Javascript object?

You can use Object.prototype.keys which returns all the keys of an object in the same order. So if you want the first object just get that array and use the first element as desired key.

const o = { "key1": "value1", "key2": "value2"};
const idx = 0; // add the index for which you want value
var key = Object.keys(o)[idx];
value = o[key]
console.log(key,value); // key2 value2

How to hide the soft keyboard from inside a fragment?

Nothing of this worked on API27. I had to add this in the container of the layout, for me it was a ConstraintLayout:

<android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:focusedByDefault="true">

//Your layout

</android.support.constraint.ConstraintLayout>

Django check for any exists for a query

this worked for me!

if some_queryset.objects.all().exists(): print("this table is not empty")

go get results in 'terminal prompts disabled' error for github private repo

From go 1.13 onwards, if you had already configured your terminal with the git credentials and yet facing this issue, then you could try setting the GOPRIVATE environment variable. Setting this environment variable solved this issue for me.

export GOPRIVATE=github.com/{organizationName/userName of the package}/*  

Switch android x86 screen resolution

To change the Android-x86 screen resolution on VirtualBox you need to:

  1. Add custom screen resolution:
    Android <6.0:

    VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x16"
    

    Android >=6.0:

    VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"
    
  2. Figure out what is the ‘hex’-value for your VideoMode:
    2.1. Start the VM
    2.2. In GRUB menu enter a (Android >=6.0: e)
    2.3. In the next screen append vga=ask and press Enter
    2.4. Find your resolution and write down/remember the 'hex'-value for Mode column

  3. Translate the value to decimal notation (for example 360 hex is 864 in decimal).

  4. Go to menu.lst and modify it:
    4.1. From the GRUB menu select Debug Mode
    4.2. Input the following:

    mount -o remount,rw /mnt  
    cd /mnt/grub  
    vi menu.lst
    

    4.3. Add vga=864 (if your ‘hex’-value is 360). Now it should look like this:

    kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode DPI=160 UVESA_MODE=320x480 SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img vga=864

    4.4. Save it:

    :wq
    
  5. Unmount and reboot:

    cd /
    umount /mnt
    reboot -f
    

Hope this helps.

<code> vs <pre> vs <samp> for inline and block code snippets

Consider TextArea

People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea> which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>, I find <textarea readonly> is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea> might appear within).

For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly> your html or etc with any characters including tabs and CrLf's </textarea>.

_x000D_
_x000D_
<textarea rows=5 cols=100 readonly>Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

To compare all...

_x000D_
_x000D_
<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>_x000D_
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>_x000D_
    _x000D_
    _x000D_
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;</textarea>_x000D_
_x000D_
<xmp>XMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; (&) will not act as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</xmp>_x000D_
_x000D_
<pre>PRE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</pre>_x000D_
_x000D_
<samp>SAMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</samp>_x000D_
_x000D_
<code>CODE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</code>
_x000D_
_x000D_
_x000D_

Avoid dropdown menu close on click inside

You could simply execute event.stopPropagation on click event of the links themselves. Something like this.

    $(".dropdown-menu a").click((event) => {
         event.stopPropagation()
         let url = event.target.href
         //Do something with the url or any other logic you wish
    })

Edit: If someone saw this answer and is using react, it will not work. React handle the javascript events differently and by the time your react event handler is being called, the event has already been fired and propagated. To overcome that you should attach the event manually like that

handleMenuClick(event) {
   event.stopPropagation()
   let menu_item = event.target
   //implement your logic here.
}
componentDidMount() {
    document.getElementsByClassName("dropdown-menu")[0].addEventListener(
        "click", this.handleMenuClick.bind(this), false)
   }
}

How to resolve the error on 'react-native start'

This is caused by node v12.11.0 due to the way it deals regular location there two ways to solve this problem

Method I

You can downgrade to node v12.10.0 this will apply the correct way to deal with parsing error

Method II

You can correctly terminate the regular expression in you case by changing the file located a:

\node_modules\metro-config\src\defaults\blacklist.js

From:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To:

 var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

How to get start and end of previous month in VB

I have similar formula for the First and Last Day

The First Day of the month

FirstDay = DateSerial(Year(Date),Month(Date),1)

The zero Day of the next month is the Last Day of the month

LastDay = DateSerial(Year(Date),Month(Date)+ 1,0) 

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

How do I find files that do not contain a given string pattern?

Problem

I need to refactor a large project which uses .phtml files to write out HTML using inline PHP code. I want to use Mustache templates instead. I want to find any .phtml giles which do not contain the string new Mustache as these still need to be rewritten.

Solution

find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

Explanation

Before the pipes:

Find

find . Find files recursively, starting in this directory

-iname '*.phtml' Filename must contain .phtml (the i makes it case-insensitive)

-exec 'grep -H -E -o -c 'new Mustache' {}' Run the grep command on each of the matched paths

Grep

-H Always print filename headers with output lines.

-E Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

-o Prints only the matching part of the lines.

-c Only a count of selected lines is written to standard output.


This will give me a list of all file paths ending in .phtml, with a count of the number of times the string new Mustache occurs in each of them.

$> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/orders.phtml:1
./app/MyApp/Customer/View/Account/banking.phtml:1
./app/MyApp/Customer/View/Account/applycomplete.phtml:1
./app/MyApp/Customer/View/Account/catalogue.phtml:1
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The first pipe grep :0$ filters this list to only include lines ending in :0:

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The second pipe sed 's/..$//' strips off the final two characters of each line, leaving just the file paths.

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
./app/MyApp/Customer/View/Account/studio.phtml
./app/MyApp/Customer/View/Account/classadd.phtml
./app/MyApp/Customer/View/Account/orders-trade.phtml

PHP find difference between two datetimes

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

How to print the full NumPy array, without truncation?

Suppose you have a numpy array

 arr = numpy.arange(10000).reshape(250,40)

If you want to print the full array in a one-off way (without toggling np.set_printoptions), but want something simpler (less code) than the context manager, just do

for row in arr:
     print row 

Rounding up to next power of 2

next = pow(2, ceil(log(x)/log(2)));

This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power.

This is a more general purpose (i.e. slower!) method than the bitwise methods linked elsewhere, but good to know the maths, eh?

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


How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

How to apply !important using .css()?

There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

Just overwrite style, but you don't have to parse anything, why would you?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty(), because it won't remove !important rules in Chrome.
Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.

Open window in JavaScript with HTML inserted

When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.

Here is an example:

var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');

Virtual Memory Usage from Java under Linux, too much memory used

Just a thought, but you may check the influence of a ulimit -v option.

That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Reactjs setState() with a dynamic key name?

I had a similar problem.

I wanted to set the state of where the 2nd level key was stored in a variable.

e.g. this.setState({permissions[perm.code]: e.target.checked})

However this isn't valid syntax.

I used the following code to achieve this:

this.setState({
  permissions: {
    ...this.state.permissions,
    [perm.code]: e.target.checked
  }
});

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

What is the Python equivalent of Matlab's tic and toc functions?

The absolute best analog of tic and toc would be to simply define them in python.

def tic():
    #Homemade version of matlab tic and toc functions
    import time
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()

def toc():
    import time
    if 'startTime_for_tictoc' in globals():
        print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
    else:
        print "Toc: start time not set"

Then you can use them as:

tic()
# do stuff
toc()

jQuery hasClass() - check for more than one class

$.fn.extend({
    hasClasses: function (selectors) {
        var self = this;
        for (var i in selectors) {
            if ($(self).hasClass(selectors[i])) 
                return true;
        }
        return false;
    }
});

$('#element').hasClasses(['class1', 'class2', 'class3']);

This should do it, simple and easy.

How to add an extra source directory for maven to compile and include in the build jar?

You can add the directories for your build process like:

    ...
   <resources>
     <resource>
       <directory>src/bootstrap</directory>
     </resource>
   </resources>
   ...

The src/main/java is the default path which is not needed to be mentioned in the pom.xml

TypeError: p.easing[this.easing] is not a function

Including this worked for me.

Please include the line mentioned below in the section.

<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js'>

Inserting data into a MySQL table using VB.NET

You need to open the connection first:

 SQLConnection.Open();

Unknown Column In Where Clause

For me the root of the problem was a number which I copied to use in a WHERE clause. The number had "invisible" symbol, at least for MySQL Workbench. I placed the number in the Chrome console it was clearly visible.

Get the current date and time

Try this one:

System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

How to add an image in Tkinter?

Just convert the jpg format image into png format. It will work 100%.

Check if string matches pattern

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

Running Python code in Vim

A simple method would be to type : while in normal mode, and then press the up arrow key on the keyboard and press Enter. This will repeat the last typed commands on VIM.

How to split a delimited string in Ruby and convert it to an array?

>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

Or for integers:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

Or for later versions of ruby (>= 1.9 - as pointed out by Alex):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]

How can I parse a String to BigDecimal?

Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)

You can directly instanciate the BigDecimal with the String ;)

Example:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

How to squash all git commits into one?

Since I had some trouble with the solutions proposed here, I want to share a really simple solution (to squash all commits on a feature branch into one):

git merge origin/master && git reset --soft origin/master

The preceding merge cmd ensures, that no recent changes from master will go on your head when committing! After that, just commit the changes and do git push -f

iOS 7: UITableView shows under status bar

This is how to write it in "Swift" An adjustment to @lipka's answer:

tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

How can I uninstall Ruby on ubuntu?

On Lubuntu, I just tried apt-get purge ruby* and as well as removing ruby, it looks like this command tried to remove various things to do with GRUB, which is a bit worrying for next time I want to reboot my computer. I can't yet say if any damage has really been done.

PHP Remove elements from associative array

Your array is quite strange : why not just use the key as index, and the value as... the value ?

Wouldn't it be a lot easier if your array was declared like this :

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);

That would allow you to use your values of key as indexes to access the array...

And you'd be able to use functions to search on the values, such as array_search() :

$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);

$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);

var_dump($array);

Easier than with your array, no ?



Instead, with your array that looks like this :

$array = array(
    array('key' => 1, 'value' => 'Awaiting for Confirmation'), 
    array('key' => 2, 'value' => 'Asssigned'), 
    array('key' => 3, 'value' => 'In Progress'), 
    array('key' => 4, 'value' => 'Completed'), 
    array('key' => 5, 'value' => 'Mark As Spam'), 
);

You'll have to loop over all items, to analyse the value, and unset the right items :

foreach ($array as $index => $data) {
    if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
        unset($array[$index]);
    }
}
var_dump($array);

Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?

Can't resolve module (not found) in React.js

I faced the same issue when I created a new react app, I tried all options in https://github.com/facebook/create-react-app/issues/2534 but it didn't help. I had to change the port for the new app and then it worked. By default, apps use the port 3000.I changed the port to 8001 in package.json as follows:

  "scripts": {
    "start": "PORT=8001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

How do I find a default constraint using INFORMATION_SCHEMA?

How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:

    select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name
          from information_schema.columns columns
             inner join information_schema.constraint_column_usage usage on 
                  columns.column_name = usage.column_name and columns.table_name = usage.table_name
             inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name
    where columns.column_default is not null

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

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

You can access the environment variables by:

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

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

Path Updates:

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

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

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

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

Find if a String is present in an array

String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

You don't have to do it this complicated way. If you are using XCode 5 (which I am sure most of us are) then create your icons call them whatever you like i.e.

  • myIcon-58.png
  • myIcon-57.png
  • myIcon-72.png
  • myIcon-80.png
  • myIcon-100.png ....

And drag and drop them on to the correct boxes under AppIcon. See screenshots. You don't have to manually edit plist file.

enter image description here enter image description here enter image description here

How to get 0-padded binary representation of an integer in java?

try...

String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));

I dont think this is the "correct" way to doing this... but it works :)

MySQL Error: : 'Access denied for user 'root'@'localhost'

  1. Open & Edit /etc/my.cnf or /etc/mysql/my.cnf, depending on your distro.
  2. Add skip-grant-tables under [mysqld]
  3. Restart Mysql
  4. You should be able to login to mysql now using the below command mysql -u root -p
  5. Run mysql> flush privileges;
  6. Set new password by ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
  7. Go back to /etc/my.cnf and remove/comment skip-grant-tables
  8. Restart Mysql
  9. Now you will be able to login with the new password mysql -u root -p

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How to change DataTable columns order

This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.

public static class DataTableExtensions
{
    /// <summary>
    /// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
    /// </summary>
    /// <param name="table"></param>
    /// <param name="columnNames"></param>
    /// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
    public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
    {
        List<string> listColNames = columnNames.ToList();

        //Remove invalid column names.
        foreach (string colName in columnNames)
        {
            if (!dtbl.Columns.Contains(colName))
            {
                listColNames.Remove(colName);
            }
        }

        foreach (string colName in listColNames)
        {
            dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
        }
}

How do I make a Git commit in the past?

Or just use a fake-git-history to generate it for a specific data range.

Correct way to focus an element in Selenium WebDriver using Java

C# extension method code, focus element, enter text, call change().

public static void EnterText(this IWebDriver driver, IWebElement element, string textToEnter)
    {
        var js = (IJavaScriptExecutor)driver;
        js.ExecuteScript("arguments[0].focus();", element);
        js.ExecuteScript("arguments[0].setAttribute('value', arguments[1])", element, textToEnter);
        js.ExecuteScript("$(arguments[0]).change();", element);
    }

Called by:

driver.EnterText(element, text);

TypeError: $(...).modal is not a function with bootstrap Modal

Check that jquery library not included in html that load via Ajax .remove <script src="~/Scripts/jquery[ver].js"></script> in your AjaxUpdate/get_modal

Linear regression with matplotlib / numpy

Another quick and dirty answer is that you can just convert your list to an array using:

import numpy as np
arr = np.asarray(listname)

Understanding repr( ) function in Python

The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?

I'm not sure what you're asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr.

Also note that the eval(repr(x)) == x analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr output.

jquery clear input default value

You may use this..

<body>
    <form method="" action="">
        <input type="text" name="email" class="input" />
        <input type="submit" value="Sign Up" class="button" />
    </form>
</body>

<script>
    $(document).ready(function() {
        $(".input").val("Email Address");
        $(".input").on("focus", function() {
            $(".input").val("");
        });
        $(".button").on("click", function(event) {
            $(".input").val("");
        });
    });
</script>

Talking of your own code, the problem is that the attr api of jquery is set by

$('.input').attr('value','Email Adress');

and not as you have done:

$('.input').attr('value') = 'Email address';

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

.prop('checked',false) or .removeAttr('checked')?

I recommend to use both, prop and attr because I had problems with Chrome and I solved it using both functions.

if ($(':checkbox').is(':checked')){
    $(':checkbox').prop('checked', true).attr('checked', 'checked');
}
else {
    $(':checkbox').prop('checked', false).removeAttr('checked');
}

How to resize an image with OpenCV2.0 and Python2.6

Example doubling the image size

There are two ways to resize an image. The new size can be specified:

  1. Manually;

    height, width = src.shape[:2]

    dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

  2. By a scaling factor.

    dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

Example shrink image to fit a max height/width (keeping aspect ratio)

import cv2

img = cv2.imread('YOUR_PATH_TO_IMG')

height, width = img.shape[:2]
max_height = 300
max_width = 300

# only shrink if img is bigger than required
if max_height < height or max_width < width:
    # get scaling factor
    scaling_factor = max_height / float(height)
    if max_width/float(width) < scaling_factor:
        scaling_factor = max_width / float(width)
    # resize image
    img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

cv2.imshow("Shrinked image", img)
key = cv2.waitKey()

Using your code with cv2

import cv2 as cv

im = cv.imread(path)

height, width = im.shape[:2]

thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)

cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()

Declaring a custom android UI element using XML

Thanks a lot for the first answer.

As for me, I had just one problem with it. When inflating my view, i had a bug : java.lang.NoSuchMethodException : MyView(Context, Attributes)

I resolved it by creating a new constructor :

public MyView(Context context, AttributeSet attrs) {
     super(context, attrs);
     // some code
}

Hope this will help !

How to open local files in Swagger-UI

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",

jQuery Ajax error handling, show custom exception messages

If making a call to asp.net, this will return the error message title:

I didn't write all of formatErrorMessage myself but i find it very useful.

function formatErrorMessage(jqXHR, exception) {

    if (jqXHR.status === 0) {
        return ('Not connected.\nPlease verify your network connection.');
    } else if (jqXHR.status == 404) {
        return ('The requested page not found. [404]');
    } else if (jqXHR.status == 500) {
        return ('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
        return ('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        return ('Time out error.');
    } else if (exception === 'abort') {
        return ('Ajax request aborted.');
    } else {
        return ('Uncaught Error.\n' + jqXHR.responseText);
    }
}


var jqxhr = $.post(addresshere, function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) { 

    var responseTitle= $(xhr.responseText).filter('title').get(0);
    alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) ); 
})

How do I crop an image in Java?

You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package.

For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel.

Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged method...

For a mousedragged action, you will get the coordinate of the rectangle form by the drag...

Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....

And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!

Python script to copy text to clipboard

To use native Python directories, use:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

on Mac, instead:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|pbcopy'
    return subprocess.check_call(cmd, shell=True)

Then use:

copy2clip('This is on my clipboard!')

to call the function.

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

Add custom buttons on Slick Carousel

I know this is an old question, but maybe I can be of help to someone, bc this also stumped me until I read the documentation a bit more:

prevArrow string (html|jQuery selector) | object (DOM node|jQuery object) Previous Allows you to select a node or customize the HTML for the "Previous" arrow.

nextArrow string (html|jQuery selector) | object (DOM node|jQuery object) Next Allows you to select a node or customize the HTML for the "Next" arrow.

this is how i changed my buttons.. worked perfectly.

  $('.carousel-content').slick({
      prevArrow:"<img class='a-left control-c prev slick-prev' src='../images/shoe_story/arrow-left.png'>",
      nextArrow:"<img class='a-right control-c next slick-next' src='../images/shoe_story/arrow-right.png'>"
  });

Twitter Bootstrap carousel different height images cause bouncing arrows

This jQuery function worked best for me. I'm using bootstrap 4 within a WordPress theme and I've used the full jQuery instead of jQuery slim.

// Set all carousel items to the same height
function carouselNormalization() {

    window.heights = [], //create empty array to store height values
    window.tallest; //create variable to make note of the tallest slide

    function normalizeHeights() {
        jQuery('#latest-blog-posts .carousel-item').each(function() { //add heights to array
            window.heights.push(jQuery(this).outerHeight());
        });
        window.tallest = Math.max.apply(null, window.heights); //cache largest value
        jQuery('#latest-blog-posts .carousel-item').each(function() {
            jQuery(this).css('min-height',tallest + 'px');
        });
    }
    normalizeHeights();

    jQuery(window).on('resize orientationchange', function () {

        window.tallest = 0, window.heights.length = 0; //reset vars
        jQuery('.sc_slides .item').each(function() {
            jQuery(this).css('min-height','0'); //reset min-height
        }); 

        normalizeHeights(); //run it again 

    });

}

jQuery( document ).ready(function() {
    carouselNormalization();
});

Source:

https://gist.github.com/mbacon40/eff3015fe96582806da5

How to remove border of drop down list : CSS

select#xyz {
  border:0px;
  outline:0px;
}

Exact solution.

Converting between java.time.LocalDateTime and java.util.Date

Much more convenient way if you are sure you need a default timezone :

Date d = java.sql.Timestamp.valueOf( myLocalDateTime );

How do I get the SharedPreferences from a PreferenceActivity in Android?

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.

(1) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove() and clear() to delete the preference values from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

What's the best way to check if a file exists in C?

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

How to get client IP address using jQuery

jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON method, for example:

_x000D_
_x000D_
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
    console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

This example is of a really simple JSONP service implemented on with api.ipify.org.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

How to save final model using keras?

you can save the model and load in this way.

from keras.models import Sequential, load_model
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss':crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

Display label text with line breaks in c#

You can also use <br/> where you want to break the text.

What does MissingManifestResourceException mean and how to fix it?

I was getting the MissingManifestResourceException error after I ported my project from VS2005 to VS2010. I didn't have any other classes defined in the file that contains my Form class. And I also had my resx Resource File Name set correctly. Didn't work.

So I deleted the resx files and regenerated them. All good now.

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Returning string from C function

Your pointer is pointing to local variable of the function. So as soon as you return from the function, memory gets deallocated. You have to assign memory on heap in order to use it in other functions.

Instead char *rtnPtr = word;

do this char *rtnPtr = malloc(length);

So that it is available in the main function. After it is used free the memory.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

How to dismiss notification after action has been clicked

In new APIs don't forget about TAG:

notify(String tag, int id, Notification notification)

and correspondingly

cancel(String tag, int id) 

instead of:

cancel(int id)

https://developer.android.com/reference/android/app/NotificationManager

Play sound file in a web-page in the background

<audio src="/music/good_enough.mp3" autoplay>
<p>If you are reading this, it is because your browser does not support the audio element.     </p>
<embed src="/music/good_enough.mp3" width="180" height="90" hidden="true" />
</audio>

Works for me just fine.

Plotting time-series with Date labels on x-axis

It's possible in ggplot and you can use scale_date for this task

 library(ggplot2)  
 Lines <- "Date            Visits
    11/1/2010   696537
    11/2/2010   718748
    11/3/2010   799355
    11/4/2010   805800
    11/5/2010   701262
    11/6/2010   531579
    11/7/2010   690068
    11/8/2010   756947
    11/9/2010   718757
    11/10/2010  701768
    11/11/2010  820113
    11/12/2010  645259"
    dm <- read.table(textConnection(Lines), header = TRUE)
    dm <- mutate(dm, Date = as.Date(dm$Date, "%m/%d/%Y"))
    ggplot(data = dm, aes(Date, Visits)) + 
    geom_line() + 
    scale_x_date(format = "%b %d", major =  "1 day")

Can we have functions inside functions in C++?

All this tricks just look (more or less) as local functions, but they don't work like that. In a local function you can use local variables of it's super functions. It's kind of semi-globals. Non of these tricks can do that. The closest is the lambda trick from c++0x, but it's closure is bound in definition time, not the use time.

How to get the server path to the web directory in Symfony2 from inside the controller?

To access the root directory from outside the controller you can simply inject %kernel.root_dir% as an argument in your services configuration.

service_name:
    class: Namespace\Bundle\etc
    arguments: ['%kernel.root_dir%']

Then you can get the web root in the class constructor:

public function __construct($rootDir)
{
    $this->webRoot = realpath($rootDir . '/../web');
}

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

Clear text area

This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.

$('textarea').empty()

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

S3 limit to objects in a bucket

According to Amazon:

Write, read, and delete objects containing from 0 bytes to 5 terabytes of data each. The number of objects you can store is unlimited.

Source: http://aws.amazon.com/s3/details/ as of Sep 3, 2015.

this in equals method

You have to look how this is called:

someObject.equals(someOtherObj); 

This invokes the equals method on the instance of someObject. Now, inside that method:

public boolean equals(Object obj) {   if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj?     return true;//If so, these are the same objects, and return true   } 

You can see that this is referring to the instance of the object that equals is called on. Note that equals() is non-static, and so must be called only on objects that have been instantiated.

Note that == is only checking to see if there is referential equality; that is, the reference of this and obj are pointing to the same place in memory. Such references are naturally equal:

Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place 

Further note that equals() is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:

FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing. 

Delete element in a slice

Where a is the slice, and i is the index of the element you want to delete:

a = append(a[:i], a[i+1:]...)

... is syntax for variadic arguments in Go.

Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println can take as many arguments as you want).

Now, when calling a function, ... does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.

So what this line does:

a = append(a[:0], a[1:]...)

is essentially:

a = append(a[:0], a[1], a[2])

Now, you may be wondering, why not just do

a = append(a[1:]...)

Well, the function definition of append is

func append(slice []Type, elems ...Type) []Type

So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Python: Converting string into decimal number

A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s

What is time(NULL) in C?

You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.

Zookeeper connection error

This can happen if there are too many open connections.

Try increasing the maxClientCnxns setting.

From documentation:

maxClientCnxns (No Java system property)

Limits the number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. This is used to prevent certain classes of DoS attacks, including file descriptor exhaustion. Setting this to 0 or omitting it entirely removes the limit on concurrent connections.

You can edit settings in the config file. Most likely it can be found at /etc/zookeeper/conf/zoo.cfg.

In modern ZooKeeper versions default value is 60. You can increase it by adding the maxClientCnxns=4096 line to the end of the config file.

How do I check if a string contains a specific word?

Use:

$a = 'How are you?';
if (mb_strpos($a, 'are')) {
    echo 'true';
}

It performs a multi-byte safe strpos() operation.

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

I like this method, because it is readable and avoids multiple iterations of the directory:

var allowedExtensions = new [] {".doc", ".docx", ".pdf", ".ppt", ".pptx", ".xls", ".xslx"}; 
var files = Directory
    .GetFiles(folder)
    .Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
    .ToList();

How to auto import the necessary classes in Android Studio with shortcut?

File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with

enter image description here

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

How do I open port 22 in OS X 10.6.7

There are 3 solutions available for these.

1) Enable remote login using below command - sudo systemsetup -setremotelogin on

2) In Mac, go to System Preference -> Sharing -> enable Remote Login that's it. 100% working solution

3) Final and most important solution is - Check your private area network connection . Sometime remote login isn't allow inside the local area network.

Kindly try to connect your machine using personal network like mobile network, Hotspot etc.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Do you mean like this?

import string
astr='a(b[c])d'

deleter=string.maketrans('()[]','    ')
print(astr.translate(deleter))
# a b c  d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a

how to convert a string to an array in php

Take a look at the explode function.

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

How to convert list data into json in java

i wrote my own function to return list of object for populate combo box :

public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
        try {
            Object[] args={};
            Class cl = Class.forName(kelas);
            Method getName = cl.getMethod(name, null);
            Method getLabel = cl.getMethod(label, null);
            String json="[";
            for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if(i>0){
                json+=",";
            }
            json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
            //System.out.println("Object = " + i+" -> "+o.getNumber());
            }
            json+="]";
            return json;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            System.out.println("Error in get JSON List");
            ex.printStackTrace();
        }
        return "";
    }

and call it from anywhere like :

String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");

PostgreSQL column 'foo' does not exist

I fixed similar issues by qutating column name

SELECT * from table_name where "foo" is NULL;

In my case it was just

SELECT id, "foo" from table_name;

without quotes i'v got same error.

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

use current date as default value for a column

You can use:

Insert into Event(Description,Date) values('teste', GETDATE());

Also, you can change your table so that 'Date' has a default, "GETDATE()"

Runtime vs. Compile time

Following from previous similar answer of question What is the difference between run-time error and compiler error?

Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int as Int.

Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn't exist, will result in a runtime error.

Read more about all programming errors here

How do I drop table variables in SQL-Server? Should I even do this?

if somebody else comes across this... and you really need to drop it like while in a loop, you can just delete all from the table variable:

DELETE FROM @tableVariableName

How do I sort a dictionary by value?

As simple as: sorted(dict1, key=dict1.get)

Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

How To Raise Property Changed events on a Dependency Property?

I agree with Sam and Xaser and have actually taken this a bit farther. I don't think you should be implementing the INotifyPropertyChanged interface in a UserControl at all...the control is already a DependencyObject and therefore already comes with notifications. Adding INotifyPropertyChanged to a DependencyObject is redundant and "smells" wrong to me.

What I did is implement both properties as DependencyProperties, as Sam suggests, but then simply had the PropertyChangedCallback from the "first" dependency property alter the value of the "second" dependency property. Since both are dependency properties, both will automatically raise change notifications to any interested subscribers (e.g. data binding etc.)

In this case, dependency property A is the string InviteText, which triggers a change in dependency property B, the Visibility property named ShowInvite. This would be a common use case if you have some text that you want to be able to hide completely in a control via data binding.

public string InviteText  
{
    get { return (string)GetValue(InviteTextProperty); }
    set { SetValue(InviteTextProperty, value); }
}

public static readonly DependencyProperty InviteTextProperty =
    DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));

private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    InvitePrompt prompt = d as InvitePrompt;
    if (prompt != null)
    {
        string text = e.NewValue as String;
        prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
    }
}

public Visibility ShowInvite
{
    get { return (Visibility)GetValue(ShowInviteProperty); }
    set { SetValue(ShowInviteProperty, value); }
}

public static readonly DependencyProperty ShowInviteProperty =
    DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));

Note I'm not including the UserControl signature or constructor here because there is nothing special about them; they don't need to subclass from INotifyPropertyChanged at all.