Programs & Examples On #Gaeunit

How to insert strings containing slashes with sed?

A simplier alternative is using AWK as on this answer:

awk '$0="prefix"$0' file > new_file

Print all key/value pairs in a Java ConcurrentHashMap

I tested your code and works properly. I've added a small demo with another way to print all the data in the map:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (String key : map.keySet()) {
    System.out.println(key + " " + map.get(key));
}

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey().toString();
    Integer value = entry.getValue();
    System.out.println("key, " + key + " value " + value);
}

How to add a progress bar to a shell script?

There are many different answers about this topic, but when calculating percentage for text file operation, using current length / total size way, for example showing percentage of ver_big_file.json progress, and I recommend using awk for this purpose, like below code:

awk '
    function bar(x){s="";i=0;while (i++ < x) s=s "#";return s}
    BEGIN{
        ("ls -l " ARGV[1]) | getline total;
        split(total,array);
        total=array[5];
    }
    {
        cur+=length($0)+1;
        percent=int(cur / total * 100);
        printf "LINE %s:%s %s%%\r", NR, bar(percent*.8), percent 
    }
    END {print}' very_big_file.json | grep "keyword" | ...

This way it's very precise, stream based, but it's only suitable for text files.

How to use icons and symbols from "Font Awesome" on Native Android Application

The FontView library lets you use normal/unicode font characters as icons/graphics in your app. It can load the font via assets or a network location.

The benefit of this library is that:

1 - it takes care of remote resources for you
2 - scales the font size in dynamically sized views
3 - allows the font to easily be styled.

https://github.com/shellum/fontView

Example:

Layout:

<com.finalhack.fontview.FontView
        android:id="@+id/someActionIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />

Java:

fontView.setupFont("fonts/font.ttf", character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);

Get first word of string

This code should get you the first word,

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

 //Now i want to get the first word of every split-ed sting parts:

 for (var i=0;i<str1.length;i++)
 {
     //What to do here to get the first word :(
     var words = str1[i].split(" ");
     console.log(words[0]);
 }

Merge (Concat) Multiple JSONObjects in Java

I used string to concatenate new object to an existing object.


private static void concatJSON() throws IOException, InterruptedException {

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(new File(Main.class.getResource("/file/user.json").toURI())));


    JSONObject jsonObj = (JSONObject) obj; //usernameJsonObj

    String [] values = {"0.9" , Date.from(Calendar.getInstance().toInstant()).toLocaleString()},
            innermost = {"Accomplished", "LatestDate"}, 
            inner = {"Lesson1", "Lesson2", "Lesson3", "Lesson4"};
    String in = "Jayvee Villa";

    JSONObject jo1 = new JSONObject();
    for (int i = 0; i < innermost.length; i++)
        jo1.put(innermost[i], values[i]);

    JSONObject jo2 = new JSONObject();
    for (int i = 0; i < inner.length; i++)
        jo2.put(inner[i], jo1);

    JSONObject jo3 = new JSONObject();
    jo3.put(in, jo2);

    String merger = jsonObj.toString().substring(0, jsonObj.toString().length()-1) + "," +jo3.toString().substring(1);

    System.out.println(merger);
    FileWriter pr = new FileWriter(file);
    pr.write(merger);
    pr.flush();
    pr.close();
}

ArrayList filter

Probably the best way is to use Guava

List<String> list = new ArrayList<String>();
list.add("How are you");
list.add("How you doing");
list.add("Joe");
list.add("Mike");
    
Collection<String> filtered = Collections2.filter(list,
    Predicates.containsPattern("How"));
print(filtered);

prints

How are you
How you doing

In case you want to get the filtered collection as a list, you can use this (also from Guava):

List<String> filteredList = Lists.newArrayList(Collections2.filter(
    list, Predicates.containsPattern("How")));

foreach loop in angularjs

Change the line into this

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value);
 });

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value.Name);
 });

Time part of a DateTime Field in SQL

select cast(getdate() as time(0))

returns for example :- 15:19:43

replace getdate() with the date time you want to extract just time from!

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

How do I generate random integers within a specific range in Java?

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

The integer x is now the random number that has a possible outcome of 5-10.

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

Modular multiplicative inverse function in Python

Sympy, a python module for symbolic mathematics, has a built-in modular inverse function if you don't want to implement your own (or if you're using Sympy already):

from sympy import mod_inverse

mod_inverse(11, 35) # returns 16
mod_inverse(15, 35) # raises ValueError: 'inverse of 15 (mod 35) does not exist'

This doesn't seem to be documented on the Sympy website, but here's the docstring: Sympy mod_inverse docstring on Github

Cannot change version of project facet Dynamic Web Module to 3.0?

Best and simple steps solved this problem for me is 1) Properties -> Project Facets -> Deselect/unmark the check box of Dynamic Web Module -> Apply 2)Now change to the desired version Apply 3)Check the Dynamic web Module check box.. --Now your are done--

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

Thread Safe C# Singleton Pattern

Jeffrey Richter recommends following:



    public sealed class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton instance = null;
    
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                if(instance != null) return instance;
                Monitor.Enter(s_lock);
                Singleton temp = new Singleton();
                Interlocked.Exchange(ref instance, temp);
                Monitor.Exit(s_lock);
                return instance;
            }
        }
    }

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

Oracle query to fetch column names

in oracle you can use

desc users

to display all columns containing in users table

Your project path contains non-ASCII characters android studio

I also encountered this problem, and I have to change the folder name from Chinese to English. Pity that current gradle build tool does not support Unicode names.

How to run a function in jquery

The following should work nicely.

