Programs & Examples On #Tabs

A user interface pattern that allows for the display of multiple pages or elements with a navigation reference above, below, or to the side of the content. On clicking the navigation reference, one element is made visible while others are toggled off. Often, the navigation reference is color-coded in a manner to indicate that it is currently visible.

How do I change Eclipse to use spaces instead of tabs?

Be sure to check the java formater since it overwrites the "insert spaces for tabs" setting. Go to:

Java->Code Style"->Formatter->Edit->Identation

Note: you will need to create a custom format to be able to save your configuration.

How to make the tab character 4 spaces instead of 8 spaces in nano?

Command-line flag

From man nano:

-T cols (--tabsize=cols)
    Set the size (width) of a tab to cols columns.
    The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
    Convert typed tabs to spaces.

For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:

nano -ET4 foo.txt

Config file

From man nanorc:

set tabsize n
    Use a tab size of n columns. The value of n must be greater than 0.
    The default value is 8.
set/unset tabstospaces
    Convert typed tabs to spaces.

Edit your ~/.nanorc file (create it if it does not exist), and add those commands to it. For example:

set tabsize 4
set tabstospaces

Nano will use these settings by default whenever it is launched, but command-line flags will override them.

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

HTML: how to force links to open in a new tab, not new window

You can change the way Safari opens a new page in Safari > Preferences > Tabs > 'Open pages in tabs instead of windows' > 'Automatically'

jQuery UI Tabs - How to Get Currently Selected Tab Index

var $tabs = $('#tabs-menu').tabs();
// jquery ui 1.8
var selected = $tabs.tabs('option', 'selected');
// jquery ui 1.9+
var active = $tabs.tabs('option', 'active');

How can I convert spaces to tabs in Vim or Linux?

Changes all spaces to tab :%s/\s/\t/g

Switch to selected tab by name in Jquery-UI Tabs

Use this function:

function uiTabs(i){
    $("#tabs").tabs("option", "selected", i);
}

And use following code to switch between tabs:

<a onclick="uiTabs(0)">Tab 1</a>
<a onclick="uiTabs(1)">Tab 2</a>
<a onclick="uiTabs(2)">Tab 3</a>

Using Vim's tabs like buffers

I ran into the same problem. I wanted tabs to work like buffers and I never quite manage to get them to. The solution that I finally settled on was to make buffers behave like tabs!

Check out the plugin called Mini Buffer Explorer, once installed and configured, you'll be able to work with buffers virtaully the same way as tabs without losing any functionality.

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

How do I write a "tab" in Python?

This is the code:

f = open(filename, 'w')
f.write("hello\talex")

The \t inside the string is the escape sequence for the horizontal tabulation.

Printing with "\t" (tabs) does not result in aligned columns

The "problem" with the tabs is that they indent the text to fixed tab positions, typically multiples of 4 or 8 characters (depending on the console or editor displaying them). Your first filename is 7 chars, so the next tab stop after its end is at position 8. Your subsequent filenames however are 8 chars long, so the next tab stop is at position 12.

If you want to ensure that columns get nicely indented at the same position, you need to take into account the actual length of previous columns, and either modify the number of following tabs, or pad with the required number of spaces instead. The latter can be achieved using e.g. System.out.printf with an appropriate format specification (e.g. "%1$13s" specifies a minimum width of 13 characters for displaying the first argument as a string).

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

Show SOME invisible/whitespace characters in Eclipse

Navigate to Window > Preferences > General > Editors > Text Editors

Click on the CheckBox "Show whitespace characters".

enter image description here

Thats all.!!!

Echo tab characters in bash script

If you want to use echo "a\tb" in a script, you run the script as:

# sh -e myscript.sh

Alternatively, you can give to myscript.sh the execution permission, and then run the script.

# chmod +x myscript.sh
# ./myscript.sh

Sublime Text 3, convert spaces to tabs

In my case, this line solved the problem:

"translate_tabs_to_spaces": false

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.

How to launch a Google Chrome Tab with specific URL using C#

UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData!


Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:

Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe", 
              "http:\\www.YourUrl.com");

Find Active Tab using jQuery and Twitter Bootstrap

Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab
$('#rowTab a:first').tab('show');

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
 console.log ( $(e.target).attr('id') );
});

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

How to insert spaces/tabs in text using HTML/CSS

You can use this code &#8287; to add a space in the HTML content. For tab space, use it 5 times or more.

Check an example here: https://www.w3schools.com/charsets/tryit.asp?deci=8287&ent=ThickSpace

Change tab bar tint color on iOS 7

Try the below:

