Programs & Examples On #Fssm

The File System State Monitor keeps track of the state of any number of paths and will fire events when said state changes.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Bundler 2

If you need to update from bundler v1 to v2 follow this official guide.

For a fast solution:

  1. In root fo your application run bundle config set path "/bundle" to add a custom path for bundler use, in this case I set /bundle, you can use whatever.

    1.2 [Alternative solution] You can use a bundler file (~/.bundle/config) also, to use this I recommend set bundler folders in environment, like a Docker image, for example. Here the official guide.

  2. You don't need to delete your Gemfile.lock, It's a bad practice and this can cause other future problems. Commit Gemfile.lock normaly, sometimes you need to update your bundle with bundle install or install individual gem.

You can see all the configs for bundler version 2 here.

Multiple GitHub Accounts & SSH Config

I posted the technique I use to deal with these here

Mongoose: Find, modify, save

The user parameter of your callback is an array with find. Use findOne instead of find when querying for a single instance.

User.findOne({username: oldUsername}, function (err, user) {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

Fastest way to extract frames using ffmpeg?

Output one image every minute, named img001.jpg, img002.jpg, img003.jpg, etc. The %03d dictates that the ordinal number of each output image will be formatted using 3 digits.

ffmpeg -i myvideo.avi -vf fps=1/60 img%03d.jpg

Change the fps=1/60 to fps=1/30 to capture a image every 30 seconds. Similarly if you want to capture a image every 5 seconds then change fps=1/60 to fps=1/5

SOURCE: https://trac.ffmpeg.org/wiki/Create a thumbnail image every X seconds of the video

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

According to this SO thread, the solution is to use the non-primitive wrapper types; e.g., Integer instead of int.

How can I expose more than 1 port with Docker?

Use this as an example:

docker create --name new_ubuntu -it -p 8080:8080 -p  15672:15672 -p 5432:5432   ubuntu:latest bash

look what you've created(and copy its CONTAINER ID xxxxx):

docker ps -a 

now write the miracle maker word(start):

docker start xxxxx

good luck

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

convert string to specific datetime format?

No need to apply anything. Just add this code at the end of variable to which date is assigned. For example

   @todaydate = "2011-05-19 10:30:14"
   @todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')

You will get proper format as you like. You can check this at Rails Console

Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14"
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :002 > todaytime
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :003 > todaytime.to_time
 => 2011-05-19 10:30:14 UTC
ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
 => "Thu May 19 10:30:14 UTC 2011"

Try 'date_format' gem to show date in different format.

Pythonic way to create a long multi-line string

Generally, I use list and join for multi-line comments/string.

lines = list()
lines.append('SELECT action.enter code here descr as "action", ')
lines.append('role.id as role_id,')
lines.append('role.descr as role')
lines.append('FROM ')
lines.append('public.role_action_def,')
lines.append('public.role,')
lines.append('public.record_def, ')
lines.append('public.action')
query = " ".join(lines)

You can use any string to join all these list elements, like '\n'(newline) or ','(comma) or ' '(space).

How do I create a readable diff of two spreadsheets using git diff?

We faced the exact same issue in our co. Our tests output excel workbooks. Binary diff was not an option. So we rolled out our own simple command line tool. Check out the ExcelCompare project. Infact this allows us to automate our tests quite nicely. Patches / Feature requests quite welcome!

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

How to tell if a <script> tag failed to load

onerror Event

*Update August 2017: onerror is fired by Chrome and Firefox. onload is fired by Internet Explorer. Edge fires neither onerror nor onload. I wouldnt use this method but it could work in some cases. See also

<link> onerror do not work in IE

*

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are:

  • onabort
  • onemptied
  • onstalled
  • onsuspend

In HTML:

element onerror="myScript">

In JavaScript, using the addEventListener() method:

object.addEventListener("error", myScript);

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

Example Execute a JavaScript if an error occurs when loading an image:

img src="image.gif" onerror="myFunction()">

How I can delete in VIM all text from current line to end of file?

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

How to add element in List while iterating in java?

I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll(). This prevents unnecessarily copying a large source list.

Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.

In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.

Timing Delays in VBA

The Timer function also applies to Access 2007, Access 2010, Access 2013, Access 2016, Access 2007 Developer, Access 2010 Developer, Access 2013 Developer. Insert this code to to pause time for certain amount of seconds

T0 = Timer
Do
    Delay = Timer - T0
Loop Until Delay = 1 'Change this value to pause time in second

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

sql searching multiple words in a string

Oracle SQL:

There is the "IN" Operator in Oracle SQL which can be used for that:

select 
    namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi'); 

Center Triangle at Bottom of Div

You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).

.hero:after,
.hero:after {
    z-index: -1;
    position: absolute;
    top: 98.1%;
    left: calc(50% - 25px);
    content: '';
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

How to allow only numeric (0-9) in HTML inputbox using jQuery?

I think it will help everyone

  $('input.valid-number').bind('keypress', function(e) { 
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
  })

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Very simple :

In your Super POM parent or setting.xml, use

        <repository>
        <id>central</id>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <updatePolicy>never</updatePolicy>
        </snapshots>
        <url>http://repo1.maven.org/maven2</url>
        <layout>legacy</layout>
    </repository>

It's my tips

How do you overcome the HTML form nesting limitation?

Well, if you submit a form, browser also sends a input submit name and value. So what yo can do is

<form   
 action="/post/dispatch/too_bad_the_action_url_is_in_the_form_tag_even_though_conceptually_every_submit_button_inside_it_may_need_to_post_to_a_diffent_distinct_url"  
method="post">  

    <input type="text" name="foo" /> <!-- several of those here -->  
    <div id="toolbar">
        <input type="submit" name="action:save" value="Save" />
        <input type="submit" name="action:delete" value="Delete" />
        <input type="submit" name="action:cancel" value="Cancel" />
    </div>
</form>

so on server side you just look for parameter that starts width string "action:" and the rest part tells you what action to take

so when you click on button Save browser sends you something like foo=asd&action:save=Save

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Another way is to use TRANSLATE:

TRANSLATE (col_name, 'x'||CHR(10)||CHR(13), 'x')

The 'x' is any character that you don't want translated to null, because TRANSLATE doesn't work right if the 3rd parameter is null.

Is there an effective tool to convert C# code to Java code?

This is off the cuff, but isn't that what Grasshopper was for?

Using number as "index" (JSON)

Probably you need an array?

var Game = {

    status: [
        ["val", "val","val"],
        ["val", "val", "val"]
    ]
}

alert(Game.status[0][0]);

How to remove elements from a generic list while iterating over it?

Select the elements you do want rather than trying to remove the elements you don't want. This is so much easier (and generally more efficient too) than removing elements.

var newSequence = (from el in list
                   where el.Something || el.AnotherThing < 0
                   select el);

I wanted to post this as a comment in response to the comment left by Michael Dillon below, but it's too long and probably useful to have in my answer anyway:

Personally, I'd never remove items one-by-one, if you do need removal, then call RemoveAll which takes a predicate and only rearranges the internal array once, whereas Remove does an Array.Copy operation for every element you remove. RemoveAll is vastly more efficient.

And when you're backwards iterating over a list, you already have the index of the element you want to remove, so it would be far more efficient to call RemoveAt, because Remove first does a traversal of the list to find the index of the element you're trying to remove, but you already know that index.

So all in all, I don't see any reason to ever call Remove in a for-loop. And ideally, if it is at all possible, use the above code to stream elements from the list as needed so no second data structure has to be created at all.

In Node.js, how do I "include" functions from my other files?

The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename

Note that, as of today, there's a bug in the vm module that prevenst runInThisContext from doing the right when invoked from a new context. This only matters if your main program executes code within a new context and then that code calls runInThisContext. See https://github.com/joyent/node/issues/898

Sadly, the with(global) approach that Fernando suggested doesn't work for named functions like "function foo() {}"

In short, here's an include() function that works for me:

function include(path) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInThisContext(code, path);
}

How to sort ArrayList<Long> in decreasing order?

You can also sort an ArrayList with a TreeSet instead of a comparator. Here's an example from a question I had before for an integer array. I'm using "numbers" as a placeholder name for the ArrayList.


     import.java.util.*;
        class MyClass{
        public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<Integer>(); 

        TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
        numbers = new ArrayList<Integer>(ts);
        System.out.println("\nThe numbers in ascending order are:");
        for(int i=0; i<numbers.size(); i++)
        System.out.print(numbers.get(i).intValue()+" ");
        System.out.println("\nThe numbers in descending order are:");
        for(int i=numbers.size()-1; i>=0; i--)
        System.out.print(numbers.get(i).intValue()+" ");
    }
}