$(function() {

  // Way 1
  function doosomething()
  {
    //Doo something
  }

  // Way 2, equivalent to Way 1
  var doosomething = function() {
    // Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Basically, you are declaring your function in the same scope as your are using it (JavaScript uses Closures to determine scope).

Now, since functions in JavaScript behave like any other object, you can simply assign doosomething as the function to call on click by using .click(doosomething);

Your function will not execute until you call it using doosomething() (doosomething without the () refers to the function but doesn't call it) or another function calls in (in this case, the click handler).

How to center Font Awesome icons horizontally?

If your icons are in an icon stack you can use the following code:

.icon-stack{ margin: auto; display: block; } 

WPF: Create a dialog / prompt

You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin, Height, Width properties set in the XAML, but should be enough to show how to get this done at a basic level.

XAML
Build a Window page like you would normally and add your fields to it, say a Label and TextBox control inside a StackPanel:

<StackPanel Orientation="Horizontal">
    <Label Name="lblUser" Content="User Name:" />
    <TextBox Name="txtUser" />
</StackPanel>

Then create a standard Button for Submission ("OK" or "Submit") and a "Cancel" button if you like:

<StackPanel Orientation="Horizontal">
    <Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
    <Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>

Code-Behind
You'll add the Click event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:

public static string strUserName = String.Empty;

Then, for the event handler functions (right-click the Click function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

Calling It From Another Page
You're thinking, if I close my window with that this.Close() up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/

They had a similar example to this (I cleaned it up a bit) of how to open your Window from another and retrieve the values:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
    {
        MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page

        //ShowDialog means you can't focus the parent window, only the popup
        popup.ShowDialog(); //execution will block here in this method until the popup closes

        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:

public static bool cancelled = false;

And let's include our btnCancel_Click event handler, and make one change to btnSubmit_Click:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{        
    cancelled = true;
    strUserName = String.Empty;
    this.Close();
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        cancelled = false;  // <-- I add this in here, just in case
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

And then we just read that variable in our MainWindow btnOpenPopup_Click event:

private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
    MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page
    //ShowDialog means you can't focus the parent window, only the popup
    popup.ShowDialog(); //execution will block here in this method until the popup closes

    // **Here we find out if we cancelled or not**
    if (popup.cancelled == true)
        return;
    else
    {
        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Long response, but I wanted to show how easy this is using public static variables. No DialogResult, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

How to find the unclosed div tag

Use notepad ++ . you can find them easily

http://notepad-plus-plus.org/download/

Or you can View source from FIREfox - Unclosed divs will be shown in RED

Bootstrap Carousel : Remove auto slide

data-interval="false"

Add this to the corresponding div ...

How can I recover a lost commit in Git?

Another way to get to the deleted commit is with the git fsck command.

git fsck --lost-found

This will output something like at the last line:

dangling commit xyz

We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

git merge xyz

Note:
We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

Finding non-numeric rows in dataframe in pandas?

# Original code
df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5],
                   'b': [0.1, 0.2, 0.3, 0.4, 0.5],
                   'item': ['a', 'b', 'c', 'd', 'e']})
df = df.set_index('item')

Convert to numeric using 'coerce' which fills bad values with 'nan'

a = pd.to_numeric(df.a, errors='coerce')

Use isna to return a boolean index:

idx = a.isna()

Apply that index to the data frame:

df[idx]

output

Returns the row with the bad data in it:

        a    b
item          
d     bad  0.4

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

What is HTML5 ARIA?

I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them

What is ARIA?

If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.

ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.

And see this you tube video for ARIA live.

Extract and delete all .gz in a directory- Linux

for foo in *.gz
do
  tar xf "$foo"
  rm "$foo"
done

Multiple lines of text in UILabel

UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.

Django -- Template tag in {% if %} block

You shouldn't use the double-bracket {{ }} syntax within if or ifequal statements, you can simply access the variable there like you would in normal python:

{% if title == source %}
   ...
{% endif %}

How to write a test which expects an Error to be thrown in Jasmine?

You are using:

expect(fn).toThrow(e)

But if you'll have a look on the function comment (expected is string):

294 /**
295  * Matcher that checks that the expected exception was thrown by the actual.
296  *
297  * @param {String} expected
298  */
299 jasmine.Matchers.prototype.toThrow = function(expected) {

I suppose you should probably write it like this (using lambda - anonymous function):

expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");

This is confirmed in the following example:

expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");

Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):

throw {
   name: "Error",
   message: "Parsing is not possible"
}

java.net.UnknownHostException: Invalid hostname for server: local

I was having the same issue on my mac. I found the issue when I pinged my $HOSTNAME from terminal and it returned ping: cannot resolve myHostName: Unknown host.

To resolve:

  1. Do echo $HOSTNAME on your terminal.
  2. Whatever hostname it shows (lets say myHostName), try to ping it : ping myHostName. If it returns ping: cannot resolve myHostName: Unknown host then add an entry into your /etc/hosts file.
  3. For that edit /etc/hosts file and add following:

    127.0.0.1 myHostName

Hope it helps.

How to set cookies in laravel 5 independently inside controller

You are going right way my friend.Now if you want retrive cookie anywhere in project just put this code $val = Cookie::get('COOKIE_NAME'); That's it! For more information how can this done click here

Checkout one file from Subversion

Using the sparse check out technique, you CAN check out a particular file that is already checked out or exists...with a simple trick:

After checkout of the top level of your repository using the 'this item only' option, in Windows explorer, you MUST first right-click on the file you need to update; choose Repo Browser in context menu; find that file AGAIN in repository browser, and right-click. You should now see the "update item to revision" in context menu.

I'm not sure whether it is an undocumented feature or simply a bug. It took me an extended after-work hours to finally find this trick. I'm using TortoiseSVN 1.6.2.

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

How to override !important?

Okay here is a quick lesson about CSS Importance. I hope that the below helps!

First of all the every part of the styles name as a weighting, so the more elements you have that relate to that style the more important it is. For example

#P1 .Page {height:100px;}

is more important than:

.Page {height:100px;}

So when using important, ideally this should only ever be used, when really really needed. So to overide the decleration, make the style more specific, but also with an override. See below:

td {width:100px !important;}
table tr td .override {width:150px !important;}

I hope this helps!!!

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

How do I determine if a checkbox is checked?

You can use this code, it can return true or false:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  _x000D_
  //add selector of your checkbox_x000D_
_x000D_
  var status=$('#IdSelector')[0].checked;_x000D_
  _x000D_
  console.log(status);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

HTTP Status 404 - The requested resource (/) is not available

If options under Server Locations are grayed out, note the message in the section title: "Server must be published with no modules present". To publish the server, right click the name of the server in the Server window and select "Publish".

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

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

Check if the file exists using VBA

just get rid of those speech marks

Sub test()

Dim thesentence As String

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

This is the one I like:

Option Explicit

Enum IsFileOpenStatus
    ExistsAndClosedOrReadOnly = 0
    ExistsAndOpenSoBlocked = 1
    NotExists = 2
End Enum


Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus

With New FileSystemObject
    If Not .FileExists(FileName) Then
        IsFileReadOnlyOpen = 2  '  NotExists = 2
        Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
    End If
End With

Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
    iFilenum = FreeFile()
    Open FileName For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
On Error GoTo 0

Select Case iErr
    Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
    Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
    Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select

End Function    'IsFileReadOnlyOpen

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

Configure Flask dev server to be visible across the network

Create file .flaskenv in the project root directory.

The parameters in this file are typically:

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000

If you have a virtual environment, activate it and do a pip install python-dotenv .

This package is going to use the .flaskenv file, and declarations inside it will be automatically imported across terminal sessions.

Then you can do flask run

On localhost, how do I pick a free port number?

If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

Add a prefix string to beginning of each line

Using the shell:

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);

  private void SumOFEPFWages(GridView grd)
    {
        Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
        /*Sum of the total Amount of the day*/
        foreach (GridViewRow gvr in grd.Rows)
        {
            Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
            lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
        }

    }

How to copy text from a div to clipboard

Create a element to be appended to the document. Set its value to the string that we want to copy to the clipboard. Append said element to the current HTML document. Use HTMLInputElement.select() to select the contents of the element. Use Document.execCommand('copy') to copy the contents of the to the clipboard. Remove the element from the document

function copyToClipboard(containertext) {
    var el = document.createElement('textarea');
    el.value = containertext;
    el.text = containertext;
    el.setAttribute('id', 'copyText');
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    var coptTextArea = document.getElementById('copyText');
    $('#copyText').text(containertext);
    coptTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    /* Alert the copied text */
    alert("Copied : "+containertext, 1000);
}

PHP passing $_GET in linux command prompt

Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");' 

This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention

the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.

Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file

Two dimensional array in python

When constructing multi-dimensional lists in Python I usually use something similar to ThiefMaster's solution, but rather than appending items to index 0, then appending items to index 1, etc., I always use index -1 which is automatically the index of the last item in the array.

i.e.

arr = []

arr.append([])
arr[-1].append("aa1")
arr[-1].append("aa2")

arr.append([])
arr[-1].append("bb1")
arr[-1].append("bb2")
arr[-1].append("bb3")

will produce the 2D-array (actually a list of lists) you're after.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

You can use these steps to import the key to an existing keystore. The instructions are combined from answers in this thread and other sites. These instructions worked for me (the java keystore):

  1. Run

openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root

(If required put the -chain option. Putting that failed for me). This will ask for the password - you must give the correct password else you will get an error (heading error or padding error etc).

  1. It will ask you to enter a new password - you must enter a password here - enter anything but remember it. (Let us assume you enter Aragorn).
  2. This will create the server.p12 file in the pkcs format.
  3. Now to import it into the *.jks file run:
    keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
    (Very important - do not leave out the deststorepass and the destkeypass parameters.)
  4. It will ask you for the src key store password. Enter Aragorn and hit enter. The certificate and key is now imported into your existing java keystore.

Watching variables in SSIS during debug

I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)

Find the max of 3 numbers in Java with different data types

if you want to do a simple, it will be like this

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

and the output will be something like this

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

References Java™ How To Program (Early Objects), Tenth Edition

Is there an auto increment in sqlite?

One should not specify AUTOINCREMENT keyword near PRIMARY KEY. Example of creating autoincrement primary key and inserting:

$ sqlite3 ex1

CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);

INSERT INTO room(name, home_id) VALUES ('test', 'home id test');

INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');

SELECT * FROM room;

will give:

1|test|home id test
2|test 2|home id test 2

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

How to add url parameter to the current url?

There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to:

topic.php?id=14&like=like

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Using the Jersey client to do a POST operation

If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE. Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.

InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);

FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

How to downgrade Node version

 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
 sudo npm install -g n
 sudo n 10.15
 npm install
 npm audit fix
 npm start

How do I convert a datetime to date?

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

Java Minimum and Maximum values in Array

Here is the working code to find the min and max in the array.I hope you will find it helpful:

 import java.util.Random;
 import java.util.Scanner;
 public class FindMin {
    public static void main(String[] args){
        System.out.println("Main Method Started");
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of the arr");
        int size = in.nextInt();
        System.out.println("Enter the maximum value of the arr");
        int max = in.nextInt();
        int [] arr  = initializeArr(max, size);
        print(arr);
        findMinMax(arr);
        System.out.println("Main Method Ended");
    }
    public static void print(int[] arr){
        for(int val:arr){
            System.out.print(val + " ");
        }
        System.out.println();
    }
    public static int[] initializeArr(int max,int size){
        Random random = new Random();
        int [] arr = new int[size];
        for(int ii=0;ii<arr.length;ii++){
            arr[ii]=random.nextInt(max);
        }
        return arr;
    }
    public static void findMinMax(int[] arr){
        int min=arr[0];
        int max=arr[0];
        for(int ii=0;ii<arr.length;ii++){
            if(arr[ii]<min){
                min=arr[ii];
            }
            else if(arr[ii]>max){
                max=arr[ii];
            }
        }
        System.out.println("The minimum in the arr::"+min);
        System.out.println("The maximum in the arr::"+max);
    }
}

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

How to do Select All(*) in linq to sql

You can use simple linq query as follow to select all records from sql table

var qry = ent.tableName.Select(x => x).ToList();

Create an Array of Arraylists

ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

How to set a default value for an existing column

The correct way to do this is as follows:

  1. Run the command:

    sp_help [table name] 
    
  2. Copy the name of the CONSTRAINT.

  3. Drop the DEFAULT CONSTRAINT:

    ALTER TABLE [table name] DROP [NAME OF CONSTRAINT] 
    
  4. Run the command below:

    ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
    

HTML5 Video tag not working in Safari , iPhone and iPad

What helped in my case was dropping the audio track. It was silent before, but it had to be gone completely.

On ubuntu:

ffmpeg -i input.mp4 -vcodec copy -an output.mp4

And safari/desktop start to play the video

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

Remove char at specific index - python

This is my generic solution for any string s and any index i:

def remove_at(i, s):
    return s[:i] + s[i+1:]

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

Asp Net Web API 2.1 get client IP address

Try to get the Ip using

ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";

JUnit 4 compare Sets

Check this article. One example from there:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  

Finding the length of a Character Array in C

There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;

Allow docker container to connect to a local/host postgres database

In Ubuntu:

First You have to check that is the Docker Database port is Available in your system by following command -

sudo iptables -L -n

Sample OUTPUT:

Chain DOCKER (1 references)
target     prot opt source               destination         
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.2           tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:22

Here 3306 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

Now, You can easily access the Docker Database from your local system by following configuration

  host: 172.17.0.2 
  adapter: mysql
  database: DATABASE_NAME
  port: 3307
  username: DATABASE_USER
  password: DATABASE_PASSWORD
  encoding: utf8

In CentOS:

First You have to check that is the Docker Database port is Available in your firewall by following command -

sudo firewall-cmd --list-all

Sample OUTPUT:

  target: default
  icmp-block-inversion: no
  interfaces: eno79841677
  sources: 
  services: dhcpv6-client ssh
  **ports: 3307/tcp**
  protocols: 
  masquerade: no
  forward-ports: 
  sourceports: 
  icmp-blocks: 
  rich rules:

Here 3307 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo firewall-cmd --zone=public --add-port=3307/tcp

In server, You can add the port permanently

sudo firewall-cmd --permanent --add-port=3307/tcp
sudo firewall-cmd --reload

Now, You can easily access the Docker Database from your local system by the above configuration.

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

Handling NULL values in Hive

Firstly — I don't think column1 is not NULL or column1 <> '' makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> '' (AND instead of OR)?

Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL when you read from them. So, for example, if table1.column1 is of type STRING and table2.column1 is of type INT, then I don't think that table1.column1 IS NOT NULL is enough to guarantee that table2.column1 IS NOT NULL. (I'm not sure about this, though.)

How can I get a web site's favicon?

HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com/favicon.ico");

w.AllowAutoRedirect = true;

HttpWebResponse r = (HttpWebResponse)w.GetResponse();

System.Drawing.Image ico;
using (Stream s = r.GetResponseStream())
{
    ico = System.Drawing.Image.FromStream(s);
}

ico.Save("favicon.ico");

REACT - toggle class onclick

you can add toggle class or toggle state on click

class Test extends Component(){
  state={
  active:false, 
 }
  toggleClass() {
    console.log(this.state.active)
    this.setState=({
     active:true,
   })
  }

    render() {
    <div>
      <div onClick={this.toggleClass.bind(this)}>
        <p>1</p>
      </div>
    </div>
  }

}

Could not autowire field in spring. why?

In spring servlet .xml :

<context:component-scan base-package="net.controller" />

(I assumed that the service impl is in the same package as the service interface "net.service")

I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

How do I check if an index exists on a table field in MySQL?

Try use this:

SELECT TRUE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_SCHEMA = "{DB_NAME}" 
AND TABLE_NAME = "{DB_TABLE}"
AND COLUMN_NAME = "{DB_INDEXED_FIELD}";

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

The DB_PATH was pointing to different database. Change it in database helper class and my code working.

private static String DB_PATH = "/data/data/com.example.abc";

cannot call member function without object

If you want to call them like that, you should declare them static.