[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

To tint the non active buttons, put the below code in your VC's viewDidLoad:

UITabBarItem *tabBarItem = [yourTabBarController.tabBar.items objectAtIndex:0];

UIImage *unselectedImage = [UIImage imageNamed:@"icon-unselected"];
UIImage *selectedImage = [UIImage imageNamed:@"icon-selected"];

[tabBarItem setImage: [unselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage: selectedImage];

You need to do this for all the tabBarItems, and yes I know it is ugly and hope there will be cleaner way to do this.

Swift:

UITabBar.appearance().tintColor = UIColor.red

tabBarItem.image = UIImage(named: "unselected")?.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = UIImage(named: "selected")?.withRenderingMode(.alwaysOriginal)

How can I align text in columns using Console.WriteLine?

Do some padding, i.e.

          public static void prn(string fname, string fvalue)
            {
                string outstring = fname.PadRight(20)  +"\t\t  " + fvalue;
                Console.WriteLine(outstring);

            }

This worked well, at least for me.

C++ printing spaces or tabs given a user input integer

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";

Stacked Tabs in Bootstrap 3

The Bootstrap team seems to have removed it. See here: https://github.com/twbs/bootstrap/issues/8922 . @Skelly's answer involves custom css which I didn't want to do so I used the grid system and nav-pills. It worked fine and looked great. The code looks like so:

<div class="row">

  <!-- Navigation Buttons -->
  <div class="col-md-3">
    <ul class="nav nav-pills nav-stacked" id="myTabs">
      <li class="active"><a href="#home" data-toggle="pill">Home</a></li>
      <li><a href="#profile" data-toggle="pill">Profile</a></li>
      <li><a href="#messages" data-toggle="pill">Messages</a></li>
    </ul>
  </div>

  <!-- Content -->
  <div class="col-md-9">
    <div class="tab-content">
      <div class="tab-pane active" id="home">Home</div>
      <div class="tab-pane" id="profile">Profile</div>
      <div class="tab-pane" id="messages">Messages</div>
    </div>
  </div>

</div>

You can see this in action here: http://bootply.com/81948

[Update] @SeanK gives the option of not having to enable the nav-pills through Javascript and instead using data-toggle="pill". Check it out here: http://bootply.com/96067. Thanks Sean.

how to use "tab space" while writing in text file

Use "\t". That's the tab space character.

You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html

Replace whitespaces with tabs in linux

You can also use astyle. I found it quite useful and it has several options too:

Tab and Bracket Options:
   If  no  indentation  option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4.  If no brackets option is set, the
   brackets will not be changed.

   --indent=spaces, --indent=spaces=#, -s, -s#
          Indent using # spaces per indent. Between 1 to 20.  Not specifying # will result in a default of 4 spaces per indent.

   --indent=tab, --indent=tab=#, -t, -t#
          Indent using tab characters, assuming that each tab is # spaces long.  Between 1 and 20. Not specifying # will result in a default assumption  of
          4 spaces per tab.`

Open new Terminal Tab from command line (Mac OS X)

Here's how it's done by bash_it:

function tab() {
  osascript 2>/dev/null <<EOF
    tell application "System Events"
      tell process "Terminal" to keystroke "t" using command down
    end
    tell application "Terminal"
      activate
      do script with command "cd \"$PWD\"; $*" in window 1
    end tell
EOF
}

After adding this to your .bash_profile, you'd use the tab command to open the current working directory in a new tab.

See: https://github.com/revans/bash-it/blob/master/plugins/available/osx.plugin.bash#L3

Bootstrap 3: Keep selected tab on page refresh

Basing myself on answers provided by Xavi Martínez and koppor I came up with a solution that uses the url hash or localStorage depending on the availability of the latter:

function rememberTabSelection(tabPaneSelector, useHash) {
    var key = 'selectedTabFor' + tabPaneSelector;
    if(get(key)) 
        $(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');

    $(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
        set(key, this.getAttribute('href'));
    }); 

    function get(key) {
        return useHash ? location.hash: localStorage.getItem(key);
    }

    function set(key, value){
        if(useHash)
            location.hash = value;
        else
            localStorage.setItem(key, value);
    }
}

Usage:

$(document).ready(function () {
    rememberTabSelection('#rowTab', !localStorage);
    // Do Work...
});

It does not keep up with the back button as is the case for Xavi Martínez's solution.

Eclipse HotKey: how to switch between tabs?

Nobody will ever read my answer, but anyway... If you are on Mac OS X you will love multi touch gestures for history navigation in Eclipse: http://sourceforge.net/apps/mediawiki/eclipsemultitch/

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

This code selects the right tab depending on the #hash and adds the right #hash when a tab is clicked. (this uses jquery)

In Coffeescript :

$(document).ready ->
    if location.hash != ''
        $('a[href="'+location.hash+'"]').tab('show')

    $('a[data-toggle="tab"]').on 'shown', (e) ->
        location.hash = $(e.target).attr('href').substr(1)

or in JS :

$(document).ready(function() {
    if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
    return $('a[data-toggle="tab"]').on('shown', function(e) {
      return location.hash = $(e.target).attr('href').substr(1);
    });
});

Programmatically open new pages on Tabs

You can, in Firefox it works, add the attribute target="_newtab" to the anchor to force the opening of a new tab.

<a href="some url" target="_newtab">content of the anchor</a>

In javascript you can use

window.open('page.html','_newtab');

Said that, I partially agree with Sam. You shouldn't force user to open new pages or new tab without showing them a hint on what is going to happen before they click on the link.

Let me know if it works on other browser too (I don't have a chance to try it on other browser than Firefox at the moment).

Edit: added reference for ie7 Maybe this link can be useful
http://social.msdn.microsoft.com/forums/en-US/ieextensiondevelopment/thread/951b04e4-db0d-4789-ac51-82599dc60405/

Visual Studio Code - Convert spaces to tabs

File -> Preferences -> Settings or just press Ctrl + , and search for spaces, then just deactivate this option:

enter image description here

I had to reopen the file so the changes would take effect.

How to make a new line or tab in <string> XML (eclipse/android)?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text

More info:

https://developer.android.com/guide/topics/resources/string-resource.html

SELECT DISTINCT on one column

try this:

SELECT 
    t.*
    FROM TestData t
        INNER JOIN (SELECT
                        MIN(ID) as MinID
                        FROM TestData
                        WHERE SKU LIKE 'FOO-%'
                   ) dt ON t.ID=dt.MinID

EDIT
once the OP corrected his samle output (previously had only ONE result row, now has all shown), this is the correct query:

declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 ,  'FOO-23'      ,'Orange')
insert into @TestData values (2 ,  'BAR-23'      ,'Orange')
insert into @TestData values (3 ,  'FOO-24'      ,'Apple')
insert into @TestData values (4 ,  'FOO-25'      ,'Orange')

--basically the same as @Aaron Alton's answer:
SELECT
    dt.ID, dt.SKU, dt.Product
    FROM (SELECT
              ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
              FROM @TestData
              WHERE  SKU LIKE 'FOO-%'
         ) AS dt
    WHERE dt.RowID=1
    ORDER BY dt.ID

Split code over multiple lines in an R script

I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][time_[s]<=12000]

I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []. Splitting at ][ doesn´t work.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, 
    Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, 
    Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, 
    Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

Wait until a process ends

I had a case where Process.HasExited didn't change after closing the window belonging to the process. So Process.WaitForExit() also didn't work. I had to monitor Process.Responding that went to false after closing the window like that:

while (!_process.HasExited && _process.Responding) {
  Thread.Sleep(100);
}
...

Perhaps this helps someone.

List directory tree structure in python?

A solution without your indentation:

for path, dirs, files in os.walk(given_path):
  print path
  for f in files:
    print f

os.walk already does the top-down, depth-first walk you are looking for.

Ignoring the dirs list prevents the overlapping you mention.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

Splitting a Java String by the pipe symbol using split("|")

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

Which browser has the best support for HTML 5 currently?

i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5

Change the selected value of a drop-down list with jQuery

How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.

If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.

This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.

How do you create a static class in C++?

Unlike other managed programming language, "static class" has NO meaning in C++. You can make use of static member function.

How to properly validate input values with React.JS?

Use onChange={this.handleChange.bind(this, "name") method and value={this.state.fields["name"]} on input text field and below that create span element to show error, see the below example.

export default class Form extends Component {

  constructor(){
    super()
    this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }
  }

  handleValidation(){
       let fields = this.state.fields;
       let errors = {};
       let formIsValid = true;

       if(!fields["name"]){
          formIsValid = false;
          errors["name"] = "Name field cannot be empty";
       }

       if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
          if(!fields["name"].match(/^[a-zA-Z]+$/)){
             formIsValid = false;
             errors["name"] = "Only letters";
          }
       }

       if(!fields["email"]){
          formIsValid = false;
          errors["email"] = "Email field cannot be empty";
       }

       if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
          let lastAtPos = fields["email"].lastIndexOf('@');
          let lastDotPos = fields["email"].lastIndexOf('.');

          if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
             formIsValid = false;
             errors["email"] = "Email is not valid";
           }
      }

      if(!fields["message"]){
         formIsValid = false;
         errors["message"] = " Message field cannot be empty";
      }

      this.setState({errors: errors});
      return formIsValid;
  }

  handleChange(field, e){
      let fields = this.state.fields;
      fields[field] = e.target.value;
      this.setState({fields});
  }

  handleSubmit(e){
      e.preventDefault();
      if(this.handleValidation()){
          console.log('validation successful')
        }else{
          console.log('validation failed')
        }
  }

  render(){
    return (
      <form onSubmit={this.handleSubmit.bind(this)} method="POST">
          <div className="row">
            <div className="col-25">
                <label htmlFor="name">Name</label>
            </div>
            <div className="col-75">
                <input type="text" placeholder="Enter Name"  refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                <span style={{color: "red"}}>{this.state.errors["name"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
              <label htmlFor="exampleInputEmail1">Email address</label>
            </div>
            <div className="col-75">
                <input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                <span style={{color: "red"}}>{this.state.errors["email"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
                <label htmlFor="message">Message</label>
            </div>
            <div className="col-75">
                <textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
                <span style={{color: "red"}}>{this.state.errors["message"]}</span>
            </div>
          </div>
          <div className="row">
            <button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
          </div>
      </form>
    )
  }
}

How to insert element as a first child?

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added by

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

How to do a recursive find/replace of a string with awk or sed?

For replace all occurrences in a git repository you can use:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

See List files in local git repo? for other options to list all files in a repository. The -z options tells git to separate the file names with a zero byte, which assures that xargs (with the option -0) can separate filenames, even if they contain spaces or whatnot.

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Find all storage devices attached to a Linux machine

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.

How do I get the current time zone of MySQL?

Simply SELECT @@system_time_zone;

Returns PST (or whatever is relevant to your system).

If you're trying to determine the session timezone you can use this query:
SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone);

Which will return the session timezone if it differs from the system timezone.

Executing command line programs from within python

This whole setup seems a little unstable to me.

Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.

Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.

How to manually set REFERER header in Javascript?

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Class constructor type in typescript?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

A Constructor type could be defined as:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;

 class A { ... }

 function factory(Ctor: AConstructorTypeOf<A>){
   return new Ctor();
 }

const aInstance = factory(A);

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

My solution is that i want data from all docs and i dont want _id, so

User.find({}, {_id:0, keyToShow:1, keyToNotShow:0})

What's the whole point of "localhost", hosts and ports at all?

In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.

Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.

It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.

Source: Wikipedia - Localhost.


The :80 part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.

How to trigger an event after using event.preventDefault()

Nope. Once the event has been canceled, it is canceled.

You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):

var lots_of_stuff_already_done = false;

$('.button').on('click', function(e) {
    if (lots_of_stuff_already_done) {
        lots_of_stuff_already_done = false; // reset flag
        return; // let the event bubble away
    }

    e.preventDefault();

    // do lots of stuff

    lots_of_stuff_already_done = true; // set flag
    $(this).trigger('click');
});

A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:

function onWithPrecondition(callback) {
    var isDone = false;

    return function(e) {
        if (isDone === true)
        {
            isDone = false;
            return;
        }

        e.preventDefault();

        callback.apply(this, arguments);

        isDone = true;
        $(this).trigger(e.type);
    }
}

Usage:

var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));

Bonus super-minimalistic jQuery plugin with Promise support:

(function( $ ) {
    $.fn.onButFirst = function(eventName,         /* the name of the event to bind to, e.g. 'click' */
                               workToBeDoneFirst, /* callback that must complete before the event is re-fired */
                               workDoneCallback   /* optional callback to execute before the event is left to bubble away */) {
        var isDone = false;

        this.on(eventName, function(e) {
            if (isDone === true) {
                isDone = false;
                workDoneCallback && workDoneCallback.apply(this, arguments);
                return;
            }

            e.preventDefault();

            // capture target to re-fire event at
            var $target = $(this);

            // set up callback for when workToBeDoneFirst has completed
            var successfullyCompleted = function() {
                isDone = true;
                $target.trigger(e.type);
            };

            // execute workToBeDoneFirst callback
            var workResult = workToBeDoneFirst.apply(this, arguments);

            // check if workToBeDoneFirst returned a promise
            if (workResult && $.isFunction(workResult.then))
            {
                workResult.then(successfullyCompleted);
            }
            else
            {
                successfullyCompleted();
            }
        });

        return this;
    };
}(jQuery));

Usage:

$('.button').onButFirst('click',
    function(){
        console.log('doing lots of work!');
    },
    function(){
        console.log('done lots of work!');
    });

How to display a Yes/No dialog box on Android?

Try this:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Confirm");
builder.setMessage("Are you sure?");

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
        // Do nothing but close the dialog

        dialog.dismiss();
    }
});

builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        // Do nothing
        dialog.dismiss();
    }
});

AlertDialog alert = builder.create();
alert.show();

What should be in my .gitignore for an Android Studio project?

I'm kosher with adding the .iml files and Intellij sez to add the .idea folder but ignore .idea/workspace.xml and .idea/tasks.xml, but what about .idea/libraries/ ?

I don't see how it makes sense to add this. It has a list of XML files that list libraries the Android Studio project is supposed to know about. These are supposed to come instead from build.gradle defined dependencies -- not an IDE project file.

Also the contents of one of these files looks like this:

<component name="libraryTable">
    <CLASSES>
       <root url="jar://$USER_HOME$/.gradle/caches/artifacts-26/filestore/com.example/example/etc...jar!"/>

It doesn't make sense to commit this. What if the user specified a different home dir for gradle, or if they use a different gradle version, the path under .gradle/caches/artifacts-xxx is going to be different for them (i.e. artifacts- the number appended on the end will relate to the gradle version release you are using.) These paths are not universal, and yet the advice is to check all this in?

How to overload functions in javascript?

What you are trying to achieve is best done using the function's local arguments variable.

function foo() {
    if (arguments.length === 0) {
        //do something
    }
    if (arguments.length === 1) {
        //do something else
    }
}

foo(); //do something
foo('one'); //do something else

You can find a better explanation of how this works here.

Extract code country from phone number [libphonenumber]

In here you can save the phone number as international formatted phone number

internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);

it return the phone number as International format +94 71 560 4888

so now I have get country code as this

String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();

Hope this will help you

Limiting the output of PHP's echo to 200 characters

Like this:

echo substr($row['style-info'], 0, 200);

Or wrapped in a function:

function echo_200($str){
    echo substr($row['style-info'], 0, 200);
}

echo_200($str);

How to get error message when ifstream open fails

The std::system_error example above is slightly incorrect. std::system_category() will map the error codes from system's native error code facility. For *nix, this is errno. For Win32, it is GetLastError(). ie, on Windows, the above example will print

failed to open C:\path\to\forbidden: The data is invalid

because EACCES is 13 which is the Win32 error code ERROR_INVALID_DATA

To fix it, either use the system's native error code facility, eg on Win32

throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);

Or use errno and std::generic_category(), eg

throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);

How to use opencv in using Gradle?

The following permissions and features are necessary in the AndroidManifest.xml file without which you will get the following dialog box

"It seems that your device does not support camera (or it is locked). Application will be closed"

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

    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

T-SQL split string

The easiest way:

  1. Install SQL Server 2016
  2. Use STRING_SPLIT https://msdn.microsoft.com/en-us/library/mt684588.aspx

It works even in express edition :).

What is jQuery Unobtrusive Validation?

Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".

Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.

Is there an easy way to attach source in Eclipse?

I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah.

These times, I've realized that the last path element was "src". Just removing this path element (thus indeed pointing one level above the actual path where the "org" or "com" folder is located) magically makes it work.

Somehow, Eclipse seems to imply this "src" path element if present, and if you then have it included in the source path, Eclipse chokes. Or something like that.

Nested routes with react router v4 / v5

A complete answer for React Router v5.


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-5-demo

How to get absolute value from double - c-language

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

What is __declspec and when do I need to use it?

It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport) and __declspec(dllexport). Other uses (some Microsoft-only) are documented in the MSDN.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

The emulator tries to find a numeric keypad on the mac, but this is not found (MacBook Pro, MacBook Air and "normal/small" keyboard do not have it). You can deselect the option Connect Hardware Keyboard or just ignore the error message, it will have no negative effect on application.

hadoop copy a local file system folder to HDFS

Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:

To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"

eg)./hadoop fs -put /opt/csv/load.csv /user/load

Here the /opt/csv/load.csv is source file path from my local linux system.

/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"

To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"

eg)hadoop fs -get /user/load/a.csv /opt/csv/

After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.

This uploaded files could also be seen through HDFS NameNode web UI.

How to create exe of a console application

For .net core 2.1 console application, the following approaches worked for me:

1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):

dotnet appName.dll

2 - from Visual Studio

R.C solution and click publish
'Target location' -> 'configure' ->
   'Deployment Mode' = 'Self-Contained'
   'Target Runtime' = 'win-x64 or win-x86 depending on the OS'

References:

For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Node/Express file upload

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

// https://www.npmjs.com/package/formidable
const formidable    = require('formidable');

// https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js
const path          = require('path');

router.post('/upload', (req, res) => {
    console.log(req.files);

    let oldpath = req.files.fileUploaded.path;

    // https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js       
    let newpath = path.resolve( `./${req.files.fileUploaded.name}` );

    // copy
    // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean
    fs.copyFile( oldpath, newpath, (err) => {

        if (err) throw err;

        // delete
        fs.unlink( oldpath, (err) => {

            if (err) throw err;

            console.log('Success uploaded")
        } );                

    } );

});

How does JavaScript .prototype work?

I always like analogies when it comes to understand this type of stuff. 'Prototypical inheritance' is pretty confusing in comparison to class bass inheritance in my opinion, even though prototypes are much simpler paradigm. In fact with prototypes, there really is no inheritance, so the name in and of itself misleading, it's more a type of 'delegation'.

Imagine this ....

You're in high-school, and you're in class and have a quiz that's due today, but you don't have a pen to fill out your answers. Doh!

You're sitting next to your friend Finnius, who might have a pen. You ask, and he looks around his desk unsuccessfully, but instead of saying "I don't have a pen", he's a nice friend he checks with his other friend Derp if he has a pen. Derp does indeed have a spare pen and passes it back to Finnius, who passes it over to you to complete your quiz. Derp has entrusted the pen to Finnius, who has delegated the pen to you for use.

What is important here is that Derp does not give the pen to you, as you don't have a direct relationship with him.

This, is a simplified example of how prototypes work, where a tree of data is searched for the thing you're looking for.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

Validating file types by regular expression

Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):

^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$

You can use a tool like Expresso to test your regular expressions.

How do you get the selected value of a Spinner?

Spinner spinner=(Spinner) findViewById(R.id.spinnername);
String valueinString = spinner.getSelectedItem().toString();

In Case Spinner values are int the typecast it to int

int valueinInt=(int)(spinner.getSelectedItem());

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

Uploading images using Node.js, Express, and Mongoose

For Express 3.0, if you want to use the formidable events, you must remove the multipart middleware, so you can create the new instance of it.

To do this:

app.use(express.bodyParser());

Can be written as:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); // Remove this line

And now create the form object:

exports.upload = function(req, res) {
    var form = new formidable.IncomingForm;
    form.keepExtensions = true;
    form.uploadDir = 'tmp/';

    form.parse(req, function(err, fields, files){
        if (err) return res.end('You found error');
        // Do something with files.image etc
        console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(400, {'content-type': 'text/plain'}); // 400: Bad Request
        res.end('error:\n\n'+util.inspect(err));
    });
    res.end('Done');
    return;
};

I have also posted this on my blog, Getting formidable form object in Express 3.0 on upload.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

Question still relevant as of Android Studio 3.5.2 for Windows.

In my specific use case, I was trying to add Gander (https://github.com/Ashok-Varma/Gander) to my list of dependencies when I keep getting this particular headache.

It turns out that I have yet to get JCenter Certificate approved in my cacerts file. I'm going through a company firewall and i had to do this with dependencies that I attempt to import. Thus, to do so:

  1. Ensure that your Android Studio does not need to go through any proxy.

  2. Export the certificate where you get your dependency (usually just JCenter)

  3. Add the certificate to your cacerts file:

    keytool -import -alias [your-certificate-name] -keystore 'C:\Program Files\Java\jdk[version]\jre\lib\security\cacerts' -file [absolute\path\to\your\certificate].cer

  4. Restart Android Studio

  5. Try syncing again.

Answer is based on this one: https://stackoverflow.com/a/26183328/4972380

Compare two dates in Java

The following will return true if two Calendar variables have the same day of the year.

  public boolean isSameDay(Calendar c1, Calendar c2){
    final int DAY=1000*60*60*24;
    return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
  } // end isSameDay

Adding data attribute to DOM

 $(document.createElement("img")).attr({
                src: 'https://graph.facebook.com/'+friend.id+'/picture',
                title: friend.name ,
                'data-friend-id':friend.id,
                'data-friend-name':friend.name
            }).appendTo(divContainer);

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

Don't just enable the first occurrence of display_errors in the php.ini file. Make sure you scroll down to the "real" setting and change it from Off to On.

The thing is that if you settle with changing (i.e. uncomment + add = On) by the very first occurrence of display_errors your changes will be overwritten somewhere on line 480 where it's set to Off again.

Java array assignment (multiple values)

Yes:

float[] values = {0.1f, 0.2f, 0.3f};

This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:

values = new float[3];

or

values = new float[] {0.1f, 0.2f, 0.3f};

Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?

How to edit data in result grid in SQL Server Management Studio

Right click on any table in your dB of interest or any database in the server using master if there are joins or using multiple dBs. Select "edit top 200 rows". Select the "SQL" button in the task bar. Copy and paste your code over the existing code and run again. Now you can edit your query's result set. Sherry ;-)

Matplotlib make tick labels font size smaller

To specify both font size and rotation at the same time, try this:

plt.xticks(fontsize=14, rotation=90)

Add zero-padding to a string

int num = 1;
num.ToString("0000");

Convert SQL Server result set into string

Test this:

 DECLARE @result NVARCHAR(MAX)

 SELECT @result = STUFF(
                        (   SELECT ',' + CONVERT(NVARCHAR(20), StudentId) 
                            FROM Student 
                            WHERE condition = abc 
                            FOR xml path('')
                        )
                        , 1
                        , 1
                        , '')

Android Viewpager as Image Slide Gallery

I made a library named AndroidImageSlider, you can have a try.

enter image description here

ADB error: cannot connect to daemon

I can solve my problem, i'm install a new firewall and it's reason of my problem, when i uninstall it my problem is solved. because of a lot of viewed of this question, i suggest you to check your firewall and antivirus that give permission for your Android Debugger Bridge.

Install opencv for Python 3.3

EDIT: first try the new pip method:

Windows: pip3 install opencv-python opencv-contrib-python

Ubuntu: sudo apt install python3-opencv

or continue below for build instructions

Note: The original question was asking for OpenCV + Python 3.3 + Windows. Since then, Python 3.5 has been released. In addition, I use Ubuntu for most development so this answer will focus on that setup, unfortunately

OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 is possible! Here's how.

These steps are copied (and slightly modified) from:

Prerequisites

Install the required dependencies and optionally install/update some libraries on your system:

# Required dependencies
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
# Dependencies for Python bindings
# If you use a non-system copy of Python (eg. with pyenv or virtualenv), then you probably don't need to do this part
sudo apt install python3.5-dev libpython3-dev python3-numpy
# Optional, but installing these will ensure you have the latest versions compiled with OpenCV
sudo apt install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

Building OpenCV

CMake Flags

There are several flags and options to tweak your build of OpenCV. There might be comprehensive documentation about them, but here are some interesting flags that may be of use. They should be included in the cmake command:

# Builds in TBB, a threading library
-D WITH_TBB=ON
# Builds in Eigen, a linear algebra library
-D WITH_EIGEN=ON

Using non-system level Python versions

If you have multiple versions of Python (eg. from using pyenv or virtualenv), then you may want to build against a certain Python version. By default OpenCV will build for the system's version of Python. You can change this by adding these arguments to the cmake command seen later in the script. Actual values will depend on your setup. I use pyenv:

-D PYTHON_DEFAULT_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_INCLUDE_DIRS=$HOME/.pyenv/versions/3.5.2/include/python3.5m
-D PYTHON_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1

CMake Python error messages

The CMakeLists file will try to detect various versions of Python to build for. If you've got different versions here, it might get confused. The above arguments may only "fix" the issue for one version of Python but not the other. If you only care about that specific version, then there's nothing else to worry about.

This is the case for me so unfortunately, I haven't looked into how to resolve the issues with other Python versions.

Install script

# Clone OpenCV somewhere
# I'll put it into $HOME/code/opencv
OPENCV_DIR="$HOME/code/opencv"
OPENCV_VER="3.1.0"
git clone https://github.com/opencv/opencv "$OPENCV_DIR"
# This'll take a while...

# Now lets checkout the specific version we want
cd "$OPENCV_DIR"
git checkout "$OPENCV_VER"

# First OpenCV will generate the files needed to do the actual build.
# We'll put them in an output directory, in this case "release"
mkdir release
cd release

# Note: This is where you'd add build options, like TBB support or custom Python versions. See above sections.
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local "$OPENCV_DIR"

# At this point, take a look at the console output.
# OpenCV will print a report of modules and features that it can and can't support based on your system and installed libraries.
# The key here is to make sure it's not missing anything you'll need!
# If something's missing, then you'll need to install those dependencies and rerun the cmake command.

# OK, lets actually build this thing!
# Note: You can use the "make -jN" command, which will run N parallel jobs to speed up your build. Set N to whatever your machine can handle (usually <= the number of concurrent threads your CPU can run).
make
# This will also take a while...

# Now install the binaries!
sudo make install

By default, the install script will put the Python bindings in some system location, even if you've specified a custom version of Python to use. The fix is simple: Put a symlink to the bindings in your local site-packages:

ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so $HOME/.pyenv/versions/3.5.2/lib/python3.5/site-packages/

The first path will depend on the Python version you setup to build. The second depends on where your custom version of Python is located.

Test it!

OK lets try it out!

ipython

Python 3.5.2 (default, Sep 24 2016, 13:13:17) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import cv2

In [2]: img = cv2.imread('derp.png')
i
In [3]: img[0]
Out[3]: 
array([[26, 30, 31],
       [27, 31, 32],
       [27, 31, 32],
       ..., 
       [16, 19, 20],
       [16, 19, 20],
       [16, 19, 20]], dtype=uint8)

Better way to convert file sizes in Python

Instead of a size divisor of 1024 * 1024 you could use the << bitwise shifting operator, i.e. 1<<20 to get megabytes, 1<<30 to get gigabytes, etc.

In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20) which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR.

Megabytes are usually all that you need, or otherwise something like this can be used:

# bytes pretty-printing
UNITS_MAPPING = [
    (1<<50, ' PB'),
    (1<<40, ' TB'),
    (1<<30, ' GB'),
    (1<<20, ' MB'),
    (1<<10, ' KB'),
    (1, (' byte', ' bytes')),
]


def pretty_size(bytes, units=UNITS_MAPPING):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    for factor, suffix in units:
        if bytes >= factor:
            break
    amount = int(bytes / factor)

    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix

print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))

## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB

How to determine the encoding of text?

Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.

The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob)  # "utf-8" "us-ascii" etc

There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic. It can also get the encoding, by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)

JavaScript is in array

Best way to do it in 2019 is by using .includes()

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

First parameter is what you are searching for. Second parameter is the index position in this array at which to begin searching.

If you need to be crossbrowsy here - there are plenty of legacy answers.

comparing strings in vb

In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.

You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.

Sub Main()
    Dim a As String = New String("This")
    Dim b As String

    b = Console.ReadLine()

    If a = b Then
        Console.WriteLine("They are equal")
    Else
        Console.WriteLine("Not equal")
    End If
    Console.ReadLine()
End Sub

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

I had two controllers with the same name defined in two different javascript files. Irritating that angular can't give a clearer error message indicating a namespace conflict.

Creating a LINQ select from multiple tables

If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.

db.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<ObjectPermissions>(op => op.Pages)
db.LoadOptions = dlo;

var pageObject = from op in db.ObjectPermissions
         select op;

// no join needed

Then you can call

pageObject.Pages.PageID

Depending on what your data looks like, you'd probably want to do this the other way around,

DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Pages>(p => p.ObjectPermissions)
db.LoadOptions = dlo;

var pageObject = from p in db.Pages
                 select p;

// no join needed

var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;

SQL Delete Records within a specific Range

You gave a condition ID (>79 and < 296) then the answer is:

delete from tab
where id > 79 and id < 296

this is the same as:

delete from tab
where id between 80 and 295

if id is an integer.

All answered:

delete from tab
where id between 79 and 296

this is the same as:

delete from tab
where id => 79 and id <= 296

Mind the difference.

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

How to automate browsing using python?

You likely want urllib2. It can handle things like HTTPS, cookies, and authentication. You will probably also want BeautifulSoup to help parse the HTML pages.

PHP check if date between two dates

Edit: use <= or >= to count today's date.

This is the right answer for your code. Just use the strtotime() php function.

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}

Adding one day to a date

The modify() method that can be used to add increments to an existing DateTime value.

Create a new DateTime object with the current date and time:

$due_dt = new DateTime();

Once you have the DateTime object, you can manipulate its value by adding or subtracting time periods:

$due_dt->modify('+1 day');

You can read more on the PHP Manual.

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

What is a reasonable length limit on person "Name" fields?

Note that many cultures have 'second surnames' often called family names. For example, if you are dealing with Spanish people, they will appreciate having a family name separated from their 'surname'.

Best bet is to define a data type for the name components, use those for a data type for the surname and tweak depending on locale.

Convert Mat to Array/Vector in OpenCV

Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):

Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);

How to get access to raw resources that I put in res folder?

In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);

How does one use glide to download an image into a bitmap?

Make sure you are on the Lastest version

implementation 'com.github.bumptech.glide:glide:4.10.0'

Kotlin:

Glide.with(this)
        .asBitmap()
        .load(imagePath)
        .into(object : CustomTarget<Bitmap>(){
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                imageView.setImageBitmap(resource)
            }
            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for
                // some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView
                // clear it here as you can no longer have the bitmap
            }
        })

Bitmap Size:

if you want to use the original size of the image use the default constructor as above, else You can pass your desired size for bitmap

into(object : CustomTarget<Bitmap>(1980, 1080)

Java:

Glide.with(this)
        .asBitmap()
        .load(path)
        .into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                imageView.setImageBitmap(resource);
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });

Old Answer:

With compile 'com.github.bumptech.glide:glide:4.8.0' and below

Glide.with(this)
        .asBitmap()
        .load(path)
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                imageView.setImageBitmap(resource);
            }
        });

For compile 'com.github.bumptech.glide:glide:3.7.0' and below

Glide.with(this)
        .load(path)
        .asBitmap()
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                imageView.setImageBitmap(resource);
            }
        });

Now you might see a warning SimpleTarget is deprecated

Reason:

The main point of deprecating SimpleTarget is to warn you about the ways in which it tempts you to break Glide's API contract. Specifically, it doesn't do anything to force you to stop using any resource you've loaded once the SimpleTarget is cleared, which can lead to crashes and graphical corruption.

The SimpleTarget still can be used as long you make sure you are not using the bitmap once the imageView is cleared.

Change action bar color in android

onclick buttons c2 to fetch and change the color of action bar and notification bar according to button's background, hope this helps

int color = c2.getBackground()).getColor();
int colorlighter = -color * 40 / 100 + color;
getWindow().setNavigationBarColor(colorlighter);
getWindow().setStatusBarColor(colorlighter);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(color));

colorlighter is used to set color of notification bar a little lighter than action bar
color is the background color of button c2, according to which we change our color.

REST API - file (ie images) processing - best practices

Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):

  1. POST to /users to create the user entity.
  2. POST the image to /images, making sure to return a Location header to where the image can be retrieved per the HTTP spec.
  3. PATCH to /users/carPhoto and assign it the ID of the photo given in the Location header of step 2.

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

Scrolling a flexbox with overflowing content

One issue that I've come across is that to have a scrollbar a n element needs a height to be specified (and not as a %).

The trick is to nest another set of divs within each column, and set the column parent's display to flex with flex-direction: column.

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    body {
        overflow-y: hidden;
        overflow-x: hidden;
        color: white;
    }

    .base-container {
        display: flex;
        flex: 1;
        flex-direction: column;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        align-items: stretch;
    }

    .title {
        flex: 0 0 50px;
        color: black;
    }

    .container {
        flex: 1 1 auto;
        display: flex;
        flex-direction: column;
    }

        .container .header {
            flex: 0 0 50px;
            background-color: red;
        }

        .container .body {
            flex: 1 1 auto;
            display: flex;
            flex-direction: row;
        }

            .container .body .left {
                display: flex;
                flex-direction: column;
                flex: 0 0 80px;
                background-color: blue;
            }
                .container .body .left .content,
                .container .body .main .content,
                .container .body .right .content {
                    flex: 1 1 auto;
                    overflow-y: auto;
                    height: 100px;
                }
                .container .body .main .content.noscrollbar {
                    overflow-y: hidden;
                }

            .container .body .main {
                display: flex;
                flex-direction: column;
                flex: 1 1 auto;
                background-color: green;
            }

            .container .body .right {
                display: flex;
                flex-direction: column;
                flex: 0 0 300px;
                background-color: yellow;
                color: black;
            }

    .test {
        margin: 5px 5px;
        border: 1px solid white;
        height: calc(100% - 10px);
    }
</style>

And here's the html:

<div class="base-container">
    <div class="title">
        Title
    </div>
    <div class="container">
        <div class="header">
            Header
        </div>
        <div class="body">
            <div class="left">
                <div class="content">
                    <ul>
                        <li>1</li>
                        <li>2</li>
                        <li>3</li>
                        <li>4</li>
                        <li>5</li>
                        <li>6</li>
                        <li>7</li>
                        <li>8</li>
                        <li>9</li>
                        <li>10</li>
                        <li>12</li>
                        <li>13</li>
                        <li>14</li>
                        <li>15</li>
                        <li>16</li>
                        <li>17</li>
                        <li>18</li>
                        <li>19</li>
                        <li>20</li>
                        <li>21</li>
                        <li>22</li>
                        <li>23</li>
                        <li>24</li>
                    </ul>
                </div>
            </div>
            <div class="main">
                <div class="content noscrollbar">
                    <div class="test">Test</div>
                </div>
            </div>
            <div class="right">
                <div class="content">
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>End</div>
                </div>
            </div>
        </div>
    </div>
</div>

https://jsfiddle.net/LiamFlavelle/czpjdfr4/

Execute a large SQL script (with GO commands)

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Sample code:

public static void Main()    
{        
  string scriptDirectory = "c:\\temp\\sqltest\\";
  string sqlConnectionString = "Integrated Security=SSPI;" +
  "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
  DirectoryInfo di = new DirectoryInfo(scriptDirectory);
  FileInfo[] rgFiles = di.GetFiles("*.sql");
  foreach (FileInfo fi in rgFiles)
  {
        FileInfo fileInfo = new FileInfo(fi.FullName);
        string script = fileInfo.OpenText().ReadToEnd();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
   }
}

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

'"SDL.h" no such file or directory found' when compiling

For Simple Direct Media Layer 2 (SDL2), after installing it on Ubuntu 16.04 via:

sudo apt-get install libsdl2-dev

I used the header:

#include <SDL2/SDL.h>  

and the compiler linker command:

-lSDL2main -lSDL2 

Additionally, you may also want to install:

apt-get install libsdl2-image-dev  
apt-get install libsdl2-mixer-dev  
apt-get install libsdl2-ttf-dev  

With these headers:

#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>  

and the compiler linker commands:

-lSDL2_image 
-lSDL2_ttf 
-lSDL2_mixer

How do I replace whitespaces with underscore?

Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

This isn't exactly the output you asked for, but IMO it's better for use in URLs.

Can a unit test project load the target application's app.config file?

The simplest way to do this is to add the .config file in the deployment section on your unit test.

To do so, open the .testrunconfig file from your Solution Items. In the Deployment section, add the output .config files from your project's build directory (presumably bin\Debug).

Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.

Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config to match the unit test's name.

Is a view faster than a simple query?

Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.

That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:

  1. Not every view can be made into an indexed view; they have to follow a specific set of guidelines, which (among other restrictions) means you can't include common query elements like COUNT, MIN, MAX, or TOP.
  2. Indexed views use physical space in the database, just like indexes on a table.

This article describes additional benefits and limitations of indexed views:

You Can…

  • The view definition can reference one or more tables in the same database.
  • Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
  • You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.

You Can’t…

  • The view definition can’t reference other views, or tables in other databases.
  • It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
  • You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
  • You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.

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

use the latest one for bootstrap 4 and above, this won't affect your UI

PowerShell: Create Local User Account

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account." 

When tracing out variables in the console, How to create a new line?

console.log('Hello, \n' + 
            'Text under your Header\n' + 
            '-------------------------\n' + 
            'More Text\n' +
            'Moree Text\n' +
            'Moooooer Text\n' );

This works great for me for text only, and easy on the eye.

Saving results with headers in Sql Server Management Studio

Tools > Options > Query Results > SQL Server > Results to Text (or Grid if you want) > Include columns headers in the result set

You might need to close and reopen SSMS after changing this option.

On the SQL Editor Toolbar you can select save to file without having to restart SSMS

PHP Constants Containing Arrays?

I know it's a bit old question, but here is my solution:

<?php
class Constant {

    private $data = [];

    public function define($constant, $value) {
        if (!isset($this->data[$constant])) {
            $this->data[$constant] = $value;
        } else {
            trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
        }
    }

    public function __get($constant) {
        if (isset($this->data[$constant])) {
            return $this->data[$constant];
        } else {
            trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
            return $constant;
        }
    }

    public function __set($constant,$value) {
        $this->define($constant, $value);
    }

}
$const = new Constant;

I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.

You can use it as $const->define("my_constant",array("my","values")); or just $const->my_constant = array("my","values");

To get the value just simply call $const->my_constant;

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
  <li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>

The fa-ul and fa-li classes easily replace default bullets in unordered lists.

Java for loop multiple variables

  1. It is cards.length(), not cards.length (length is a method of java.lang.String, not an attribute).

  2. It is System.out (capital 's'), not system.out. See java.lang.System.

  3. It is

    for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
    

    not

    for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
    
  4. Syntactically, it is if(rank == cards.substring(a,b)){, not if(rank===cards.substring(a,b){ (double equals, not triple equals; missing closing parenthesis), but to compare if two Strings are equal you need to use equals(): if(rank.equals(cards.substring(a,b))){

You should probably consider downloading Eclipse, which is an integrated development environment (not only) for Java development. Eclipse shows you the errors while you type and also provides help in fixing these. This makes it much easier to get started with Java development.

How do I upgrade to Python 3.6 with conda?

Anaconda has not updated python internally to 3.6.

a) Method 1

  1. If you wanted to update you will type conda update python
  2. To update anaconda type conda update anaconda
  3. If you want to upgrade between major python version like 3.5 to 3.6, you'll have to do

    conda install python=$pythonversion$
    

b) Method 2 - Create a new environment (Better Method)

conda create --name py36 python=3.6

c) To get the absolute latest python(3.6.5 at time of writing)

conda create --name py365 python=3.6.5 --channel conda-forge

You can see all this from here

Also, refer to this for force upgrading

EDIT: Anaconda now has a Python 3.6 version here

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

Use the AutoSize and AutoSizeMode properties.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx

An example:

private void Form1_Load(object sender, EventArgs e)
{
    // no smaller than design time size
    this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);

    // no larger than screen size
    this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);

    this.AutoSize = true;
    this.AutoSizeMode = AutoSizeMode.GrowAndShrink;

    // rest of your code here...
}

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Difference between string and char[] types in C++

Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.

In terms of API and standard library everything is implemented in terms of strings and not char[], but there are still lots of functions from the libc that receive char[] so you may need to use it for those, apart from that I would always use std::string.

In terms of efficiency of course a raw buffer of unmanaged memory will almost always be faster for lots of things, but take in account comparing strings for example, std::string has always the size to check it first, while with char[] you need to compare character by character.

Windows 8.1 gets Error 720 on connect VPN

I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command

Dism /Online /Cleanup-Image /RestoreHealth

Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.

Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

Get a Windows Forms control by name in C#

You can use find function in your Form class. If you want to cast (Label) ,(TextView) ... etc, in this way you can use special features of objects. It will be return Label object.

(Label)this.Controls.Find(name,true)[0];

name: item name of searched item in the form

true: Search all Children boolean value

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

I think you need OpenSessionInViewFilter to keep your session open during view rendering (but it is not too good practice).

Close a div by clicking outside

You'd better go with something like this. Just give an id to the div which you want to hide and make a function like this. call this function by adding onclick event on body.

function myFunction(event) { 

if(event.target.id!="target_id")
{ 
    document.getElementById("target_id").style.display="none";
  }
}

How and where are Annotations used in Java?

Frameworks like Hibernate were lots of configuration/mapping is required uses Annotations heavily.

Take a look at Hibernate Annotations

How can I find the link URL by link text with XPath?

Think of the phrase in the square brackets as a WHERE clause in SQL.

So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".

invalid types 'int[int]' for array subscript

int myArray[10][10][10];

should be

int myArray[10][10][10][10];

Disable browser 'Save Password' functionality

autocomplete="off" does not work for disabling the password manager in Firefox 31 and most likely not in some earlier versions, too.

Checkout the discussion at mozilla about this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=956906

We wanted to use a second password field to enter a one-time password generated by a token. Now we are using a text input instead of a password input. :-(

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Adding/removing items from a JavaScript object with jQuery

Well, it's just a javascript object, so you can manipulate data.items just like you would an ordinary array. If you do:

data.items.pop();

your items array will be 1 item shorter.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

How to set a JavaScript breakpoint from code in Chrome?

There are many ways to debug JavaScript code. Following two approaches are widely used to debug JavaScript via code

  1. Using console.log() to print out the values in the browser console. (This will help you understand the values at certain points of your code)

  2. Debugger keyword. Add debugger; to the locations you want to debug, and open the browser's developer console and navigate to the sources tab.

For more tools and ways in which you debug JavaScript Code, are given in this link by W3School.

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

How do you get a directory listing in C?

You can find the sample code on the wikibooks link

/**************************************************************
 * A simpler and shorter implementation of ls(1)
 * ls(1) is very similar to the DIR command on DOS and Windows.
 **************************************************************/
#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) 
{
  struct dirent *entry;
  DIR *dp;

  dp = opendir(path);
  if (dp == NULL) 
  {
    perror("opendir");
    return -1;
  }

  while((entry = readdir(dp)))
    puts(entry->d_name);

  closedir(dp);
  return 0;
}

int main(int argc, char **argv) {
  int counter = 1;

  if (argc == 1)
    listdir(".");

  while (++counter <= argc) {
    printf("\nListing %s...\n", argv[counter-1]);
    listdir(argv[counter-1]);
  }

  return 0;
}

Going to a specific line number using Less in Unix

You can use sed for this too -

sed -n '320123'p filename 

This will print line number 320123.

If you want a range then you can do -

sed -n '320123,320150'p filename 

If you want from a particular line to the very end then -

sed -n '320123,$'p filename 

How to remove a column from an existing table?

This is the correct answer:

ALTER TABLE MEN DROP COLUMN Lname

But... if a CONSTRAINT exists on the COLUMN, then you must DROP the CONSTRAINT first, then you will be able to DROP the COLUMN. In order to drop a CONSTRAINT, run:

ALTER TABLE MEN DROP CONSTRAINT {constraint_name_on_column_Lname}

LINQ select in C# dictionary

This will return all the values matching your key valueTitle

subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();

What is a "thread" (really)?

I am going to use a lot of text from the book Operating Systems Concepts by ABRAHAM SILBERSCHATZ, PETER BAER GALVIN and GREG GAGNE along with my own understanding of things.

Process

Any application resides in the computer in the form of text (or code).

We emphasize that a program by itself is not a process. A program is a passive entity, such as a file containing a list of instructions stored on disk (often called an executable file).

When we start an application, we create an instance of execution. This instance of execution is called a process. EDIT:(As per my interpretation, analogous to a class and an instance of a class, the instance of a class being a process. )

An example of processes is that of Google Chrome. When we start Google Chrome, 3 processes are spawned:

• The browser process is responsible for managing the user interface as well as disk and network I/O. A new browser process is created when Chrome is started. Only one browser process is created.

Renderer processes contain logic for rendering web pages. Thus, they contain the logic for handling HTML, Javascript, images, and so forth. As a general rule, a new renderer process is created for each website opened in a new tab, and so several renderer processes may be active at the same time.

• A plug-in process is created for each type of plug-in (such as Flash or QuickTime) in use. Plug-in processes contain the code for the plug-in as well as additional code that enables the plug-in to communicate with associated renderer processes and the browser process.

Thread

To answer this I think you should first know what a processor is. A Processor is the piece of hardware that actually performs the computations. EDIT: (Computations like adding two numbers, sorting an array, basically executing the code that has been written)

Now moving on to the definition of a thread.

A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack.

EDIT: Definition of a thread from intel's website:

A Thread, or thread of execution, is a software term for the basic ordered sequence of instructions that can be passed through or processed by a single CPU core.

So, if the Renderer process from the Chrome application sorts an array of numbers, the sorting will take place on a thread/thread of execution. (The grammar regarding threads seems confusing to me)

My Interpretation of Things

A process is an execution instance. Threads are the actual workers that perform the computations via CPU access. When there are multiple threads running for a process, the process provides common memory.

EDIT: Other Information that I found useful to give more context

All modern day computer have more than one threads. The number of threads in a computer depends on the number of cores in a computer.

Concurrent Computing:

From Wikipedia:

Concurrent computing is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts). This is a property of a system—this may be an individual program, a computer, or a network—and there is a separate execution point or "thread of control" for each computation ("process").

So, I could write a program which calculates the sum of 4 numbers:

(1 + 3) + (4 + 5)

In the program to compute this sum (which will be one process running on a thread of execution) I can fork another process which can run on a different thread to compute (4 + 5) and return the result to the original process, while the original process calculates the sum of (1 + 3).

Check that a variable is a number in UNIX shell

This can be checked using regular expression.

 ###    
    echo $var|egrep '^[0-9]+$'
    if [ $? -eq 0 ]; then
        echo "$var is a number"
    else
        echo "$var is not a number"
    fi

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

Searching for Text within Oracle Stored Procedures

I allways use UPPER(text) like UPPER('%blah%')

How can I get the selected VALUE out of a QCombobox?

I know I'm very late but for those who still have that problem, it can be solved easily. I use Qt 5.3 and it works fine. No need to create a function or all that.

int valueComboBox;
valueComboBox = comboBox->currentIndex();

and it works ! Hope it helps !

Can I get image from canvas element and use it in img src tag?

Do this. Add this to the bottom of your doc just before you close the body tag.

<script>
    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box
      ctx.fillStyle="#FF0000";
      ctx.fillRect(10,10,30,30);

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document
    }

    canvasToImg(); //execute the function
</script>

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" />

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

Git: Cannot see new remote branch

Check whether .git/config contains

[remote "origin"]
    url = …
    fetch = +refs/heads/master:refs/remotes/origin/master

If so, change it to say

[remote "origin"]
    url = …
    fetch = +refs/heads/*:refs/remotes/origin/*

Then you should be able to use it:

$ git fetch
remote: Counting objects: …
remote: Compressing objects: ..
Unpacking objects: …
remote: …
From …
 * [new branch]            branchname -> origin/branchname
$ git checkout branchname
Branch branchname set up to track remote branch branchname from origin.
Switched to a new branch 'branchname'

pandas dataframe convert column type to string or categorical

You need astype:

df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)

For converting to categorical:

df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')

Another solution is Categorical:

df['zipcode'] = pd.Categorical(df.zipcode)

Sample with data:

import pandas as pd

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

print (df.dtypes)
bathrooms      float64
bedrooms         int64
floors         float64
sqft_living      int64
sqft_lot         int64
zipcode          int64
dtype: object

df['zipcode'] = df.zipcode.astype('category')

print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot zipcode
722         3.25         4     2.0         4670     51836   98005
2680        0.75         2     1.0         1440      3700   98107
14554       2.50         4     2.0         3180      9603   98155
17384       1.50         2     3.0         1430      1650   98125
18754       1.00         2     1.0         1130      2640   98109

print (df.dtypes)
bathrooms       float64
bedrooms          int64
floors          float64
sqft_living       int64
sqft_lot          int64
zipcode        category
dtype: object

Loading .sql files from within PHP

phpBB uses a few functions to parse their files. They are rather well-commented (what an exception!) so you can easily know what they do (I got this solution from http://www.frihost.com/forums/vt-8194.html). here is the solution an I've used it a lot:

<php
ini_set('memory_limit', '5120M');
set_time_limit ( 0 );
/***************************************************************************
*                             sql_parse.php
*                              -------------------
*     begin                : Thu May 31, 2001
*     copyright            : (C) 2001 The phpBB Group
*     email                : [email protected]
*
*     $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
*
****************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

/***************************************************************************
*
*   These functions are mainly for use in the db_utilities under the admin
*   however in order to make these functions available elsewhere, specifically
*   in the installation phase of phpBB I have seperated out a couple of
*   functions into this file.  JLH
*
\***************************************************************************/

//
// remove_comments will strip the sql comment lines out of an uploaded sql file
// specifically for mssql and postgres type files in the install....
//
function remove_comments(&$output)
{
   $lines = explode("\n", $output);
   $output = "";

   // try to keep mem. use down
   $linecount = count($lines);

   $in_comment = false;
   for($i = 0; $i &lt; $linecount; $i++)
   {
      if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
      {
         $in_comment = true;
      }

      if( !$in_comment )
      {
         $output .= $lines[$i] . "\n";
      }

      if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
      {
         $in_comment = false;
      }
   }

   unset($lines);
   return $output;
}

//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
   $lines = explode("\n", $sql);

   // try to keep mem. use down
   $sql = "";

   $linecount = count($lines);
   $output = "";

   for ($i = 0; $i &lt; $linecount; $i++)
   {
      if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
      {
         if (isset($lines[$i][0]) && $lines[$i][0] != "#")
         {
            $output .= $lines[$i] . "\n";
         }
         else
         {
            $output .= "\n";
         }
         // Trading a bit of speed for lower mem. use here.
         $lines[$i] = "";
      }
   }

   return $output;

}

//
// split_sql_file will split an uploaded sql file into single sql statements.
// Note: expects trim() to have already been run on $sql.
//
function split_sql_file($sql, $delimiter)
{
   // Split up our string into "possible" SQL statements.
   $tokens = explode($delimiter, $sql);

   // try to save mem.
   $sql = "";
   $output = array();

   // we don't actually care about the matches preg gives us.
   $matches = array();

   // this is faster than calling count($oktens) every time thru the loop.
   $token_count = count($tokens);
   for ($i = 0; $i &lt; $token_count; $i++)
   {
      // Don't wanna add an empty string as the last thing in the array.
      if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
      {
         // This is the total number of single quotes in the token.
         $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
         // Counts single quotes that are preceded by an odd number of backslashes,
         // which means they're escaped quotes.
         $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

         $unescaped_quotes = $total_quotes - $escaped_quotes;

         // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
         if (($unescaped_quotes % 2) == 0)
         {
            // It's a complete sql statement.
            $output[] = $tokens[$i];
            // save memory.
            $tokens[$i] = "";
         }
         else
         {
            // incomplete sql statement. keep adding tokens until we have a complete one.
            // $temp will hold what we have so far.
            $temp = $tokens[$i] . $delimiter;
            // save memory..
            $tokens[$i] = "";

            // Do we have a complete statement yet?
            $complete_stmt = false;

            for ($j = $i + 1; (!$complete_stmt && ($j &lt; $token_count)); $j++)
            {
               // This is the total number of single quotes in the token.
               $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
               // Counts single quotes that are preceded by an odd number of backslashes,
               // which means they're escaped quotes.
               $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

               $unescaped_quotes = $total_quotes - $escaped_quotes;

               if (($unescaped_quotes % 2) == 1)
               {
                  // odd number of unescaped quotes. In combination with the previous incomplete
                  // statement(s), we now have a complete statement. (2 odds always make an even)
                  $output[] = $temp . $tokens[$j];

                  // save memory.
                  $tokens[$j] = "";
                  $temp = "";

                  // exit the loop.
                  $complete_stmt = true;
                  // make sure the outer loop continues at the right point.
                  $i = $j;
               }
               else
               {
                  // even number of unescaped quotes. We still don't have a complete statement.
                  // (1 odd and 1 even always make an odd)
                  $temp .= $tokens[$j] . $delimiter;
                  // save memory.
                  $tokens[$j] = "";
               }

            } // for..
         } // else
      }
   }

   return $output;
}

$dbms_schema = 'yourfile.sql';

$sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
$sql_query = remove_remarks($sql_query);
$sql_query = split_sql_file($sql_query, ';');

$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database_name';

//In case mysql is deprecated use mysqli functions. 
mysqli_connect($host,$user,$pass) or die('error connection');
mysqli_select_db($db) or die('error database selection');

$i=1;
foreach($sql_query as $sql){
echo $i++;
echo "<br />";
mysql_query($sql) or die('error in query');
}

?>

How to keep the spaces at the end and/or at the beginning of a String?

Working well I'm using \u0020

<string name="hi"> Hi \u0020 </string>
<string name="ten"> \u0020 out of 10  </string>
<string name="youHaveScored">\u0020 you have Scored \u0020</string>

Java file

String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
               Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();

Screenshot here Image of Showing Working of this code

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

Array of PHP Objects

Yes, its possible to have array of objects in PHP.

class MyObject {
  private $property;

  public function  __construct($property) {
    $this->Property = $property;
  }
}
$ListOfObjects[] = new myObject(1); 
$ListOfObjects[] = new myObject(2); 
$ListOfObjects[] = new myObject(3); 
$ListOfObjects[] = new myObject(4); 

print "<pre>";
print_r($ListOfObjects);
print "</pre>";

Content is not allowed in Prolog SAXParserException

Check the XML. It is not a valid xml.

Prolog is the first line with xml version info. It ok not to include it in your xml.

This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.

e.g.

  1. Root/><document>
  2. Root<document>

PHP: How to get current time in hour:minute:second?

Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.

Looking up a function is easy, just visit http://php.net/<function name> and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.

We immediately learn a couple things about this function by examining its signature:

string date ( string $format [, int $timestamp = time() ] )

First, it returns a string. That's what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).

date("d-m-Y") // produces something like 03-12-2012

In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.

To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:

h   12-hour format of an hour with leading zeros    01 through 12
i   Minutes with leading zeros                      00 to 59
s   Seconds, with leading zeros                     00 through 59

With this in mind, we can no create a new format string:

date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13

Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.

Format a JavaScript string using placeholders and an object of substitutions?

const stringInject = (str = '', obj = {}) => {
  let newStr = str;
  Object.keys(obj).forEach((key) => {
    let placeHolder = `#${key}#`;
    if(newStr.includes(placeHolder)) {
      newStr = newStr.replace(placeHolder, obj[key] || " ");
    }
  });
  return newStr;
}
Input: stringInject("Hi #name#, How are you?", {name: "Ram"});
Output: "Hi Ram, How are you?"