How to handle calendar TimeZones using Java?

public static Calendar convertToGmt(Calendar cal) {

    Date date = cal.getTime();
    TimeZone tz = cal.getTimeZone();

    log.debug("input calendar has date [" + date + "]");

    //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT 
    long msFromEpochGmt = date.getTime();

    //gives you the current offset in ms from GMT at the current date
    int offsetFromUTC = tz.getOffset(msFromEpochGmt);
    log.debug("offset is " + offsetFromUTC);

    //create a new calendar in GMT timezone, set to this date and add the offset
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.setTime(date);
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

    log.debug("Created GMT cal with date [" + gmtCal.getTime() + "]");

    return gmtCal;
}

Here's the output if I pass the current time ("12:09:05 EDT" from Calendar.getInstance()) in:

DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]

12:09:05 GMT is 8:09:05 EDT.

The confusing part here is that Calendar.getTime() returns you a Date in your current timezone, and also that there is no method to modify the timezone of a calendar and have the underlying date rolled also. Depending on what type of parameter your web service takes, your may just want to have the WS deal in terms of milliseconds from epoch.

The real difference between "int" and "unsigned int"

Yes, because in your case they use the same representation.

The bit pattern 0xFFFFFFFF happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.

It's the same as char c = 65. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a.


As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).

The standard points it out in 7.19.6.1-9

If a conversion speci?cation is invalid, the behavior is unde?ned. If any argument is not the correct type for the corresponding conversion speci?cation, the behavior is unde?ned.

How to print Unicode character in C++?

This code works in Linux (C++11, geany, g++ 7.4.0):

#include <iostream>

using namespace std;


int utf8_to_unicode(string utf8_code);
string unicode_to_utf8(int unicode);


int main()
{
    cout << unicode_to_utf8(36) << '\t';
    cout << unicode_to_utf8(162) << '\t';
    cout << unicode_to_utf8(8364) << '\t';
    cout << unicode_to_utf8(128578) << endl;

    cout << unicode_to_utf8(0x24) << '\t';
    cout << unicode_to_utf8(0xa2) << '\t';
    cout << unicode_to_utf8(0x20ac) << '\t';
    cout << unicode_to_utf8(0x1f642) << endl;

    cout << utf8_to_unicode("$") << '\t';
    cout << utf8_to_unicode("¢") << '\t';
    cout << utf8_to_unicode("€") << '\t';
    cout << utf8_to_unicode("") << endl;

    cout << utf8_to_unicode("\x24") << '\t';
    cout << utf8_to_unicode("\xc2\xa2") << '\t';
    cout << utf8_to_unicode("\xe2\x82\xac") << '\t';
    cout << utf8_to_unicode("\xf0\x9f\x99\x82") << endl;

    return 0;
}


int utf8_to_unicode(string utf8_code)
{
    unsigned utf8_size = utf8_code.length();
    int unicode = 0;

    for (unsigned p=0; p<utf8_size; ++p)
    {
        int bit_count = (p? 6: 8 - utf8_size - (utf8_size == 1? 0: 1)),
            shift = (p < utf8_size - 1? (6*(utf8_size - p - 1)): 0);

        for (int k=0; k<bit_count; ++k)
            unicode += ((utf8_code[p] & (1 << k)) << shift);
    }

    return unicode;
}


string unicode_to_utf8(int unicode)
{
    string s;

    if (unicode>=0 and unicode <= 0x7f)  // 7F(16) = 127(10)
    {
        s = static_cast<char>(unicode);

        return s;
    }
    else if (unicode <= 0x7ff)  // 7FF(16) = 2047(10)
    {
        unsigned char c1 = 192, c2 = 128;

        for (int k=0; k<11; ++k)
        {
            if (k < 6)  c2 |= (unicode % 64) & (1 << k);
            else c1 |= (unicode >> 6) & (1 << (k - 6));
        }

        s = c1;    s += c2;

        return s;
    }
    else if (unicode <= 0xffff)  // FFFF(16) = 65535(10)
    {
        unsigned char c1 = 224, c2 = 128, c3 = 128;

        for (int k=0; k<16; ++k)
        {
            if (k < 6)  c3 |= (unicode % 64) & (1 << k);
            else if (k < 12) c2 |= (unicode >> 6) & (1 << (k - 6));
            else c1 |= (unicode >> 12) & (1 << (k - 12));
        }

        s = c1;    s += c2;    s += c3;

        return s;
    }
    else if (unicode <= 0x1fffff)  // 1FFFFF(16) = 2097151(10)
    {
        unsigned char c1 = 240, c2 = 128, c3 = 128, c4 = 128;

        for (int k=0; k<21; ++k)
        {
            if (k < 6)  c4 |= (unicode % 64) & (1 << k);
            else if (k < 12) c3 |= (unicode >> 6) & (1 << (k - 6));
            else if (k < 18) c2 |= (unicode >> 12) & (1 << (k - 12));
            else c1 |= (unicode >> 18) & (1 << (k - 18));
        }

        s = c1;    s += c2;    s += c3;    s += c4;

        return s;
    }
    else if (unicode <= 0x3ffffff)  // 3FFFFFF(16) = 67108863(10)
    {
        ;  // actually, there are no 5-bytes unicodes
    }
    else if (unicode <= 0x7fffffff)  // 7FFFFFFF(16) = 2147483647(10)
    {
        ;  // actually, there are no 6-bytes unicodes
    }
    else  ;  // incorrect unicode (< 0 or > 2147483647)

    return "";
}

More:

How to add a jar in External Libraries in android studio

Create "libs" folder in app directory copy your jar file in libs folder right click on your jar file in Android Studio and Add As library... Then open build.gradle and add this:

dependencies {
    implementation files('libs/your jar file.jar')
}

Where to place JavaScript in an HTML file?

With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.

How can I pass some data from one controller to another peer controller

Use a service to achieve this:

MyApp.app.service("xxxSvc", function () {

var _xxx = {};

return {
    getXxx: function () {
        return _xxx;
    },
    setXxx: function (value) {
        _xxx = value;
    }
};

});