AngularJS routing without the hash '#'

The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag For Example:

There are 2 things that need to be done.

  • Configuring $locationProvider

  • Setting our base for relative links

  • $location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.

https://docs.angularjs.org/api/ng/service/$location

$locationProvider and html5Mode

  • We will use the $locationProvider module and set html5Mode to true.
  • We will do this when defining your Angular application and configuring your routes.

    angular.module('noHash', [])
    
    .config(function($routeProvider, $locationProvider) {
    
       $routeProvider
           .when('/', {
               templateUrl : 'partials/home.html',
               controller : mainController
           })
           .when('/about', {
               templateUrl : 'partials/about.html',
               controller : mainController
           })
           .when('/contact', {
               templateUrl : 'partials/contact.html',
               controller : mainController
           });
    
       // use the HTML5 History API
       $locationProvider.html5Mode(true); });
    

What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:

http://diveintohtml5.info/history.html

Setting For Relative Links

  • To link around your application using relative links, you will need to set the <base> in the <head> of your document. This may be in the root index.html file of your Angular app. Find the <base> tag, and set it to the root URL you'd like for your app.

For example: <base href="/">

  • There are plenty of other ways to configure this, and the HTML5 mode set to true should automatically resolve relative links. If your root of your application is different than the url (for instance /my-base, then use that as your base.

Fallback for Older Browsers

  • The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
  • This happens transparently to you and you won’t have to configure anything for it to work. From the Angular $location docs, you can see the fallback method and how it works.

In Conclusion

  • This is a simple way to get pretty URLs and remove the hashtag in your Angular application. Have fun making those super clean and super fast Angular apps!

How do I read / convert an InputStream into a String in Java?

You can use Apache Commons.

In the IOUtils you can find the toString method with three helpful implementations.

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input, String encoding)
            throws IOException {
        return toString(input, Charsets.toCharset(encoding));
}

How do I schedule jobs in Jenkins?

Jenkins uses Cron format on scheduling. You can refer this link for more detailhttps://en.wikipedia.org/wiki/Cron. One more thing, Jenkins provide us a very useful preview. Please take a look on the screenshot. enter image description here

I hope this help. Thanks

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

I ran into this error in a different situation, posting the resolution for those arriving via search: from within Visual Studio, I had copied a file from one project and pasted into another. Turns out that creates a symbolic link, not an actual copy. Thus the project did not find the file in the current working directory as expected. When I made a physical copy instead, in Windows Explorer, suddenly #include "myfile.h" worked.

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

Easiest way to mask characters in HTML(5) text input

Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.

However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown event to block key input before it displays on the screen.

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

Adding background image to div using CSS

Add height & width properties to your .css file.

System.Net.WebException: The remote name could not be resolved:

It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult is generic, however you can determine the exact issue catching HttpRequestException and then inspecting InnerException: if it's a WebException then you can check the WebException.Status property, for example WebExceptionStatus.NameResolutionFailure should indicate a DNS resolution problem.


It may happen, there isn't much you can do.

What I'd suggest to always wrap that (network related) code in a loop with a try/catch block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
    using (var client = new HttpClient()) {
        for (int i=1; i <= NumberOfRetries; ++i) {
            try {
                return await client.GetAsync(url); 
            }
            catch (Exception e) when (i < NumberOfRetries) {
                await Task.Delay(DelayOnRetry);
            }
        }
    }
}

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

Asking the user for input until they give a valid response

Use try-except to handle the error and repeat it again:

while True:
    try:
        age = int(input("Please enter your age: "))
        if age >= 18:
            print("You are able to vote in the United States!")
        else:
            print("You are not able to vote in the United States.")
    except Exception as e:
        print("please enter number")

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

In my case, when I run df -i it shows me that my number of inodes are full and then I have to delete some of the small files or folder. Otherwise it will not allow us to create files or folders once inodes get full.

All you have to do is delete files or folder that has not taken up full space but is responsible for filling inodes.

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

How to properly ignore exceptions

In Python, we handle exceptions similar to other language, but the difference is some syntax difference, for example,

try:
    #Your code in which exception can occur
except <here we can put in a particular exception name>:
    # We can call that exception here also, like ZeroDivisionError()
    # now your code
# We can put in a finally block also
finally:
    # Your code...

Set the text in a span

This is because you have wrong selector. According to your markup, .ui-icon and .ui-icon-circle-triangle-w" should point to the same <span> element. So you should use:

$(".ui-icon.ui-icon-circle-triangle-w").html("<<");

or

$(".ui-datepicker-prev .ui-icon").html("<<");

or

$(".ui-datepicker-prev span").html("<<");

Getting unix timestamp from Date()

getTime() retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.

Apache HttpClient Android (Gradle)

None of the others worked for me. I had to add the following dependency, as explained here

compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'

because I was targeting API 23.

How can I read large text files in Python, line by line, without loading it into memory?

The blaze project has come a long way over the last 6 years. It has a simple API covering a useful subset of pandas features.

dask.dataframe takes care of chunking internally, supports many parallelisable operations and allows you to export slices back to pandas easily for in-memory operations.

import dask.dataframe as dd

df = dd.read_csv('filename.csv')
df.head(10)  # return first 10 rows
df.tail(10)  # return last 10 rows

# iterate rows
for idx, row in df.iterrows():
    ...

# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()

# slice by column
df[df.my_field=='XYZ'].compute()

Git says remote ref does not exist when I delete remote branch

The command git branch -a shows remote branches that exist in your local repository. This may sound a bit confusing but to understand it, you have to understand that there is a difference between a remote branch, and a branch that exists in a remote repository. Remote branches are local branches that map to branches of the remote repository. So the set of remote branches represent the state of the remote repository.

The usual way to update the list of remote branches is to use git fetch. This automatically gets an updated list of branches from the remote and sets up remote branches in the local repository, also fetching any commit objects you may be missing.

However, by default, git fetch does not remove remote branches that no longer have a counterpart branch on the remote. In order to do that, you explicitly need to prune the list of remote branches:

git fetch --prune

This will automatically get rid of remote branches that no longer exist on the remote. Afterwards, git branch -r will show you an updated list of branches that really exist on the remote: And those you can delete using git push.

That being said, in order to use git push --delete, you need to specify the name of the branch on the remote repository; not the name of your remote branch. So to delete the branch test (represented by your remote branch origin/test), you would use git push origin --delete test.

MySQL: Curdate() vs Now()

Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-

NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.

NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;

Change connection string & reload app.config at run time

Here's the method I use:

public void AddOrUpdateAppConnectionStrings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.ConnectionStrings.ConnectionStrings;
        if (settings[key] == null)
        {
            settings.Add(new ConnectionStringSettings(key,value));
        }
        else
        {
            settings[key].ConnectionString = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.ConnectionStrings.SectionInformation.Name);
        Properties.Settings.Default.Reload();
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

MSVCP120d.dll missing

From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).

  • vc8 = Visual Studio 2005
  • vc9 = Visual Studio 2008
  • vc10 = Visual Studio 2010
  • vc11 = Visual Studio 2012
  • vc12 = Visual Studio 2013
  • vc14 = Visual Studio 2015
  • vc15 = Visual Studio 2017
  • vc16 = Visual Studio 2019