Resize HTML5 canvas to fit window

A pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).

<!DOCTYPE html>
<html>
    <head>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }
        canvas {
            background-color: #ccc;
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillRect(25,25,100,100);
            ctx.clearRect(45,45,60,60);
            ctx.strokeRect(50,50,50,50);
        }
    </script>
</body>
</html>

Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html

But take care, as @jerseyboy states in his comment:

Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

A more un-obtrusive way (assuming you use jQuery):

HTML:

<a id="my-link" href="page.html">page link</a>

Javascript:

$('#my-link').click(function(e)
{
    e.preventDefault();
});

The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Subset and ggplot2

There's another solution that I find useful, especially when I want to plot multiple subsets of the same object:

myplot<-ggplot(df)+geom_line(aes(Value1, Value2, group=ID, colour=ID))
myplot %+% subset(df, ID %in% c("P1","P3"))
myplot %+% subset(df, ID %in% c("P2"))

Fetch: reject promise and catch the error if status is not OK?

I just checked the status of the response object:

$promise.then( function successCallback(response) {  
  console.log(response);
  if (response.status === 200) { ... }
});

javascript date + 7 days

In One line:

new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)

How do I measure a time interval in C?

On Linux you can use clock_gettime():

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp

// ... do stuff ... //

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);   // get final time-stamp