Next, inject this service into both controllers.

In Controller1, you would need to set the shared xxx value with a call to the service: xxxSvc.setXxx(xxx)

Finally, in Controller2, add a $watch on this service's getXxx() function like so:

  $scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
        if (newValue != null) {
            //update Controller2's xxx value
            $scope.xxx= newValue;
        }
    }, true);

How to correctly use "section" tag in HTML5?

In the W3 wiki page about structuring HTML5, it says:

<section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.

And then displays an image that I cleaned up:

enter image description here

It's also important to know how to use the <article> tag (from the same W3 link above):

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up.

In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article>
      <!-- first blog post -->
    </article>

    <article>
      <!-- second blog post  -->
    </article>

    <article>
      <!-- third blog post -->
    </article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction">
  </section>

  <section id="content">
  </section>

  <section id="summary">
  </section>
</article>

Printing a java map Map<String, Object> - How?

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

How do I clone a specific Git branch?

git clone -b <branch> <remote_repo>

Example:

git clone -b my-branch [email protected]:user/myproject.git

With Git 1.7.10 and later, add --single-branch to prevent fetching of all branches. Example, with OpenCV 2.4 branch:

git clone -b opencv-2.4 --single-branch https://github.com/Itseez/opencv.git

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

SQL Query to find the last day of the month

Just a different version of adding a month and subtracting a day for creating reports:

ex: StartofMonth is '2019-10-01'

dateadd(day,-1,dateadd(month,1,StartofMonth))

EndOfMonth will become '2019-10-31'

Android WebView Cookie Problem

Solution:Webview CookieSyncManager

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.example.com");

Swift Bridging Header import issue

I have the same issue for different reason , here is my case I build project that needs slide menu to be included , I am using SWRevealViewController lib to approach that

when I import the library files I add sub-folder(SWRevealViewController) under Supporting Files for .h && .m files , it fire two errors , cant import bridge and SWRevealViewController.h is not found .

How I fix it

when I move files to Supporting Files directly (delete sub-folder) , SWRevealViewController.m automatically added to Build Phases --> Compile Sources and issue is gone

enter image description here

Convert form data to JavaScript object with jQuery

One-liner (no dependencies other than jQuery), uses fixed object binding for function passsed to map method.

$('form').serializeArray().map(function(x){this[x.name] = x.value; return this;}.bind({}))[0]

What it does?

"id=2&value=1&comment=ok" => Object { id: "2", value: "1", comment: "ok" }

suitable for progressive web apps (one can easily support both regular form submit action as well as ajax requests)

What are the rules about using an underscore in a C++ identifier?

Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.

Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());
    }
}
c.close();

Pass variable to function in jquery AJAX success callback

Try something like this (use this.url to get the url):

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

Taken from here

How can I limit the visible options in an HTML <select> dropdown?

Raj_89 solution is the closest to being valid option altough as mentioned by Kevin Swarts in comment it is going to break IE, which for large number of corporate client is an issue (and telling your client that you won't code for IE "because reasons" is unlikely to make your boss happy ;) ).

So I played around with it and here is the problem: the 'onmousedown' event is throwing a fit in IE, so what we want to do, is to prevent default when user clicks the dropdown for the first time. It is important this is only time we do this: if we prevent defult on the next click, when user makes his pick, the onchange event won't fire.

This way we get nice dropdown, no flicker, no breaking down IE - just works... well at least in IE10 and up, and latest relases of all the other major browsers.

<p>Which is the most annoing browser of them all:</p>
<select id="sel" size = "1">
    <option></option>
    <option>IE 9</option>
    <option>IE 10</option>
    <option>Edge</option>
    <option>Firefox</option>
    <option>Chrome</option>
    <option>Opera</option>
</select>

Here is the fiddle: https://jsfiddle.net/88cxzhom/27/

Few more things to notice: 1) The absolute positioning and setting z-index is helpful to avoid moving other elements when the options are displayed. 2) Use 'currentTarget' property - this will be the select element across all browsers. While 'target' will be select in IE, the rest will actually allow you to work with option.

Hope this helps someone.

Authentication failed to bitbucket

I tried everything else and found helpless but this indeed worked for me "To update your credentials, go to Control Panel -> Credential Manager -> Generic Credentials. Find the credentials related to your git account and edit them to use the updated passwords".

Above Solution found in this link: https://cmatskas.com/how-to-update-your-git-credentials-on-windows/

Is there a short cut for going back to the beginning of a file by vi editor?

using :<line number> you can navigate to any line, thus :1 takes you to the first line.

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

How to run a command as a specific user in an init script?

For systemd style init scripts it's really easy. You just add a User= in the [Service] section.

Here is an init script I use for qbittorrent-nox on CentOS 7:

[Unit]
Description=qbittorrent torrent server

[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort

[Install]
WantedBy=multi-user.target

list all files in the folder and also sub folders

You can return a List instead of an array and things gets much simpler.

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Split string in C every white space

malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?

How to split page into 4 equal parts?

Demo at http://jsfiddle.net/CRSVU/

_x000D_
_x000D_
html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
}

div {
  width: 50%;
  height: 50%;
  float: left;
}

#div1 {
  background: #DDD;
}

#div2 {
  background: #AAA;
}

#div3 {
  background: #777;
}

#div4 {
  background: #444;
}
_x000D_
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
_x000D_
_x000D_
_x000D_

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Jquery in React is not defined

Try add jQuery to your project, like

npm i jquery --save

or if you use bower

bower i jquery --save

then

import $ from 'jquery'; 

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In your entity definition, you're not specifying the @JoinColumn for the Account joined to a Transaction. You'll want something like this:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

EDIT: Well, I guess that would be useful if you were using the @Table annotation on your class. Heh. :)

How do I put hint in a asp:textbox

Just write like this:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>

Counting number of occurrences in column?

Put the following in B3 (credit to @Alexander-Ivanov for the countif condition):

={UNIQUE(A3:A),ARRAYFORMULA(COUNTIF(UNIQUE(A3:A),"=" & UNIQUE(A3:A)))}

Benefits: It only requires editing 1 cell, it includes the name filtered by uniqueness, and it is concise.

Downside: it runs the unique function 3x

To use the unique function only once, split it into 2 cells:

B3: =UNIQUE(A3:A)

C3: =ARRAYFORMULA(COUNTIF(B3:B,"=" & B3:B))

php timeout - set_time_limit(0); - don't work

Check the php.ini

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

ini_set('max_execution_time', 0); //0=NOLIMIT

Difference between Statement and PreparedStatement

Some of the benefits of PreparedStatement over Statement are:

  1. PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters.
  2. PreparedStatement allows us to execute dynamic queries with parameter inputs.
  3. PreparedStatement provides different types of setter methods to set the input parameters for the query.
  4. PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use it’s batch processing methods for executing multiple queries.
  5. PreparedStatement helps us in writing object Oriented code with setter methods whereas with Statement we have to use String Concatenation to create the query. If there are multiple parameters to set, writing Query using String concatenation looks very ugly and error prone.

Read more about SQL injection issue at http://www.journaldev.com/2489/jdbc-statement-vs-preparedstatement-sql-injection-example

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

I solved this issue finally, it was because of some systems like skype and system processes take that port 80, you can make check using netstat -ao for port 80