The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.

  • MSVCP80.DLL is from Visual Studio 2005
  • MSVCP90.DLL is from Visual Studio 2008
  • MSVCP100.DLL is from Visual Studio 2010
  • MSVCP110.DLL is from Visual Studio 2012
  • MSVCP120.DLL is from Visual Studio 2013
  • MSVCP140.DLL is from Visual Studio 2015, 2017 and 2019

There is binary compatibility between Visual Studio 2015, 2017 and 2019.

Styling multi-line conditions in 'if' statements?

All respondents that also provide multi-conditionals for the if statement is just as ugly as the problem presented. You don't solve this problem by doing the same thing..

Even the PEP 0008 answer is repulsive.

Here is a far more readable approach

condition = random.randint(0, 100) # to demonstrate
anti_conditions = [42, 67, 12]
if condition not in anti_conditions:
    pass

Want me to eat my words? Convince me you need multi-conditionals and I'll literally print this and eat it for your amusement.

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;


    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

calling a function from class in python - different way

disclaimer: this is not a just to the point answer, it's more like a piece of advice, even if the answer can be found on the references

IMHO: object oriented programming in Python sucks quite a lot.

The method dispatching is not very straightforward, you need to know about bound/unbound instance/class (and static!) methods; you can have multiple inheritance and need to deal with legacy and new style classes (yours was old style) and know how the MRO works, properties...

In brief: too complex, with lots of things happening under the hood. Let me even say, it is unpythonic, as there are many different ways to achieve the same things.

My advice: use OOP only when it's really useful. Usually this means writing classes that implement well known protocols and integrate seamlessly with the rest of the system. Do not create lots of classes just for the sake of writing object oriented code.

Take a good read to this pages:

you'll find them quite useful.

If you really want to learn OOP, I'd suggest starting with a more conventional language, like Java. It's not half as fun as Python, but it's more predictable.

jQuery: how to get which button was clicked upon form submission?

You can create input type="hidden" as holder for a button id information.

<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

How to call an element in a numpy array?

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

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

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

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

For example:

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

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

Lightbox to show videos from Youtube and Vimeo?

I've had a LOT of trouble with pretty photo and IE9. I also had issues with fancybox in IE.

For youtube.com, I'm having a lot of luck with CeeBox.

http://catcubed.com/2008/12/23/ceebox-a-thickboxvideobox-mashup/

How do I trim a file extension from a String in Java?

String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

Is this a trick question? :p

I can't think of a faster way atm.

What is a correct MIME type for .docx, .pptx, etc.?

Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

What does "static" mean in C?

Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Look at this for example - A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

#include<stdio.h> 
int fun() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("%d ", fun()); 
  printf("%d ", fun()); 
  return 0; 
}

This will output: 1 2

As 1 stays in the memory as it was declared static

Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.

#include <stdio.h> 
int main() 
{ 
    static int x; 
    int y; 
    printf("%d \n %d", x, y); 
}

This will output : 0 [some_garbage_value]

These are the major ones I found that weren't explained above for a newbie!

Extract hostname name from string

Okay, I know this is an old question, but I made a super-efficient url parser so I thought I'd share it.

As you can see, the structure of the function is very odd, but it's for efficiency. No prototype functions are used, the string doesn't get iterated more than once, and no character is processed more than necessary.

function getDomain(url) {
    var dom = "", v, step = 0;
    for(var i=0,l=url.length; i<l; i++) {
        v = url[i]; if(step == 0) {
            //First, skip 0 to 5 characters ending in ':' (ex: 'https://')
            if(i > 5) { i=-1; step=1; } else if(v == ':') { i+=2; step=1; }
        } else if(step == 1) {
            //Skip 0 or 4 characters 'www.'
            //(Note: Doesn't work with www.com, but that domain isn't claimed anyway.)
            if(v == 'w' && url[i+1] == 'w' && url[i+2] == 'w' && url[i+3] == '.') i+=4;
            dom+=url[i]; step=2;
        } else if(step == 2) {
            //Stop at subpages, queries, and hashes.
            if(v == '/' || v == '?' || v == '#') break; dom += v;
        }
    }
    return dom;
}

Android EditText Max Length

If you want to see a counter label you can use app:counterEnabled and android:maxLength, like:

<android.support.design.widget.TextInputLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:counterEnabled="true">

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="420" />

</android.support.design.widget.TextInputLayout>

DO NOT set app:counterMaxLength on TextInputLayout because it will conflict with android:maxLength resulting into the issue of invisible chars after the text hits the size limit.

How to set UTF-8 encoding for a PHP file

Try this way header('Content-Type: text/plain; charset=utf-8');

Remove URL parameters without refreshing page

a simple way to do this, works on any page, requires HTML 5

// get the string following the ?
var query = window.location.search.substring(1)

// is there anything there ?
if(query.length) {
   // are the new history methods available ?
   if(window.history != undefined && window.history.pushState != undefined) {
        // if pushstate exists, add a new state to the history, this changes the url without reloading the page

        window.history.pushState({}, document.title, window.location.pathname);
   }
}

Rails: FATAL - Peer authentication failed for user (PG::Error)

For permanent solution:

The problem is with your pg_hba. This line:

local   all             postgres                                peer

Should be

local   all             postgres                                md5

Then restart your postgresql server after changing this file.

If you're on Linux, command would be

sudo service postgresql restart

Composer: The requested PHP extension ext-intl * is missing from your system

Just uncomment this line (to find it, simply search this line in editor):

;extension=php_sockets.dll

(Remove semicolon to uncomment)

For me, no need to restart XAMPP (in your case, WAMP). But if didn't work, restart it.

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

Wrapping a react-router Link in an html button

For anyone looking for a solution using React 16.8+ (hooks) and React Router 5:

You can change the route using a button with the following code:

<button onClick={() => props.history.push("path")}>

React Router provides some props to your components, including the push() function on history which works pretty much like the < Link to='path' > element.

You don't need to wrap your components with the Higher Order Component "withRouter" to get access to those props.

How to remove button shadow (android)

I use a custom style

<style name="MyButtonStyle" parent="@style/Widget.AppCompat.Button.Borderless"></style>

Don't forget to add

<item name="android:textAllCaps">false</item>

otherwise the button text will be in UpperCase.

Reliable method to get machine's MAC address in C#

We use WMI to get the mac address of the interface with the lowest metric, e.g. the interface windows will prefer to use, like this:

public static string GetMACAddress()
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
    IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
    string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
    return mac;
}

Or in Silverlight (needs elevated trust):

public static string GetMACAddress()
{
    string mac = null;
    if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
    {
        dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
        dynamic sWbemServices = sWbemLocator.ConnectServer(".");
        sWbemServices.Security_.ImpersonationLevel = 3; //impersonate

        string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
        dynamic results = sWbemServices.ExecQuery(query);

        int mtu = int.MaxValue;
        foreach (dynamic result in results)
        {
            if (result.IPConnectionMetric < mtu)
            {
                mtu = result.IPConnectionMetric;
                mac = result.MACAddress;
            }
        }
    }
    return mac;
}

How to run an EXE file in PowerShell with parameters with spaces and quotes

There are quite a few methods you can use to do it.

There are other methods like using the Call Operator (&), Invoke-Expression cmdlet etc. But they are considered unsafe. Microsoft recommends using Start-Process.

Method 1

A simple example