double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
              (double)(end.tv_nsec - start.tv_nsec);
                                                 // subtract time-stamps and
                                                 // multiply to get elapsed
                                                 // time in ns

Git add and commit in one command

If you type:

git config --global alias.a '!git add -A && git commit -m'

once, you will just need to type

git a

every time:

git a 'your comment'

get UTC timestamp in python with datetime

If input datetime object is in UTC:

>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0

Note: it returns float i.e., microseconds are represented as fractions of a second.

If input date object is in UTC:

>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600

See more details at Converting datetime.date to UTC timestamp in Python.

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.

This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.

console.writeline and System.out.println

There's no Console.writeline in Java. Its in .NET.

Console and standard out are not same. If you read the Javadoc page you mentioned, you will see that an application can have access to a console only if it is invoked from the command line and the output is not redirected like this

java -jar MyApp.jar > MyApp.log

Other such cases are covered in SimonJ's answer, though he missed out on the point that there's no Console.writeline.

Changing color of Twitter bootstrap Nav-Pills

You can supply your own class to the nav-pills container with your custom color for your active link, that way you can create as many colors as you like without modifying the bootstrap default colors in other sections of your page. Try this:

Markup

<ul class="nav nav-pills red">
    <li class="active"><a href="#tab1" data-toggle="tab">Overview</a></li>
    <li><a href="#tab2" data-toggle="tab">Sample</a></li>
    <li><a href="#tab3" data-toggle="tab">Sample</a></li>