Kindly find the following steps

  1. After installing your Apache HTTP go to the bin folder using cmd

  2. Install it as a service using httpd.exe -k install even when you see the error never mind

  3. Now make sure the service is installed (even if not started) according to your os

  4. Restart the system, then you will find the Apache service will be the first one to take the 80 port,

Congratulations the issue is solved.

Is there an "if -then - else " statement in XPath?

Personally, I would use XSLT to transform the XML and remove the trailing colons. For example, suppose I have this input:

<?xml version="1.0" encoding="UTF-8"?>
<Document>
    <Paragraph>This paragraph ends in a period.</Paragraph>
    <Paragraph>This one ends in a colon:</Paragraph>
    <Paragraph>This one has a : in the middle.</Paragraph>
</Document>

If I wanted to strip out trailing colons in my paragraphs, I would use this XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    version="2.0">
    <!-- identity -->
    <xsl:template match="/|@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- strip out colons at the end of paragraphs -->
    <xsl:template match="Paragraph">
        <xsl:choose>
            <!-- if it ends with a : -->
            <xsl:when test="fn:ends-with(.,':')">
                <xsl:copy>
                    <!-- copy everything but the last character -->
                    <xsl:value-of select="substring(., 1, string-length(.)-1)"></xsl:value-of>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet> 

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

Is there a free GUI management tool for Oracle Database Express?

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

How to do a newline in output

I would like to share my experience with \n
I came to notice that "\n" works as-

puts "\n\n" // to provide 2 new lines

but not

p "\n\n"

also puts '\n\n'
Doesn't works.

Hope will work for you!!

Convert list to array in Java

This (Ondrej's answer):

Foo[] array = list.toArray(new Foo[0]);

Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.

What are major differences between C# and Java?

C# has automatic properties which are incredibly convenient and they also help to keep your code cleaner, at least when you don't have custom logic in your getters and setters.

How to bind multiple values to a single WPF TextBlock?

Use a ValueConverter

[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("{0}:{1}", (string) value, (string) parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        return DependencyProperty.UnsetValue;
    }
}

and in the markup

<src:MyConverter x:Key="MyConverter"/>

. . .

<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />

How to center Font Awesome icons horizontally?

Give a class to your cell containing the icon

<td class="icon"><i class="icon-ok"></i></td>

and then

.icon{
    text-align: center;
}

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Possible to iterate backwards through a foreach?

As 280Z28 says, for an IList<T> you can just use the index. You could hide this in an extension method:

public static IEnumerable<T> FastReverse<T>(this IList<T> items)
{
    for (int i = items.Count-1; i >= 0; i--)
    {
        yield return items[i];
    }
}

This will be faster than Enumerable.Reverse() which buffers all the data first. (I don't believe Reverse has any optimisations applied in the way that Count() does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)

For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:

public static IEnumerable<T> GetStringsOfIncreasingSize()
{
    string ret = "";
    while (true)
    {
        yield return ret;
        ret = ret + "x";
    }
}

What would you expect to happen if you tried to iterate over that in reverse?

How can I change the date format in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());

This should do the trick

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

One line if statement not working

Both the shell and C one-line constructs work (ruby 1.9.3p429):

# Shell format
irb(main):022:0> true && "Yes" || "No"
=> "Yes"
irb(main):023:0> false && "Yes" || "No"
=> "No"

# C format
irb(main):024:0> true ? "Yes" : "No"
=> "Yes"
irb(main):025:0> false ? "Yes" : "No"
=> "No"

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Please use below code

package com.myjava.string;

import java.util.StringTokenizer;

public class MyStrRemoveMultSpaces {

    public static void main(String a[]){

        String str = "String    With Multiple      Spaces";

        StringTokenizer st = new StringTokenizer(str, " ");

        StringBuffer sb = new StringBuffer();

        while(st.hasMoreElements()){
            sb.append(st.nextElement()).append(" ");
        }

        System.out.println(sb.toString().trim());
    }
}

How to convert hex string to Java string?

You can go from String (hex) to byte array to String as UTF-8(?). Make sure your hex string does not have leading spaces and stuff.

public static byte[] hexStringToByteArray(String hex) {
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                + Character.digit(hex.charAt(i + 1), 16));
    }
    return data;
}

Usage:

String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);

Eclipse error: indirectly referenced from required .class files?

When i use a new eclipse version and try to use the previous workspace which i used with old eclipse version, this error occured.

Here is how i solve the problem:

Right click my project on Package Explorer -> Properties -> Java Build Path -> Libraries -> I see an error(Cross Sign) on JRE System Library. Because the path cannot be found. -> Double click the JRE System Library -> Select the option "Workspace Default JRE" -> Finish -> OK. -> BUM IT IS WORKING

FYI.

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

Trying to handle "back" navigation button action in iOS

Swift

override func didMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

How exactly does <script defer="defer"> work?

Have a look at this excellent article Deep dive into the murky waters of script loading by the Google developer Jake Archibald written in 2013.

Quoting the relevant section from that article:

Defer

<script src="//other-domain.com/1.js" defer></script>
<script src="2.js" defer></script>

Spec says: Download together, execute in order just before DOMContentLoaded. Ignore “defer” on scripts without “src”.

IE < 10 says: I might execute 2.js halfway through the execution of 1.js. Isn’t that fun??

The browsers in red say: I have no idea what this “defer” thing is, I’m going to load the scripts as if it weren’t there.

Other browsers say: Ok, but I might not ignore “defer” on scripts without “src”.

(I'll add that early versions of Firefox trigger DOMContentLoaded before the defer scripts finish running, according to this comment.)

Modern browsers seem to support async properly, but you need to be OK with scripts running out of order and possibly before DOMContentLoaded.

SQLite add Primary Key

As long as you are using CREATE TABLE, if you are creating the primary key on a single field, you can use:

CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER PRIMARY KEY,
field3 BLOB,
);

With CREATE TABLE, you can also always use the following approach to create a primary key on one or multiple fields:

CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER,
field3 BLOB,
PRIMARY KEY (field2, field1)
);

Reference: http://www.sqlite.org/lang_createtable.html

This answer does not address table alteration.

link button property to open in new tab?

try by Adding following onClientClick event.

OnClientClick="aspnetForm.target ='_blank';"

so on click it will call Javascript function an will open respective link in News tab.

<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'  />

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

C#: easiest way to populate a ListBox from a List

Try :

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

listBox1.DataSource = MyList;

Have a look at ListControl.DataSource Property

How can I escape a double quote inside double quotes?

Check out printf...

#!/bin/bash
mystr="say \"hi\""

Without using printf

echo -e $mystr

Output: say "hi"

Using printf

echo -e $(printf '%q' $mystr)

Output: say \"hi\"

How to access the value of a promise?

In the Node REPL, to get a DB connection that was the value of a promise, I took the following approach:

let connection
try {
  (async () => {
    connection = await returnsAPromiseResolvingToConnection()
  })()
} catch(err) {
  console.log(err)
}

The line with await would normally return a promise. This code can be pasted into the Node REPL or if saved in index.js it can be run in Bash with

node -i -e "$(< index.js)"

which leaves you in the Node REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connection for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.

How to round each item in a list of floats to 2 decimal places?

mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList =  [round(x,2) for x in mylist] 
# [0.3, 0.5, 0.2]

Using CSS in Laravel views?

Like Ahmad Sharif mentioned, you can link stylesheet over http