Start-Process -NoNewWindow -FilePath "C:\wamp64\bin\mysql\mysql5.7.19\bin\mysql" -ArgumentList "-u root","-proot","-h localhost"

In your case

Start-Process -NoNewWindow -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync","-source:dbfullsql=`"Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`"","-dest:dbfullsql=`"Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`"","computername=10.10.10.10","username=administrator","password=adminpass"

In this method you separate each and every parameter in the ArgumentList using commas.

Method 2

Simple Example

Start-Process -NoNewWindow -FilePath "C:\wamp64\bin\mysql\mysql5.7.19\bin\mysql" -ArgumentList "-u root -proot -h localhost"

In your case

Start-Process -NoNewWindow -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync -source:dbfullsql=`"Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`" -dest:dbfullsql=`"Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`",computername=10.10.10.10,username=administrator,password=adminpass"

This method is easier as it allows to type your parameters in one go.

Note that in powershell to represent the quotation mark ( " ) in a string you should insert the grave accent ( ` ) (This is the key above the Tab key in the US keyboard).

-NoNewWindow parameter is used to display the new process in the current console window. By default Windows PowerShell opens a new window.

References : Powershell/Scripting/Start-Process

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Resolved the issue... you need to add the ssh public key to your github account.

  1. Verify that the ssh keys have been setup correctly.
    1. Run ssh-keygen
    2. Enter the password (keep the default path - ~/.ssh/id_rsa)
  2. Add the public key (~/.ssh/id_rsa.pub) to github account
  3. Try git clone. It works!


Initial status (public key not added to git hub account)

foo@bn18-251:~$ rm -rf test
foo@bn18-251:~$ ls
foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git
Cloning into 'test'...
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
foo@bn18-251:~$


Now, add the public key ~/.ssh/id_rsa.pub to the github account (I used cat ~/.ssh/id_rsa.pub)

foo@bn18-251:~$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/foo/.ssh/id_rsa): 
Created directory '/home/foo/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/foo/.ssh/id_rsa.
Your public key has been saved in /home/foo/.ssh/id_rsa.pub.
The key fingerprint is:
xxxxx
The key's randomart image is:
+--[ RSA 2048]----+
xxxxx
+-----------------+
foo@bn18-251:~$ cat ./.ssh/id_rsa.pub 
xxxxx
foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git
Cloning into 'test'...
The authenticity of host 'github.com (207.97.227.239)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts.
Enter passphrase for key '/home/foo/.ssh/id_rsa': 
warning: You appear to have cloned an empty repository.
foo@bn18-251:~$ ls
test
foo@bn18-251:~/test$ git status
# On branch master
#
# Initial commit
#
nothing to commit (create/copy files and use "git add" to track)

UIGestureRecognizer on UIImageView

Swift 2.0 Solution

You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.

4 Steps

1.) Inherit from UIGestureRecognizerDelegate by adding it to your class signature.

class ViewController: UIViewController, UIGestureRecognizerDelegate {...}

2.) Control drag from your image to your viewController to create an IBOutlet:

@IBOutlet weak var tapView: UIImageView!

3.) In your viewDidLoad add the following code:

// create an instance of UITapGestureRecognizer and tell it to run 
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
tapView.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
tapView.addGestureRecognizer(tap)

4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil if you choose).

func handleTap(sender: UITapGestureRecognizer? = nil) {
    // just creating an alert to prove our tap worked!
    let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}

Your final code should look something like this:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var tapView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        tapView.userInteractionEnabled = true
        tapView.addGestureRecognizer(tap)
    }

    func handleTap(sender: UITapGestureRecognizer? = nil) {
        let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
        tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
        self.presentViewController(tapAlert, animated: true, completion: nil)
    }
}

Concatenate two PySpark dataframes

Maybe, you want to concatenate more of two Dataframes. I found a issue which use pandas Dataframe conversion.

Suppose you have 3 spark Dataframe who want to concatenate.

The code is the following:

list_dfs = []
list_dfs_ = []

df = spark.read.json('path_to_your_jsonfile.json',multiLine = True)
df2 = spark.read.json('path_to_your_jsonfile2.json',multiLine = True)
df3 = spark.read.json('path_to_your_jsonfile3.json',multiLine = True)

list_dfs.extend([df,df2,df3])

for df in list_dfs : 

    df = df.select([column for column in df.columns]).toPandas()
    list_dfs_.append(df)

list_dfs.clear()

df_ = sqlContext.createDataFrame(pd.concat(list_dfs_))

How to check version of python modules?

I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no glove solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.

import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
    modules_version = f.read()
  
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}

Retrieve your module's versions through passing the module label key, e.g.:

>>  module_dict["seaborn"]
'0.9.0'

How to return an array from a function?

int* test();

but it would be "more C++" to use vectors:

std::vector< int > test();

EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[] and delete[] operators, but it's the same with malloc/free.

In the first case, you'll write something like:

int* test() {
    return new int[size_needed];
}

but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, although the client can safely deallocate it with a call to delete[].

int* theArray = test();
for (size_t i; i < ???; ++i) { // I don't know what is the array size!
    // ...
}
delete[] theArray; // ok.

A better signature would be this one:

int* test(size_t& arraySize) {
    array_size = 10;
    return new int[array_size];
}

And your client code would now be:

size_t theSize = 0;
int* theArray = test(theSize);
for (size_t i; i < theSize; ++i) { // now I can safely iterate the array
    // ...
}
delete[] theArray; // still ok.

Since this is C++, std::vector<T> is a widely-used solution:

std::vector<int> test() {
    std::vector<int> vector(10);
    return vector;
}

Now you don't have to call delete[], since it will be handled by the object, and you can safely iterate it with:

std::vector<int> v = test();
std::vector<int>::iterator it = v.begin();
for (; it != v.end(); ++it) {
   // do your things
}

which is easier and safer.

How to write a caption under an image?

Figure and Figcaption tags:

<figure>
    <img src='image.jpg' alt='missing' />
    <figcaption>Caption goes here</figcaption>
</figure>

Gotta love HTML5.


See sample

_x000D_
_x000D_
#container {_x000D_
    text-align: center;_x000D_
}_x000D_
a, figure {_x000D_
    display: inline-block;_x000D_
}_x000D_
figcaption {_x000D_
    margin: 10px 0 0 0;_x000D_
    font-variant: small-caps;_x000D_
    font-family: Arial;_x000D_
    font-weight: bold;_x000D_
    color: #bb3333;_x000D_
}_x000D_
figure {_x000D_
    padding: 5px;_x000D_
}_x000D_
img:hover {_x000D_
    transform: scale(1.1);_x000D_
    -ms-transform: scale(1.1);_x000D_
    -webkit-transform: scale(1.1);_x000D_
    -moz-transform: scale(1.1);_x000D_
    -o-transform: scale(1.1);_x000D_
}_x000D_
img {_x000D_
    transition: transform 0.2s;_x000D_
    -webkit-transition: -webkit-transform 0.2s;_x000D_
    -moz-transition: -moz-transform 0.2s;_x000D_
    -o-transition: -o-transform 0.2s;_x000D_
}
_x000D_
<div id="container">_x000D_
    <a href="#">_x000D_
        <figure>_x000D_
            <img src="http://lorempixel.com/100/100/nature/1/" width="100px" height="100px" />_x000D_
            <figcaption>First image</figcaption>_x000D_
        </figure>_x000D_
    </a>_x000D_
    <a href="#">_x000D_
        <figure>_x000D_
             <img src="http://lorempixel.com/100/100/nature/2/" width="100px" height="100px" />_x000D_
            <figcaption>Second image</figcaption>_x000D_
        </figure>_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