</ul>

And here is the CSS for your custom color:

.red .active a,
.red .active a:hover {
    background-color: red;
}

Also, if you prefer to replace the default color for the .active item in your nav-pills you can modify the original like so:

.nav-pills > .active > a, .nav-pills > .active > a:hover {
    background-color: red;
}

Adjust width of input field to its input

You can do it even simpler in angularjs using the built-in ng-style directive.

In your html:

  <input ng-style="inputStyle(testdata)" ng-model="testdata" />

In your controller:

 $scope.testdata = "whatever";

 $scope.inputStyle = function(str) {
    var charWidth = 7;
    return  {"width": (str.length +1) * charWidth + "px" };
    };

In your css:

input { font-family:monospace; font-size:12px; }

Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;

How to find the socket buffer size of linux

For getting the buffer size in c/c++ program the following is the flow

int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size

How to obfuscate Python code effectively?

You could embed your code in C/C++ and compile Embedding Python in Another Application

embedded.c

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("print('Hello world !')");
  Py_Finalize();
  return 0;
}

In Ubuntu/Debian

$ sudo apt-get install python-dev

In Centos/Redhat/Fedora

$ sudo yum install python-devel

compile with

$ gcc -o embedded -fPIC -I/usr/include/python2.7 -lpython2.7 embedded.c