<link href="{{ asset('/css/style.css') }}" rel="stylesheet"> 

but if you are using https then the request will be blocked and a mixed content error will come, to use it over https use secure_asset like

<link href="{{ secure_asset('/css/style.css') }}" rel="stylesheet">

https://laravel.com/docs/5.1/helpers#method-secure-asset

Backup/Restore a dockerized PostgreSQL database

cat db.dump | docker exec ... way didn't work for my dump (~2Gb). It took few hours and ended up with out-of-memory error.

Instead, I cp'ed dump into container and pg_restore'ed it from within.

Assuming that container id is CONTAINER_ID and db name is DB_NAME:

# copy dump into container
docker cp local/path/to/db.dump CONTAINER_ID:/db.dump

# shell into container
docker exec -it CONTAINER_ID bash

# restore it from within
pg_restore -U postgres -d DB_NAME --no-owner -1 /db.dump

Error: Uncaught SyntaxError: Unexpected token <

This is a browser issue rather than a javascript or JQuery issue; it's attempting to interpret the angle bracket as an HTML tag.

Try doing this when setting up your javascripts:

<script>
//<![CDATA[

    // insert teh codez

//]]>
</script>

Alternatively, move your javascript to a separate file.

Edit: Ahh.. with that link I've tracked it down. What I said was the issue wasn't the issue at all. this is the issue, stripped from the website:

<script type="text/javascript"
    $(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

Can you spot the error? It's in the first line: the <script tag isn't closed. It should be <script type="text/javascript">

My previous suggestion still stands, however: you should enclose intra-tagged scripts in a CDATA block, or move them to a separately linked file.

That wasn't the issue here, but it would have shown the real issue faster.

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

Angular - Set headers for every request

There were some changes for angular 2.0.1 and higher:

    import {RequestOptions, RequestMethod, Headers} from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule }     from '@angular/http';
    import { AppRoutingModule } from './app.routing.module';   
    import { AppComponent }  from './app.component';

    //you can move this class to a better place
    class GlobalHttpOptions extends RequestOptions {
        constructor() { 
          super({ 
            method: RequestMethod.Get,
            headers: new Headers({
              'MyHeader': 'MyHeaderValue',
            })
          });
        }
      }

    @NgModule({

      imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
      declarations: [ AppComponent],
      bootstrap:    [ AppComponent ],
      providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
    })

    export class AppModule { }

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

How to Troubleshoot Intermittent SQL Timeout Errors

I am experiencing the same issue.. and I build some logging into several functions that I could identify that were frequently running long. when I say frequently I mean about 2% of the time. So part of the log inserted the start time and the end time of the procedure or query. I then produced a simple report sorting several days of logs by the total execution time descending. here is what I found.

the long running instances always started between HH:00 and HH:02 or HH:30 an HH:32 and none of the short running queries ran between those times. Interesting....

Now It seems that there is actually more order to the chaos that I was experiencing. I was using a recovery target of 0 this implemented "indirect checkpoints" in my databases so that my recovery time could be achieved at nearly 1 minute. causing these checkpoints to be created every 30 mins.

WOW, what a coincidence!

In Microsoft's online documentation about changing the recovery time of a database comes with this little warning...

"An online transactional workload on a database that is configured for indirect checkpoints could experience performance degradation."

Wow go figure...

so I modified my recovery time and bango no more issues.

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

Extract specific columns from delimited file using Awk

Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.

csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv

Replacing 2 with the column number will effectively extract the column data you are looking for.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Best practice to run Linux service as a different user

on a CENTOS (Red Hat) virtual machine for svn server: edited /etc/init.d/svnserver to change the pid to something that svn can write:

pidfile=${PIDFILE-/home/svn/run/svnserve.pid}

and added option --user=svn:

daemon --pidfile=${pidfile} --user=svn $exec $args

The original pidfile was /var/run/svnserve.pid. The daemon did not start becaseu only root could write there.

 These all work:
/etc/init.d/svnserve start
/etc/init.d/svnserve stop
/etc/init.d/svnserve restart

Node/Express file upload

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

npm install --save multer


in app.js

    var multer  =   require('multer');
    var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './public/uploads');
      },
      filename: function (req, file, callback) {
        console.log(file);
        callback(null, Date.now()+'-'+file.originalname)
      }
    });

    var upload = multer({storage: storage}).single('photo');

    router.route("/storedata").post(function(req, res, next){

        upload(req, res, function(err) {
          if(err) {
            console.log('Error Occured');
            return;
          }
          var userDetail = new mongoOp.User({
            'name':req.body.name,
            'email':req.body.email,
            'mobile':req.body.mobile,
            'address':req.body.address
          });

          console.log(req.file);

          res.end('Your File Uploaded');
          console.log('Photo Uploaded');

          userDetail.save(function(err,result){
          if (err) {
            return console.log(err)
          }
          console.log('saved to database') 
        })
      })

      res.redirect('/')

    });

How can I install packages using pip according to the requirements.txt file from a local directory?

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

How to call Base Class's __init__ method from the child class?

As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super() since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__ instead. Here is the code after incorporating these changes :

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):

    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__ with super()

sed edit file in place

The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

Example:

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

and

sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

on macOS.

Create an ISO date object in javascript

Try using the ISO string

var isodate = new Date().toISOString()

See also: method definition at MDN.

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

It appears to me that the simplest way to do this is

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

In Java, remove empty elements from a list of Strings

There are a few approaches that you could use:

  1. Iterate over the list, calling Iterator.remove() for the list elements you want to remove. This is the simplest.

  2. Repeatedly call List.remove(Object). This is simple too, but performs worst of all ... because you repeatedly scan the entire list. (However, this might be an option for a mutable list whose iterator didn't support remove ... for some reason.)

  3. Create a new list, iterate over the old list, adding elements that you want to retain to a new list.

  4. If you can't return the new list, as 3. above and then clear the old list and use addAll to add the elements of the new list back to it.

Which of these is fastest depends on the class of the original list, its size, and the number of elements that need to be removed. Here are some of the factors:

  • For an ArrayList, each individual remove operation is O(N), where N is the list size. It is expensive to remove multiple elements from a large ArrayList using the Iterator.remove() method (or the ArrayList.remove(element) method).

    By contrast, the Iterator.remove method for a LinkedList is O(1).

  • For an ArrayList, creating and copying a list is O(N) and relatively cheap, especially if you can ensure that the destination list's capacity is large enough (but not too large).

    By contrast, creating and copying to a LinkedList is also O(N), but considerably more expensive.

All of this adds up to a fairly complicated decision tree. If the lists are small (say 10 or less elements) you can probably get away with any of the approaches above. If the lists could be large, you need to weigh up all of the issues in the list of the expected list size and expected number of removals. (Otherwise you might end up with quadratic performance.)

Shared folder between MacOSX and Windows on Virtual Box

Yesterday, I am able to share the folders from my host OS Macbook (high Sierra) to Guest OS Windows 10

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Download the VBoxGuestAdditions_4.0.12.iso from http://download.virtualbox.org/virtualbox/4.0.12/
  4. Go to Devices > Optical drives > choose disk image.. choose the one downloaded in step 3
  5. Inside host guest OS (Windows 10, in my case) I could see: This PC > CD Drive (D:) Virtual Guest Additions

For now, right click on it, select Properties, the Compatibility tab, and select Windows 8 compatibility there. Much easier than using the compatibility troubleshooting I did initially.

enter image description here

  1. reboot the guest OS (Windows 10)
  2. Inside host guest OS, you could see the shared folder This PC> shared folder

It worked for me so I thought of sharing with everyone too.

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

Difference between innerText, innerHTML and value?

InnerText will only return the text value of the page with each element on a newline in plain text, while innerHTML will return the HTML content of everything inside the body tag, and childNodes will return a list of nodes, as the name suggests.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

Generating Random Passwords

public string CreatePassword(int length)
{
        const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder res = new StringBuilder();
        Random rnd = new Random();
        while (0 < length--)
        {
            res.Append(valid[rnd.Next(valid.Length)]);
        }
        return res.ToString();
}

This has a good benefit of being able to choose from a list of available characters for the generated password (e.g. digits only, only uppercase or only lowercase etc.)

Connecting PostgreSQL 9.2.1 with Hibernate

This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>



        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>



       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>

JavaScript for handling Tab Key press

Only one suggestion instead of 9 you can use KeyCodes.TAB.

Algorithm for Determining Tic Tac Toe Game Over

Here is a solution I came up with, this stores the symbols as chars and uses the char's int value to figure out if X or O has won (look at the Referee's code)