How to use relative/absolute paths in css URLs?

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

Convert datetime to Unix timestamp and convert it back in python

Rather than this expression to create a POSIX timestamp from dt,

(dt - datetime(1970,1,1)).total_seconds()

Use this:

int(dt.strftime("%s"))

I get the right answer in your example using the second method.

EDIT: Some followup... After some comments (see below), I was curious about the lack of support or documentation for %s in strftime. Here's what I found:

In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us:

"Other codes may be available on your platform.
 See documentation for the C library strftime function."

So now if we man strftime (on BSD systems such as Mac OS X), you'll find support for %s:

"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."

Anyways, that's why %s works on the systems it does. But there are better solutions to OP's problem (that take timezones into account). See @abarnert's accepted answer here.

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

Insert current date/time using now() in a field using MySQL/PHP

These both work fine for me...

<?php
  $db = mysql_connect('localhost','user','pass');
  mysql_select_db('test_db');

  $stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}','{$last}','NOW())";
  $rslt = mysql_query($stmt);

  $stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}', '{$last}', CURRENT_TIMESTAMP)";
  $rslt = mysql_query($stmt);

?>

Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.

How can I lookup a Java enum from its String value?

You can define your Enum as following code :

public enum Verbosity 
{
   BRIEF, NORMAL, FULL, ACTION_NOT_VALID;
   private int value;

   public int getValue()
   {
     return this.value;
   } 

   public static final Verbosity getVerbosityByValue(int value)
   {
     for(Verbosity verbosity : Verbosity.values())
     {
        if(verbosity.getValue() == value)
            return verbosity ;
     }

     return ACTION_NOT_VALID;
   }

   @Override
   public String toString()
   {
      return ((Integer)this.getValue()).toString();
   }
};

See following link for more clarification

Pass C# ASP.NET array to Javascript array

Prepare an array (in my case it is 2d array):

        // prepare a 2d array in c#
        ArrayList header = new ArrayList { "Task Name", "Hours"};
        ArrayList data1 = new ArrayList {"Work", 2};
        ArrayList data2 = new ArrayList { "Eat", 2 };
        ArrayList data3 = new ArrayList { "Sleep", 2 };
        ArrayList data = new ArrayList {header, data1, data2, data3};
        // convert it in json
        string dataStr = JsonConvert.SerializeObject(data, Formatting.None);
        // store it in viewdata/ viewbag
        ViewBag.Data = new HtmlString(dataStr);   

Parse it in the view.

<script>    
    var data = JSON.parse('@ViewBag.Data');
    console.log(data);
</script>

In your case you can directly use variable name instead of ViewBag.Data.

HttpContext.Current.User.Identity.Name is Empty

I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured

However, the IISExpress.config settings file had:

<windowsAuthentication enabled="false">

The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

If you already have node installed, your path variable is set up and you suddenly start getting this error; try updating to the latest version.

This worked for me going from 6.9.2 to 6.10.

ES6 export all values from object

I just had need to do this for a config file.

var config = {
    x: "CHANGE_ME",
    y: "CHANGE_ME",
    z: "CHANGE_ME"
}

export default config;

You can do it like this

import { default as config } from "./config";

console.log(config.x); // CHANGE_ME

This is using Typescript mind you.

.keyCode vs. .which

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get remote registry value

If you need user's SID and browse remote HKEY_USERS folder, you can follow this script :

<# Replace following domain.name with yours and userAccountName with remote username #>
$userLogin = New-Object System.Security.Principal.NTAccount(“domain.name“,”userAccountName“)
$userSID = $userLogin.Translate([System.Security.Principal.SecurityIdentifier])

<# We will open HKEY_USERS and with accurate user’s SID from remoteComputer #>
$remoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘Users’,”remoteComputer“)

<# We will then retrieve LocalName value from Control Panel / International subkeys #>

$key = $userSID.value+”\Control Panel\International”
$openKey = $remoteRegistry.OpenSubKey($key)

<# We can now retrieve any values #>

$localName = $openKey.GetValue(‘LocaleName’)

Source : http://techsultan.com/how-to-browse-remote-registry-in-powershell/

What are Unwind segues for and how do you use them?

For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.

@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
        if sender.source is ViewControllerB  {
            if let _ = sender.source as? ViewControllerB {
                self.textLabel.text = "Came from B = B->A , B exited"
            }
            
        }

}
  • Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:

enter image description here

  • Unwind Seague Completed -> TextLabel of viewControllerA is Changed.

enter image description here

Initialise numpy array of unknown length

For posterity, I think this is quicker:

a = np.array([np.array(list()) for _ in y])

You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


Responding to comment below:

>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object)], dtype=object)

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

how to define ssh private key for servers fetched by dynamic inventory in files

You can simply define the key to use directly when running the command:

ansible-playbook \
        \ # Super verbose output incl. SSH-Details:
    -vvvv \
        \ # The Server to target: (Keep the trailing comma!)
    -i "000.000.0.000," \
        \ # Define the key to use:
    --private-key=~/.ssh/id_rsa_ansible \
        \ # The `env` var is needed if `python` is not available:
    -e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
        \ # Dry–Run:
    --check \
    deploy.yml

Copy/ Paste:

ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml

Auto insert date and time in form input field?

<input type="date" id="myDate"  />

<script type="text/javascript">
function SetDate()
{
var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;


document.getElementById('myDate').value = today;
}
</script>

<body onload="SetDate();">

found here: http://jsbin.com/oqekar/1/edit?html,js,output

Sort a list by multiple attributes?

There is a operator < between lists e.g.:

[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]

will give

False

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

border-radius not working

you may include bootstrap to your html file and you put it under the style file so if you do that bootstrap file will override the style file briefly like this

     // style file
     <link rel="stylesheet" href="css/style.css" />
     // bootstrap file
     <link rel="stylesheet" href="css/bootstrap.min.css" />

the right way is this

    // bootstrap file
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    // style file
    <link rel="stylesheet" href="css/style.css" />

How to script FTP upload and download?

Create a command file with your commands

ie: commands.txt

open www.domainhere.com
user useridhere 
passwordhere
put test.txt
bye

Then run the FTP client from the command line: ftp -s:commands.txt

Note: This will work for the Windows FTP client.

Edit: Should have had a linebreak after the user name before the password.

How can I color Python logging output?

There are tons of responses. But none is talking about decorators. So here's mine.

Because it is a lot more simple.

There's no need to import anything, nor to write any subclass:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import logging


NO_COLOR = "\33[m"
RED, GREEN, ORANGE, BLUE, PURPLE, LBLUE, GREY = \
    map("\33[%dm".__mod__, range(31, 38))

logging.basicConfig(format="%(message)s", level=logging.DEBUG)
logger = logging.getLogger(__name__)

# the decorator to apply on the logger methods info, warn, ...
def add_color(logger_method, color):
  def wrapper(message, *args, **kwargs):
    return logger_method(
      # the coloring is applied here.
      color+message+NO_COLOR,
      *args, **kwargs
    )
  return wrapper