run with

$ chmod u+x ./embedded
$ time ./embedded
Hello world !

real  0m0.014s
user  0m0.008s
sys 0m0.004s

initial script: hello_world.py:

print('Hello World !')

run the script

$ time python hello_world.py
Hello World !

real  0m0.014s
user  0m0.008s
sys 0m0.004s

however some strings of the python code may be found in the compiled file

$ grep "Hello" ./embedded
Binary file ./embedded matches

$ grep "Hello World" ./embedded
$

In case you want an extra bit of obfuscation you could use base64

...
PyRun_SimpleString("import base64\n"
                  "base64_code = 'your python code in base64'\n"
                  "code = base64.b64decode(base64_code)\n"
                  "exec(code)");
...

e.g:

create the base 64 string of your code

$ base64 hello_world.py
cHJpbnQoJ0hlbGxvIFdvcmxkICEnKQoK

embedded_base64.c

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("import base64\n"
                    "base64_code = 'cHJpbnQoJ0hlbGxvIFdvcmxkICEnKQoK'\n"
                    "code = base64.b64decode(base64_code)\n"
                    "exec(code)\n");
  Py_Finalize();
  return 0;
}

all commands

$ gcc -o embedded_base64 -fPIC -I/usr/include/python2.7 -lpython2.7 ./embedded_base64.c
$ chmod u+x ./embedded_base64