public class TicTacToe {
    public static final char BLANK = '\u0000';
    private final char[][] board;
    private int moveCount;
    private Referee referee;

    public TicTacToe(int gridSize) {
        if (gridSize < 3)
            throw new IllegalArgumentException("TicTacToe board size has to be minimum 3x3 grid");
        board = new char[gridSize][gridSize];
        referee = new Referee(gridSize);
    }

    public char[][] displayBoard() {
        return board.clone();
    }

    public String move(int x, int y) {
        if (board[x][y] != BLANK)
            return "(" + x + "," + y + ") is already occupied";
        board[x][y] = whoseTurn();
        return referee.isGameOver(x, y, board[x][y], ++moveCount);
    }

    private char whoseTurn() {
        return moveCount % 2 == 0 ? 'X' : 'O';
    }

    private class Referee {
        private static final int NO_OF_DIAGONALS = 2;
        private static final int MINOR = 1;
        private static final int PRINCIPAL = 0;
        private final int gridSize;
        private final int[] rowTotal;
        private final int[] colTotal;
        private final int[] diagonalTotal;

        private Referee(int size) {
            gridSize = size;
            rowTotal = new int[size];
            colTotal = new int[size];
            diagonalTotal = new int[NO_OF_DIAGONALS];
        }

        private String isGameOver(int x, int y, char symbol, int moveCount) {
            if (isWinningMove(x, y, symbol))
                return symbol + " won the game!";
            if (isBoardCompletelyFilled(moveCount))
                return "Its a Draw!";
            return "continue";
        }

        private boolean isBoardCompletelyFilled(int moveCount) {
            return moveCount == gridSize * gridSize;
        }

        private boolean isWinningMove(int x, int y, char symbol) {
            if (isPrincipalDiagonal(x, y) && allSymbolsMatch(symbol, diagonalTotal, PRINCIPAL))
                return true;
            if (isMinorDiagonal(x, y) && allSymbolsMatch(symbol, diagonalTotal, MINOR))
                return true;
            return allSymbolsMatch(symbol, rowTotal, x) || allSymbolsMatch(symbol, colTotal, y);
        }

        private boolean allSymbolsMatch(char symbol, int[] total, int index) {
            total[index] += symbol;
            return total[index] / gridSize == symbol;
        }

        private boolean isPrincipalDiagonal(int x, int y) {
            return x == y;
        }

        private boolean isMinorDiagonal(int x, int y) {
            return x + y == gridSize - 1;
        }
    }
}

Also here are my unit tests to validate it actually works

import static com.agilefaqs.tdd.demo.TicTacToe.BLANK;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class TicTacToeTest {
    private TicTacToe game = new TicTacToe(3);

    @Test
    public void allCellsAreEmptyInANewGame() {
        assertBoardIs(new char[][] { { BLANK, BLANK, BLANK },
                { BLANK, BLANK, BLANK },
                { BLANK, BLANK, BLANK } });
    }

    @Test(expected = IllegalArgumentException.class)
    public void boardHasToBeMinimum3x3Grid() {
        new TicTacToe(2);
    }

    @Test
    public void firstPlayersMoveMarks_X_OnTheBoard() {
        assertEquals("continue", game.move(1, 1));
        assertBoardIs(new char[][] { { BLANK, BLANK, BLANK },
                { BLANK, 'X', BLANK },
                { BLANK, BLANK, BLANK } });
    }

    @Test
    public void secondPlayersMoveMarks_O_OnTheBoard() {
        game.move(1, 1);
        assertEquals("continue", game.move(2, 2));
        assertBoardIs(new char[][] { { BLANK, BLANK, BLANK },
                { BLANK, 'X', BLANK },
                { BLANK, BLANK, 'O' } });
    }

    @Test
    public void playerCanOnlyMoveToAnEmptyCell() {
        game.move(1, 1);
        assertEquals("(1,1) is already occupied", game.move(1, 1));
    }

    @Test
    public void firstPlayerWithAllSymbolsInOneRowWins() {
        game.move(0, 0);
        game.move(1, 0);
        game.move(0, 1);
        game.move(2, 1);
        assertEquals("X won the game!", game.move(0, 2));
    }

    @Test
    public void firstPlayerWithAllSymbolsInOneColumnWins() {
        game.move(1, 1);
        game.move(0, 0);
        game.move(2, 1);
        game.move(1, 0);
        game.move(2, 2);
        assertEquals("O won the game!", game.move(2, 0));
    }

    @Test
    public void firstPlayerWithAllSymbolsInPrincipalDiagonalWins() {
        game.move(0, 0);
        game.move(1, 0);
        game.move(1, 1);
        game.move(2, 1);
        assertEquals("X won the game!", game.move(2, 2));
    }

    @Test
    public void firstPlayerWithAllSymbolsInMinorDiagonalWins() {
        game.move(0, 2);
        game.move(1, 0);
        game.move(1, 1);
        game.move(2, 1);
        assertEquals("X won the game!", game.move(2, 0));
    }

    @Test
    public void whenAllCellsAreFilledTheGameIsADraw() {
        game.move(0, 2);
        game.move(1, 1);
        game.move(1, 0);
        game.move(2, 1);
        game.move(2, 2);
        game.move(0, 0);
        game.move(0, 1);
        game.move(1, 2);
        assertEquals("Its a Draw!", game.move(2, 0));
    }

    private void assertBoardIs(char[][] expectedBoard) {
        assertArrayEquals(expectedBoard, game.displayBoard());
    }
}

Full solution: https://github.com/nashjain/tictactoe/tree/master/java

How to call an element in a numpy array?

If you are using numpy and your array is an np.array of np.array elements like:

A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])

and you want to access the inner elements (like 10,11,12 13,14.......) then use:

A[0][0] instead of A[0,0]

For example:

>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR

(P.S.: Might be useful when using numpy.array_split())

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Interface type check with Typescript

same as above where user-defined guards were used but this time with an arrow function predicate

interface A {
  member:string;
}

const check = (p: any): p is A => p.hasOwnProperty('member');

var foo: any = { member: "foobar" };
if (check(foo))
    alert(foo.member);

Changing default shell in Linux