for level, color in zip((
  "info", "warn", "error", "debug"), (
  GREEN, ORANGE, RED, BLUE
)):
  setattr(logger, level, add_color(getattr(logger, level), color))

# this is displayed in red.
logger.error("Launching %s." % __file__)

This set the errors in red, debug messages in blue, and so on. Like asked in the question.

We could even adapt the wrapper to take a color argument to dynamicaly set the message's color using logger.debug("message", color=GREY)

EDIT: So here's the adapted decorator to set colors at runtime:

def add_color(logger_method, _color):
  def wrapper(message, *args, **kwargs):
    color = kwargs.pop("color", _color)
    if isinstance(color, int):
      color = "\33[%dm" % color
    return logger_method(
      # the coloring is applied here.
      color+message+NO_COLOR,
      *args, **kwargs
    )
  return wrapper

# blah blah, apply the decorator...

# this is displayed in red.
logger.error("Launching %s." % __file__)
# this is displayed in blue
logger.error("Launching %s." % __file__, color=34)
# and this, in grey
logger.error("Launching %s." % __file__, color=GREY)

What is the standard Python docstring format?

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

And last a basic example to give an idea how it looks like:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

I got this error too. I figured out that my version of PHP didn't have openssl compiled in, so simply adding the extension directive to php.ini wasn't enough. I don't know how you have to solve this in your particular case, but for me, I use macports, and the command was just:

sudo port install php5-openssl

Checking for empty queryset in Django

I disagree with the predicate

if not orgs:

It should be

if not orgs.count():

I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.

How to embed YouTube videos in PHP?

Use a regex to extract the "video id" after watch?v=

Store the video id in a variable, let's call this variable vid

Get the embed code from a random video, remove the video id from the embed code and replace it with the vid you got.

I don't know how to deal with regex in php, but it shouldn't be too hard

Here's example code in python:

>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>

The regular expression v\=([\-\w]+) captures a (sub)string of characters and dashes that comes after v=

Get column index from label in a data frame

I wanted to see all the indices for the colnames because I needed to do a complicated column rearrangement, so I printed the colnames as a dataframe. The rownames are the indices.

as.data.frame(colnames(df))

1 A
2 B
3 C

How to convert WebResponse.GetResponseStream return into a string?

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

Send Outlook Email Via Python?

For a solution that uses outlook see TheoretiCAL's answer below.

Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.

Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.

Android WebView Cookie Problem

I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").

Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

The following resolved the problem for me:

  1. Go to Control Panel -> Network and Internet -> change adapter settings
    Right click on VirtualBox Host-Only Network and select properties The following options must be ticked

    • client for microsoft networks
    • virtualBox bridged network driver
    • qos pocket scheduler
    • file and printer sharing for microsoft network

    If see another program select and uninstall it.

  2. In VirtualBox go to File -> Preferences -> Network
    Double click on VirtualBox Host-Only ethernet adapter
    Edit like this:
    IPV4 address: 192.168.56.1 mask: 255.255.255.0
    DHCP: address 192.168.56.100 mask: 255.255.255.0
    low bounds: 192.168.56.101 high bound: 192.168.56.254
    Restart or log off your windows and start genymotion
    If that didn't solve your problem in VirtualBox go to File -> Preferences -> Network and delete Host-Only ethernet adapter.

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Alternative to iFrames with HTML5

Basically there are 4 ways to embed HTML into a web page:

  • <iframe> An iframe's content lives entirely in a separate context than your page. While that's mostly a great feature and it's the most compatible among browser versions, it creates additional challenges (shrink wrapping the size of the frame to its content is tough, insanely frustrating to script into/out of, nearly impossible to style).
  • AJAX. As the solutions shown here prove, you can use the XMLHttpRequest object to retrieve data and inject it to your page. It is not ideal because it depends on scripting techniques, thus making the execution slower and more complex, among other drawbacks.
  • Hacks. Few mentioned in this question and not very reliable.
  • HTML5 Web Components. HTML Imports, part of the Web Components, allows to bundle HTML documents in other HTML documents. That includes HTML, CSS, JavaScript or anything else an .html file can contain. This makes it a great solution with many interesting use cases: split an app into bundled components that you can distribute as building blocks, better manage dependencies to avoid redundancy, code organization, etc. Here is a trivial example:

    <!-- Resources on other origins must be CORS-enabled. -->
    <link rel="import" href="http://example.com/elements.html">
    

Native compatibility is still an issue, but you can use a polyfill to make it work in evergreen browsers Today.

You can learn more here and here.

Android - set TextView TextStyle programmatically?

Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

CSS Pseudo-classes with inline styles

Rather than needing inline you could use Internal CSS

<a href="http://www.google.com" style="hover:text-decoration:none;">Google</a>

You could have:

<a href="http://www.google.com" id="gLink">Google</a>
<style>
  #gLink:hover {
     text-decoration: none;
  }
</style>

Get source JARs from Maven repository

I have also used the eclipse plugin to get the project into the eclipse workspace. Since I've worked on a different project I saw that it is possible to work with eclipse but without the maven-eclipse-plugin. That makes it easier to use with different environments and enables the easy use of maven over eclipse. And that without changing the pom.xml-file.

So, I recommend the approach of Gabriel Ramirez.

Composer: how can I install another dependency without updating old ones?

In my case, I had a repo with:

  • requirements A,B,C,D in .json
  • but only A,B,C in the .lock

In the meantime, A,B,C had newer versions with respect when the lock was generated.

For some reason, I deleted the "vendors" and wanted to do a composer install and failed with the message:

Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD but composer insisted to update more things, so .lock had too changes seen my my git tool.

The solution I used was:

  1. Delete all the vendors dir.
  2. Temporarily remove the requirement VendorD/LibraryD from the .json.
  3. run composer install.
  4. Then delete the file .json and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).
  5. Then run Seldaek's solution composer update vendorD/libraryD

It did install the library, but in addition, git diff showed me that in the .lock only the new things were added without editing the other ones.

(Thnx Seldaek for the pointer ;) )

jQuery If DIV Doesn't Have Class "x"

You can also use the addClass and removeClass methods to toggle between items such as tabs.

e.g.

if($(element).hasClass("selected"))
   $(element).removeClass("selected");

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

OSX Sierra, Python 2.7, Graphviz 2.38

Using pip install graphviz and conda install graphviz BOTH resolves the problem.

pip only gets path problem same as yours and conda only gets import error.

How to retrieve field names from temporary table (SQL Server 2008)

To use information_schema and not collide with other sessions:

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
    object_name(
        object_id('tempdb..#test'),
        (select database_id from sys.databases where name = 'tempdb'))

failed to push some refs to [email protected]

It is probably due to an Outdated yarn.lock file

Just run the following commands

yarn install
git add yarn.lock
git commit -m "Updated Yarn lockfile"
git push heroku master

What __init__ and self do in Python?

Yep, you are right, these are oop constructs.

__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

The __init__ method gets called when memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the __init__ method like this:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

Visual Studio 2015 is very slow

I found that the Windows Defender Antimalware is causing huge delays. Go to Update & Security -> Settings -> Windows Defender. Open the Defender and in the Settings selection, choose Exclusions and add the "devenv.exe' process. It worked for me