$ time ./embedded_base64
Hello World !

real  0m0.014s
user  0m0.008s
sys 0m0.004s

$ grep "Hello" ./embedded_base64
$

update:

this project (pyarmor) might also help:

https://pypi.org/project/pyarmor/

Use dynamic (variable) string as regex pattern in JavaScript

I found this thread useful - so I thought I would add the answer to my own problem.

I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.

This was my solution.

dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'

// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
    // need to use double escape '\\' when putting regex in strings !
    var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
    var myRegExp = new RegExp(searchString + re, "g");
    var match = myRegExp.exec(data);
    var replaceThis = match[1];
    var writeString = data.replace(replaceThis, newString);
    fs.writeFile(file, writeString, 'utf-8', function (err) {
    if (err) throw err;
        console.log(file + ' updated');
    });
});
}

searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"

replaceStringNextLine(dse_cassandra_yaml, searchString, newString );

After running, it will change the existing data directory setting to the new one:

config file before:

data_file_directories:  
   - /var/lib/cassandra/data

config file after:

data_file_directories:  
- /mnt/cassandra/data

How do I make a delay in Java?

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000) or any other millisecond value:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms) but replace ms with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

Spring Boot - inject map from application.yml

You can make it even simplier, if you want to avoid extra structures.

service:
  mappings:
    key1: value1
    key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {

  @Bean
  @ConfigurationProperties(prefix = "service.mappings")
  public Map<String, String> serviceMappings() {
    return new HashMap<>();
  }

}