You should have a 'skeleton' somewhere in /etc, probably /etc/skeleton, or check the default settings, probably /etc/default or something. Those are scripts that define standard environment variables getting set during a login.

If it is just for your own account: check the (hidden) file ~/.profile and ~/.login. Or generate them, if they don't exist. These are also evaluated by the login process.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

The accepted answer is the correct command, I just want to add one additional thing, when extracting the key if you leave the PEM password("Enter PEM pass phrase:") blank then the complete key will not be extracted but only the localKeyID will be extracted. To get the complete key you must specify a PEM password whem running the following command.

Please note that when it comes to Import password, you can specify the actual password for "Enter Import Password:" or can leave this password blank:

openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem

python NameError: global name '__file__' is not defined

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

When using your script from the console or as an application, the functions hereunder will deliver you the "execution path", not the "actual file path":

print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))

Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html

Your old line (initial question):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Substitute your line of code with the following snippet.

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it's data/configuration files.

Tested with python:

  • 3.3.4
  • 2.7.13

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

What are the differences between if, else, and else if?

you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions

  • go with an umbrella
  • go without an umbrella

and both the two actions are bound to one condition, i.e is it raining?

now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.

ASP.NET file download from server

Try this set of code to download a CSV file from the server.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

How to convert a const char * to std::string

std::string the_string(c_string);
if(the_string.size() > max_length)
    the_string.resize(max_length);

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

The simplest way to resize an UIImage?

Yet another way of resizing an UIImage:

// Resize to height = 100 points.
let originalImage = UIImage(named: "MyOriginalImage")!
let resizingFactor = 100 / originalImage.size.height
let newImage = UIImage(cgImage: originalImage.cgImage!, scale: originalImage.scale / resizingFactor, orientation: .up)

Change the maximum upload file size

You need to set the value of upload_max_filesize and post_max_size in your php.ini :

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

After modifying php.ini file(s), you need to restart your HTTP server to use new configuration.

If you can't change your php.ini, you're out of luck. You cannot change these values at run-time; uploads of file larger than the value specified in php.ini will have failed by the time execution reaches your call to ini_set.

See the Description of core php.ini directives.

net::ERR_INSECURE_RESPONSE in Chrome

For me the answer to this was available here on StackOverflow:

ERR_INSECURE_RESPONSE caused by change to Fiddler's root certificate generation using CertEnroll for Windows 7 and later

Unfortunately, this change can cause problems for users who have previously trusted the Fiddler root certificate; the browser may show an error message like NET::ERR_CERT_AUTHORITY_INVALID or The certificate was not issued by a trusted certificate authority.

(Quote from the original source)

I had this ERR_CERT_AUTHORITY_INVALID error on the browser and ERR_INSECURE_RESPONSE shown in Developer Tools of Chrome.

How to change bower's default components folder?

Create a Bower configuration file .bowerrc in the project root (as opposed to your home directory) with the content:

{
  "directory" : "public/components"
}

Run bower install again.

Disable form autofill in Chrome without disabling autocomplete

Not a beautiful solution, but worked on Chrome 56:

<INPUT TYPE="text" NAME="name" ID="name" VALUE=" ">
<INPUT TYPE="password" NAME="pass" ID="pass">

Note a space on the value. And then:

$(document).ready(function(){
   setTimeout("$('#name').val('')",1000);
});

How can I display the current branch and folder path in terminal?

Simple way

Open ~/.bash_profile in your favorite editor and add the following content to the bottom.

Git branch in prompt.

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Add Git Branch To Terminal Prompt (Mac)

Trigger to fire only if a condition is met in SQL Server

For triggers in general, you need to use a cursor to handle inserts or updates of multiple rows. For example:

DECLARE @Attribute;
DECLARE @ParameterValue;
DECLARE mycursor CURSOR FOR SELECT Attribute, ParameterValue FROM inserted;
OPEN mycursor;
FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
WHILE @@FETCH_STATUS = 0
BEGIN

If @Attribute LIKE 'NoHist_%'
      Begin
          Return
      End

etc.

FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
END

Triggers, at least in SQL Server, are a big pain and I avoid using them at all.

What is the &#xA; character?

That would be an HTML Encoded Line Feed character (using the hexadecimal value).

The decimal value would be &#10;

Fastest way to get the first object from a queryset in django?

r = list(qs[:1])
if r:
  return r[0]
return None

DropDownList in MVC 4 with Razor

Believe me I have tried a lot of options to do that and I have answer here

but I always look for the best practice and the best way I know so far for both front-end and back-end developers is for loop (yes I'm not kidding)

Because when the front-end gives you the UI Pages with dummy data he also added classes and some inline styles on specific select option so its hard to deal with using HtmlHelper

Take look at this :

<select class="input-lg" style="">
    <option value="0" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
    <option value="4">44</option>
</select>

this from the front-end developer so best solution is to use the for loop

fristly create or get your list of data from (...) in the Controller Action and put it in ViewModel, ViewBag or whatever

//This returns object that contain Items and TotalCount
ViewBag.MembershipList = await _membershipAppService.GetAllMemberships();

Secondly in the view do this simple for loop to populate the dropdownlist

<select class="input-lg" name="PrerequisiteMembershipId" id="PrerequisiteMembershipId">
    <option value="" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    @foreach (var item in ViewBag.MembershipList.Items)
    {
        <option value="@item.Id" @(Model.PrerequisiteMembershipId == item.Id ? "selected" : "")>
            @item.Name
        </option>
    }
</select>

in this way you will not break UI Design, and its simple , easy and more readable

hope this help you even if you did not used razor

Start index for iterating Python list

stdlib will hook you up son!

deque.rotate():

#!/usr/local/bin/python2.7

from collections import deque

a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
a.rotate(3)
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])

ImportError: No module named 'bottle' - PyCharm

I am using Ubuntu 16.04. For me it was the incorrect interpretor, which was by default using the virtual interpretor from project.

So, make sure you select the correct one, as the pip install will install the package to system python interpretor.

enter image description here

What is the difference between "is None" and "== None"

It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.

For a specific example take a numpy array where the == comparison is implemented elementwise:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

Magento addFieldToFilter: Two fields, match as OR, not AND

To filter by multiple attributes use something like:

//for AND
    $collection = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter('my_field1', 'my_value1')
    ->addFieldToFilter('my_field2', 'my_value2');

    echo $collection->getSelect()->__toString();

//for OR - please note 'attribute' is the key name and must remain the same, only replace //the value (my_field1, my_field2) with your attribute name


    $collection = Mage::getModel('sales/order')->getCollection()
        ->addAttributeToSelect('*')
        ->addFieldToFilter(
            array(
                array('attribute'=>'my_field1','eq'=>'my_value1'),
                array('attribute'=>'my_field2', 'eq'=>'my_value2')
            )
        );

For more information check: http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection_Db.html#_getConditionSql

Get Hours and Minutes (HH:MM) from date

Just use the first 5 characters...?

 SELECT CONVERT(VARCHAR(5),getdate(),108) 

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

Check if an array item is set in JS

TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.

foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.

var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();

If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

How do you extract IP addresses from files using a regex in a linux shell?

For those who want a ready solution for getting IP addresses from apache log and listing occurences of how many times IP address has visited website, use this line:

grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' error.log | sort | uniq -c | sort -nr > occurences.txt