And then use it as usual, for example with a constructor:

public class Foo {

  private final Map<String, String> serviceMappings;

  public Foo(Map<String, String> serviceMappings) {
    this.serviceMappings = serviceMappings;
  }

}

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4


The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

Better way to check if a Path is a File or a Directory?

With only this line you can get if a path is a directory or a file:

File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

Why is Spring's ApplicationContext.getBean considered bad?

Others have pointed to the general problem (and are valid answers), but I'll just offer one additional comment: it's not that you should NEVER do it, but rather that do it as little as possible.

Usually this means that it is done exactly once: during bootstrapping. And then it's just to access the "root" bean, through which other dependencies can be resolved. This can be reusable code, like base servlet (if developing web apps).

Creating a .dll file in C#.Net

You need to make a class library and not a Console Application. The console application is translated into an .exe whereas the class library will then be compiled into a dll which you can reference in your windows project.

  • Right click on your Console Application -> Properties -> Change the Output type to Class Library

enter image description here

How to program a fractal?

Well, simple and graphically appealing don't really go hand in hand. If you're serious about programming fractals, I suggest reading up on iterated function systems and the advances that have been made in rendering them.

http://flam3.com/flame_draves.pdf

Android RatingBar change star colors

It's a little complicated at the mentioned blog, I've used a similar but simplier way. You do need 3 star images (red_star_full.png, red_star_half.png and red_star_empty.png) and one xml, that's all.

Put these 3 images at res/drawable.

Put there the following ratingbar_red.xml:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/red_star_empty" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/red_star_half" />
    <item android:id="@android:id/progress" android:drawable="@drawable/red_star_full" />
</layer-list>

and, finally, tell your ratingbar definition to use this, i.e.

<RatingBar android:progressDrawable="@drawable/ratingbar_red"/>

That's it.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I think the best solution to this problem can be found here: IIS_IUSRS and IUSR permissions in IIS8 This a good workaround but it does not work when you access the webserver over the Internet.

Check if string is neither empty nor space in shell script

You need a space on either side of the !=. Change your code to:

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str" != " " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2" != " " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3" != " " ]; then
        echo "Str3 is not null or space"
fi

ASP.NET Identity reset password

Deprecated

This was the original answer. It does work, but has a problem. What if AddPassword fails? The user is left without a password.

The original answer: we can use three lines of code:

UserManager<IdentityUser> userManager = 
    new UserManager<IdentityUser>(new UserStore<IdentityUser>());

userManager.RemovePassword(userId);

userManager.AddPassword(userId, newPassword);

See also: http://msdn.microsoft.com/en-us/library/dn457095(v=vs.111).aspx

Now Recommended

It's probably better to use the answer that EdwardBrey proposed and then DanielWright later elaborated with a code sample.

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

What's the difference between lists enclosed by square brackets and parentheses in Python?

Square brackets are lists while parentheses are tuples.

A list is mutable, meaning you can change its contents:

>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]

while tuples are not:

>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:

>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Note that, as many people have pointed out, you can add tuples together. For example:

>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)

However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:

>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)

Whereas, if you were to construct this same example with a list, y would also be updated:

>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

Set start value for column with autoincrement

In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:

Here the autoincrement will start at 760

Conditional statement in a one line lambda function in python?

The right way to do this is simple:

def rate(T):
    if (T > 200):
        return 200*exp(-T)
    else:
        return 400*exp(-T)

There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.

The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).


From a comment:

Well the function needed to fit in one line, which i didn't think you could do with a named function?

I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:

>>> def foo(x): return x + 1

Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.

Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.

But on the off chance that this really is what you need here: Just use exec instead of eval.

You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:

exec(my_function_string, my_globals, my_locals)

In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.

In earlier 2.x (before 2.6, I think?) you have to do it like this instead:

exec my_function_string in my_globals, my_locals

How can I rollback an UPDATE query in SQL server 2005?

Try

ROLLBACK WORK;

It usually works

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Accessing inventory host variable in Ansible playbook

Thanks a lot this note was very useful for me! Was able to send the variable defined under /group_var/vars in the ansible playbook as indicated below.

tasks:
- name: check service account password expiry
- command:

sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}

Swapping pointers in C (char, int)

You need to understand the different between pass-by-reference and pass-by-value.

Basically, C only support pass-by-value. So you can't reference a variable directly when pass it to a function. If you want to change the variable out a function, which the swap do, you need to use pass-by-reference. To implement pass-by-reference in C, need to use pointer, which can dereference to the value.

The function:

void intSwap(int* a, int* b)

It pass two pointers value to intSwap, and in the function, you swap the values which a/b pointed to, but not the pointer itself. That's why R. Martinho & Dan Fego said it swap two integers, not pointers.

For chars, I think you mean string, are more complicate. String in C is implement as a chars array, which referenced by a char*, a pointer, as the string value. And if you want to pass a char* by pass-by-reference, you need to use the ponter of char*, so you get char**.

Maybe the code below more clearly:

typedef char* str;
void strSwap(str* a, str* b);

The syntax swap(int& a, int& b) is C++, which mean pass-by-reference directly. Maybe some C compiler implement too.

Hope I make it more clearly, not comfuse.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods

Method 1:

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
_x000D_
_x000D_
_x000D_

Method 2:

_x000D_
_x000D_
document.write(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
_x000D_
_x000D_
_x000D_

How do I make an HTTP request in Swift?

Another option is the Alamofire lib that offers Chainable Request / Response methods.

https://github.com/Alamofire/Alamofire

Making a Request

import Alamofire

Alamofire.request(.GET, "http://httpbin.org/get")

Response Handling

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { request, response, data, error in
              print(request)
              print(response)
              print(error)
          }

Simple Java Client/Server Program

If you got your IP address from an external web site (http://whatismyipaddress.com/), you have your external IP address. If your server is on the same local network, you may need an internal IP address instead. Local IP addresses look like 10.X.X.X, 172.X.X.X, or 192.168.X.X.

Try the suggestions on this page to find what your machine thinks its IP address is.

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

MySQL root access from all hosts

Run the following query:

use mysql;
update user set host='%' where host='localhost'

NOTE: Not recommended for production use.

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

Current user in Magento?

Have a look at the helper class: Mage_Customer_Helper_Data

To simply get the customer name, you can write the following code:-

$customerName = Mage::helper('customer')->getCustomerName();

For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-

echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";

From the helper class, you can also get information about customer login url, register url, logout url, etc.

From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.

AngularJS: factory $http.get JSON file

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:

menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) { 
    console.log("success!");
    $scope.appetizers = data.appetizers;
        console.log(data.appetizers);
    });    
});

Remove unused imports in Android Studio

Sorry for the late answer.. For mac users command + option + o Try this.. It is working for me..

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

Make column fixed position in bootstrap

iterating over Ihab's answer, just using position:fixed and bootstraps col-offset you don't need to be specific on the width.

<div class="row">
    <div class="col-lg-3" style="position:fixed">
        Fixed content
    </div>
    <div class="col-lg-9 col-lg-offset-3">
        Normal scrollable content
    </div>
</div>