Nice method to ban hackers. Next you can:

  1. Delete lines with less than 20 visits
  2. Using regexp cut till single space so you will have only IP addresses
  3. Using regexp cut 1-3 last numbers of IP addresses so you will have only network addresses
  4. Add deny from and a space at the beginning of each line
  5. Put the result file as .htaccess

How does true/false work in PHP?

think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.

other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.

PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.

Read file content from S3 bucket with boto3

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

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

How do I do base64 encoding on iOS?

I Think This will be helpful

 + (NSString *)toBase64String:(NSString *)string {
    NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];

    NSString *ret = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    return ret;
    }

    + (NSString *)fromBase64String:(NSString *)string {
NSData *aData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *aDataDecoded = [[NSData alloc]initWithBase64EncodedString:string options:0];
NSString *decryptedStr = [[NSString alloc]initWithData:aDataDecoded encoding:NSUTF8StringEncoding];

return [decryptedStr autorelease];

}

Can you nest html forms?

You can also use formaction="" inside the button tag.

<button type="submit" formaction="/rmDog" method='post' id="rmDog">-</button>

This would be nested in the original form as a separate button.

Disallow Twitter Bootstrap modal window from closing

You can disable the background's click-to-close behavior and make this the default for all your modals by adding this JavaScript to your page (make sure it is executed after jQuery and Bootstrap JS are loaded):

$(function() {
    $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
});

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Making button go full-width?

The question was raised years ago, with the older version it was a little hard to get...but now this question has a very easy answer.

<div class="btn btn-outline-primary btn-block">Button text here</div>

Preloading @font-face fonts?

Your head should include the preload rel as follows:

<head>
    ...
    <link rel="preload" as="font" href="/somefolder/font-one.woff2">
    <link rel="preload" as="font" href="/somefolder/font-two.woff2">
</head>

This way woff2 will be preloaded by browsers that support preload, and all the fallback formats will load as they normally do.
And your css font face should look similar to to this

@font-face {
    font-family: FontOne;
    src: url(../somefolder/font-one.eot);
    src: url(../somefolder/font-one.eot?#iefix) format('embedded-opentype'),
    url(../somefolder/font-one.woff2) format('woff2'), //Will be preloaded
    url(../somefolder/font-one.woff) format('woff'),
    url(../somefolder/font-one.ttf)  format('truetype'),
    url(../somefolder/font-one.svg#svgFontName) format('svg'); 
}
@font-face {
    font-family: FontTwo;
    src: url(../somefolder/font-two.eot);
    src: url(../somefolder/font-two.eot?#iefix) format('embedded-opentype'),
    url(../somefolder/font-two.woff2) format('woff2'), //Will be preloaded
    url(../somefolder/font-two.woff) format('woff'),
    url(../somefolder/font-two.ttf)  format('truetype'),
    url(../somefolder/font-two.svg#svgFontName) format('svg');
}

How to check if a folder exists

There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.

How to know the git username and email saved during configuration?

To view git configuration type -

git config --list

To change username globally type -

git config --global user.name "your_name"

To change email globally type -

git config --global user.email "your_email"

Python naming conventions for modules

From PEP-8: Package and Module Names:

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.

Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

how to remove the bold from a headline?

The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:

h1 { font-weight:normal; }

More: http://www.w3.org/TR/css3-fonts/#font-weight-prop

How can I see the current value of my $PATH variable on OS X?

for MacOS, make sure you know where the GO install

export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin

How to remove all the null elements inside a generic list in one go?

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

How can I use the HTML5 canvas element in IE?

The page is using excanvas - a JS library that simulates the canvas element using IE's VML renderer.

Note that in Internet Explorer 9, the canvas tag is supported natively! See MSDN docs for details...

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

Example use of "continue" statement in Python?

I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

I get code like this:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Visual Studio 64 bit?

No! There is no 64-bit version of Visual Studio.

How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0

As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.

Detect if Android device has Internet connection

I have modified THelper's answer slightly, to use a known hack that Android already uses to check if the connected WiFi network has Internet access. This is a lot more efficient over grabbing the entire Google home page. See here and here for more info.

public static boolean hasInternetAccess(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) 
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(TAG, "No network available!");
    }
    return false;
}

What is the javascript filename naming convention?

The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.

As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).

So the answer, like so many, is "it depends" or "it's up to you."

The one rule you should follow is to be consistent in the convention you choose.

Detect page change on DataTable

Try using delegate instead of live as here:

$('#link-wrapper').delegate('a', 'click', function() {
  // do something ..
}

Dynamic WHERE clause in LINQ

You could use the Any() extension method. The following seems to work for me.

XStreamingElement root = new XStreamingElement("Results",
                from el in StreamProductItem(file)
                where fieldsToSearch.Any(s => el.Element(s) != null && el.Element(s).Value.Contains(searchTerm))
                select fieldsToReturn.Select(r => (r == "product") ? el : el.Element(r))
            );
            Console.WriteLine(root.ToString());

Where 'fieldsToSearch' and 'fieldsToReturn' are both List objects.

dispatch_after - GCD in Swift?

In Swift 5, use in the below:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

How to find index of all occurrences of element in array?

You can use Polyfill

if (!Array.prototype.filterIndex) {
Array.prototype.filterIndex = function (func, thisArg) {

    'use strict';
    if (!((typeof func === 'Function' || typeof func === 'function') && this))
        throw new TypeError();

    let len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;

    let kValue;
    if (thisArg === undefined) {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i]; // in case t is changed in callback
                if (func(t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }
    else {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i];
                if (func.call(thisArg, t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }

    res.length = c; // shrink down array to proper size
    return res;
};

}

Use it like this:

[2,23,1,2,3,4,52,2].filterIndex(element => element === 2)

result: [0, 3, 7]

How to get an object's property's value by property name?

Expanding upon @aquinas:

Get-something | select -ExpandProperty PropertyName

or

Get-something | select -expand PropertyName

or

Get-something | select -exp PropertyName

I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.

In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:

Get-CalendarProcessing [email protected] | Select -expand BookInPolicy

Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

JavaScript Regular Expression Email Validation

I have been using this one....

/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/

It allows that + before @ ([email protected])

How to move an element into another element?

If the div where you want to put your element has content inside, and you want the element to show after the main content:

  $("#destination").append($("#source"));

If the div where you want to put your element has content inside, and you want to show the element before the main content:

$("#destination").prepend($("#source"));

If the div where you want to put your element is empty, or you want to replace it entirely:

$("#element").html('<div id="source">...</div>');

If you want to duplicate an element before any of the above:

$("#destination").append($("#source").clone());
// etc.

What is InputStream & Output Stream? Why and when do we use them?

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

@echo off

:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause

echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause

Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory 
pause 

goto START

Browser detection

if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
} 
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    { 
        DoSomething(); 
    }
    ...
}
else { }

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines in the script solved the issue for me.

# !/usr/bin/python
# coding=utf-8

Hope it helps !

Button background as transparent

I achieved this with in XML with

android:background="@android:color/transparent"

My Routes are Returning a 404, How can I Fix Them?

You could try to move root/public/.htaccess to root/.htaccess and it should work

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How do I handle the window close event in Tkinter?

You should use destroy() to close a tkinter window.

   from Tkinter import *
   root = Tk()
   Button(root, text="Quit", command=root.destroy).pack()
   root.mainloop()

Explanation:

root.quit() The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy() While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop()`.

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something