Programs & Examples On #Boost gil

The Boost Generic Image Library (Boost.GIL) is a C++ library that abstracts image representations from algorithms and allows writing code that can work on a variety of images with performance similar to hand-writing for a specific image type.

How to get Tensorflow tensor dimensions (shape) as int values?

Another way to solve this is like this:

tensor_shape[0].value

This will return the int value of the Dimension object.

Java ArrayList copy

Yes l1 and l2 will point to the same reference, same object.

If you want to create a new ArrayList based on the other ArrayList you do this:

List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");

The result will be l1 will still have 2 elements and l2 will have 3 elements.

How to compile C++ under Ubuntu Linux?

Use g++. And make sure you have the relevant libraries installed.

How to change UINavigationBar background color from the AppDelegate

In Swift 4.2 and Xcode 10.1

You can change your navigation bar colour from your AppDelegate directly to your entire project.

In didFinishLaunchingWithOptions launchOptions: write below to lines of code

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)

Here

tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)

barTintColor is for navigation bar background colour

If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()

//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white

enter image description here

Apache VirtualHost 403 Forbidden

Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error. You would also see a log message of the form "client denied by server configuration". The feature is requiring a user identity to access a directory. It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive

Require all denied

This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:

Require all granted

as in

<Directory "your directory here">
   Order allow,deny
   Allow from all
   # New directive needed in Apache 2.4.3: 
   Require all granted
</Directory>

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

How to display HTML tags as plain text

The native JavaScript approach -

('<strong>Look just ...</strong>').replace(/</g, '&lt;').replace(/>/g, '&gt;');

Enjoy!

select2 - hiding the search box

//Disable a search on particular selector
$(".my_selector").select2({
    placeholder: "ÁREAS(todas)",
    tags: true,
    width:'100%',
    containerCssClass: "area_disable_search_input" // I add new class 
});

//readonly prop to selector class
$(".area_disable_search_input input").prop("readonly", true);

Empty set literal?

Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ? = frozenset() (? is U+03D5) and use it instead.

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

  1. Go to Setting/Apps/ Search for your app and uninstall...
  2. open command prompt and "adb uninstall "

It´s worked for me

How to get a value of an element by name instead of ID

//name directly given
<input type="text" name="MeetingDateFrom">
var meetingDateFrom = $("input[name=MeetingDateFrom]").val();

//Handle name array
<select multiple="multiple" name="Roles[]"></select>
 var selectedValues = $('select[name="Roles[]"] option:selected').map(function() {
    arr.push(this.value);
  });

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

Get first word of string

I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()


To answer the question directly:

let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");

for (var i = 0; i < codeLines.length; i++) {
  const first = codeLines[i].split(' ').shift()
  firstWords.push(first)
}

Skip to next iteration in loop vba

Just do nothing once the criteria is met, otherwise do the processing you require and the For loop will go to the next item.

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return = 0 And Level = 0 Then
        'Do nothing
    Else
        'Do something
    End If
Next i

Or change the clause so it only processes if the conditions are met:

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return <> 0 Or Level <> 0 Then
        'Do something
    End If
Next i

How do I execute external program within C code in linux with arguments?

For a simple way, use system():

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system() will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256).

The manpage for wait() (in section 2, man 2 wait on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED and WEXITSTATUS.

Alternatively, if you need to read foo's standard output, use popen(3), which returns a file pointer (FILE *); interacting with the command's standard input/output is then the same as reading from or writing to a file.

Mysql - delete from multiple tables with one query

usually, i would expect this as a 'cascading delete' enforced in a trigger, you would only need to delete the main record, then all the depepndent records would be deleted by the trigger logic.

this logic would be similar to what you have written.

Load local HTML file in a C# WebBrowser

Update on @ghostJago answer above

for me it worked as the following lines in VS2017

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

RegEx - Match Numbers of Variable Length

What regex engine are you using? Most of them will support the following expression:

\{\d+:\d+\}

The \d is actually shorthand for [0-9], but the important part is the addition of + which means "one or more".

How To fix white screen on app Start up?

Put this in a custom style and it solves all the problems. Using the hacky translucent fix will make your task bar and nav bar translucent and make the splashscreen or main screen look like spaghetti.

<item name="android:windowDisablePreview">true</item>

Object Library Not Registered When Adding Windows Common Controls 6.0

I have been having the same problem. VB6 Win7 64 bit and have come across a very simple solution, so I figured it would be a good idea to share it here in case it helps anyone else.

First I have tried the following with no success:

  • unregistered and re-registering MSCOMCTL, MSCOMCTL2 and the barcode active X controls in every directory I could think of trying (VB98, system 32, sysWOW64, project folder.)

  • Deleting working folder and getting everything again. (through source safe)

  • Copying the OCX files from a machine with no problems and registering those.

  • Installing service pack 6

  • Installing MZ tools - it was worth a try

  • Installing the distributable version of the project.

  • Manually editing the vbp file (after making it writeable) to amend/remove the references and generally fiddling.

  • Un-Installing VB6 and re-Installing (this I thought was a last resort) The problem was occurring on a new project and not just existing ones.

NONE of the above worked but the following did

Open VB6
New project
>Project
    >Components
        Tick the following:
            Microsoft flexigrid control 6.0 (sp6)
            Microsoft MAPI controls 6.0
            Microsoft Masked Edit Control 6.0 (sp3)
            Microsoft Tabbed Dialog Control 6.0 (sp6)
        >Apply

After this I could still not tick the Barcode Active X or the windows common contols 6.0 and windows common controls 2 6.0, but when I clicked apply, the message changed from unregistered, to that it was already in the project.

>exit the components dialog and then load project. 

This time it worked. Tried the components dialog again and the missing three were now ticked. Everything seems fine now.

Constructor in an Interface?

Here´s an example using this Technic. In this specifik example the code is making a call to Firebase using a mock MyCompletionListener that is an interface masked as an abstract class, an interface with a constructor

private interface Listener {
    void onComplete(databaseError, databaseReference);
}

public abstract class MyCompletionListener implements Listener{
    String id;
    String name;
    public MyCompletionListener(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

private void removeUserPresenceOnCurrentItem() {
    mFirebase.removeValue(child("some_key"), new MyCompletionListener(UUID.randomUUID().toString(), "removeUserPresenceOnCurrentItem") {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

        }
    });
    }
}

@Override
public void removeValue(DatabaseReference ref, final MyCompletionListener var1) {
    CompletionListener cListener = new CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (var1 != null){
                        System.out.println("Im back and my id is: " var1.is + " and my name is: " var1.name);
                        var1.onComplete(databaseError, databaseReference);
                    }
                }
            };
    ref.removeValue(cListener);
}

Type List vs type ArrayList in Java

I would say that 1 is preferred, unless

  • you are depending on the implementation of optional behavior* in ArrayList, in that case explicitly using ArrayList is more clear
  • You will be using the ArrayList in a method call which requires ArrayList, possibly for optional behavior or performance characteristics

My guess is that in 99% of the cases you can get by with List, which is preferred.

  • for instance removeAll, or add(null)

How to print the current time in a Batch-File?

You can use the command time /t for the time and date /t for the date, here is an example:

@echo off
time /t >%tmp%\time.tmp
date /t >%tmp%\date.tmp
set ttime=<%tmp%\time.tmp
set tdate=<%tmp%\date.tmp
del /f /q %tmp%\time.tmp
del /f /q %tmp%\date.tmp
echo Time: %ttime%
echo Date: %tdate%
pause >nul

You can also use the built in variables %time% and %date%, here is another example:

@echo off
echo Time: %time:~0,5%
echo Date: %date%
pause >nul

Difference between SelectedItem, SelectedValue and SelectedValuePath

Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.

To be more specific if you literally want to retrieve Text of Selected Item then you can write:

ListBox1.SelectedItem.Text;

Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.

Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use

ListBox1.SelectedValue

Source

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

Jasmine JavaScript Testing - toBe vs toEqual

toEqual() compares values if Primitive or contents if Objects. toBe() compares references.

Following code / suite should be self explanatory :

describe('Understanding toBe vs toEqual', () => {
  let obj1, obj2, obj3;

  beforeEach(() => {
    obj1 = {
      a: 1,
      b: 'some string',
      c: true
    };

    obj2 = {
      a: 1,
      b: 'some string',
      c: true
    };

    obj3 = obj1;
  });

  afterEach(() => {
    obj1 = null;
    obj2 = null;
    obj3 = null;
  });

  it('Obj1 === Obj2', () => {
    expect(obj1).toEqual(obj2);
  });

  it('Obj1 === Obj3', () => {
    expect(obj1).toEqual(obj3);
  });

  it('Obj1 !=> Obj2', () => {
    expect(obj1).not.toBe(obj2);
  });

  it('Obj1 ==> Obj3', () => {
    expect(obj1).toBe(obj3);
  });
});

cURL equivalent in Node.js?

Here is a standard lib (http) async / await solution.

const http = require("http");

const fetch = async (url) => {
  return new Promise((resolve, reject) => {
    http
      .get(url, (resp) => {
        let data = "";
        resp.on("data", (chunk) => {
          data += chunk;
        });
        resp.on("end", () => {
          resolve(data);
        });
      })
      .on("error", (err) => {
        reject(err);
      });
  });
};

Usage:

await fetch("http://example.com");

TypeError: sequence item 0: expected string, int found

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Checking if a folder exists (and creating folders) in Qt, C++

If you need an empty folder you can loop until you get an empty folder

    QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    while(QDir(folder).exists())
    {
         folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    QDir().mkdir(folder);

This case you will get a folder name with a number .

Waiting until the task finishes

Use DispatchGroups to achieve this. You can either get notified when the group's enter() and leave() calls are balanced:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    DispatchQueue.main.async {
        a = 1
        group.leave()
    }

    // does not wait. But the code in notify() gets run 
    // after enter() and leave() calls are balanced

    group.notify(queue: .main) {
        print(a)
    }
}

or you can wait:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    // avoid deadlocks by not using .main queue here
    DispatchQueue.global(attributes: .qosDefault).async {
        a = 1
        group.leave()
    }

    // wait ...
    group.wait()

    print(a) // you could also `return a` here
}

Note: group.wait() blocks the current queue (probably the main queue in your case), so you have to dispatch.async on another queue (like in the above sample code) to avoid a deadlock.

How to sort a dataframe by multiple column(s)

For the sake of completeness: you can also use the sortByCol() function from the BBmisc package:

library(BBmisc)
sortByCol(dd, c("z", "b"), asc = c(FALSE, TRUE))
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1

Performance comparison:

library(microbenchmark)
microbenchmark(sortByCol(dd, c("z", "b"), asc = c(FALSE, TRUE)), times = 100000)
median 202.878

library(plyr)
microbenchmark(arrange(dd,desc(z),b),times=100000)
median 148.758

microbenchmark(dd[with(dd, order(-z, b)), ], times = 100000)
median 115.872

Selenium C# WebDriver: Wait until element is present

WebDriverWait won't take effect.

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end

This would immediately throw an exception once the page was "interactive". I don't know why, but the timeout acts as if it does not exist.

Perhaps SeleniumExtras.WaitHelpers works, but I didn't try. It's official, but it was split out into another NuGet package. You can refer to C# Selenium 'ExpectedConditions is obsolete'.

I use FindElements and check Count == 0. If true, use await Task.Delay. It's really not quite efficient.

Failed loading english.pickle with nltk.data.load

The main reason why you see that error is nltk couldn't find punkt package. Due to the size of nltk suite, all available packages are not downloaded by default when one installs it.

You can download punkt package like this.

import nltk
nltk.download('punkt')

from nltk import word_tokenize,sent_tokenize

If you do not pass any argument to the download function, it downloads all packages i.e chunkers, grammars, misc, sentiment, taggers, corpora, help, models, stemmers, tokenizers.

nltk.download()

The above function saves packages to a specific directory. You can find that directory location from comments here. https://github.com/nltk/nltk/blob/67ad86524d42a3a86b1f5983868fd2990b59f1ba/nltk/downloader.py#L1051

How do I line up 3 divs on the same row?

Why don't try to use bootstrap's solutions. They are perfect if you don't want to meddle with tables and floats.

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <!--- This line is just linking the bootstrap thingie in the file. The real thing starts below -->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

No meddling with complex CSS, and the best thing is that you can edit the width of the columns by changing the number. You can find more examples at https://getbootstrap.com/docs/4.0/layout/grid/

How to add an image to the "drawable" folder in Android Studio?

My way of exporting/importing image assets. I use Sketch design.

Step 1. Sketch: export using Android preset

Sketch

Step 2. Finder: Go to the export folder > Cmd+C Finder

Step 3. Finder: Go to your project's /res folder > Cmd+V > Apply to all > Merge Finder

OK, the images are in your project now.

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

c++ parse int from string

Some handy quick functions (if you're not using Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Example:

int i = FromString<int>(s);
std::string str = ToString(i);

Works for any streamable types (floats etc). You'll need to #include <sstream> and possibly also #include <string>.

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

How do I import the javax.servlet API in my Eclipse project?

You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar

@BalusC,

I would prefer to use the exact classes that my application is going to use rather than one provided by Eclipse (when I am feeling like a paranoid developer).

Another solution would be to use Eclipse "Configure Build Path" > Libraries > Add External Jars, and add servlet api of whatever Container one chooses to use.

And follow @kaustav datta's solution when using ant to build - have a property like tomcat.home or weblogic.home. However it introduces another constraint that the developer must install Weblogic on his/her local machine if weblogic is being used ! Any other cleaner solution?

How to check if type of a variable is string?

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

returns True

type(a) in [str, unicode]

returns True

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

how to have two headings on the same line in html

Display property 'inline-block' will place both headers next to each other. You can run this code snippet to see it

_x000D_
_x000D_
<h1 style="display: inline-block" >Text 1</h1>
<h1 style="display: inline-block" >Text 2</h1>
_x000D_
_x000D_
_x000D_

Push JSON Objects to array in localStorage

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Running multiple commands in one line in shell

Why not cp to location 1, then mv to location 2. This takes care of "removing" the original.

And no, it's not the correct syntax. | is used to "pipe" output from one program and turn it into input for the next program. What you want is ;, which seperates multiple commands.

cp file1 file2 ; cp file1 file3 ; rm file1

If you require that the individual commands MUST succeed before the next can be started, then you'd use && instead:

cp file1 file2 && cp file1 file3 && rm file1

That way, if either of the cp commands fails, the rm will not run.

Saving image from PHP URL

I wasn't able to get any of the other solutions to work, but I was able to use wget:

$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';

exec("cd $tempDir && wget --quiet $imageUrl");

if (!file_exists("$tempDir/image.jpg")) {
    throw new Exception('Failed while trying to download image');
}

if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
    throw new Exception('Failed while trying to move image file from temp dir to final dir');
}

MySQL Error: #1142 - SELECT command denied to user

This error happened on my server when I imported a view with an invalid definer.

Removing the faulty view fixed the error.

The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Here's a list of things that are worth checking:

Is Suhosin installed?

ini_set

  • The format is important ini_set('memory_limit', '512'); // DIDN'T WORK ini_set('memory_limit', '512MB'); // DIDN'T WORK ini_set('memory_limit', '512M'); // OK - 512MB ini_set('memory_limit', 512000000); // OK - 512MB

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.

http://php.net/manual/en/ini.core.php#ini.memory-limit

  • Has php_admin_value been used in .htaccess or virtualhost files?

Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.

http://php.net/manual/en/configuration.changes.php

Calculate rolling / moving average in C++

You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.

How can I properly use a PDO object for a parameterized SELECT query

if you are using inline coding in single page and not using oops than go with this full example, it will sure help

//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw); 

//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";

//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);

//view the entire array (for testing)
print_r($result);

//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

How to remove an element slowly with jQuery?

You mean like

$target.hide('slow')

?

What is the difference between null and System.DBNull.Value?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.

DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.

How do I remove a specific element from a JSONArray?

Try this code

ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 
int len = jsonArray.length();
if (jsonArray != null) { 
   for (int i=0;i<len;i++){ 
    list.add(jsonArray.get(i).toString());
   } 
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);

Edit: Using ArrayList will add "\" to the key and values. So, use JSONArray itself

JSONArray list = new JSONArray();     
JSONArray jsonArray = new JSONArray(jsonstring); 
int len = jsonArray.length();
if (jsonArray != null) { 
   for (int i=0;i<len;i++)
   { 
       //Excluding the item at position
        if (i != position) 
        {
            list.put(jsonArray.get(i));
        }
   } 
}

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

Convert JsonObject to String

You can try Gson convertor, to get the exact conversion like json.stringify

val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)

Add element to a list In Scala

Use import scala.collection.mutable.MutableList or similar if you really need mutation.

import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)

C# Convert a Base64 -> byte[]

I've written an extension method for this purpose:

public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
    string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
    return Convert.FromBase64String(base64String);
}

Call it like this:

byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();

I hope it helps someone.

ElasticSearch - Return Unique Values

if you want to get the first document for each language field unique value, you can do this:

{
 "query": {
    "match_all": {
    }
  },
  "collapse": {
    "field": "language.keyword",
    "inner_hits": {
    "name": "latest",
      "size": 1
    }
  }
}

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

The only thing that solved it for me was to put the connection details in config/database.php instead of the .env file. Hope this helps

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

How can I iterate through a string and also know the index (current position)?

For strings, you can use string.c_str() which will return you a const char*, which can be treated as an array, example:

const char* strdata = str.c_str();

for (int i = 0; i < str.length(); ++i)
    cout << i << strdata[i];

You are trying to add a non-nullable field 'new_field' to userprofile without a default

You can use method from Django Doc from this page https://docs.djangoproject.com/en/1.8/ref/models/fields/#default

Create default and use it

def contact_default():
   return {"email": "[email protected]"}

contact_info = JSONField("ContactInfo", default=contact_default)

Why is super.super.method(); not allowed in Java?

It would seem to be possible to at least get the class of the superclass's superclass, though not necessarily the instance of it, using reflection; if this might be useful, please consider the Javadoc at http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getSuperclass()

Eclipse comment/uncomment shortcut?

Source -> Remove Block Comment

link

enter image description here

How to link to a named anchor in Multimarkdown?

I tested Github Flavored Markdown for a while and can summarize with four rules:

  1. punctuation marks will be dropped
  2. leading white spaces will be dropped
  3. upper case will be converted to lower
  4. spaces between letters will be converted to -

For example, if your section is named this:

## 1.1 Hello World

Create a link to it this way:

[Link](#11-hello-world)

What is the use of ByteBuffer in Java?

The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:

  • Absolute and relative get and put methods that read and write single bytes;

  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;

  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;

  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;

  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and

  • Methods for compacting, duplicating, and slicing a byte buffer.

Example code : Putting Bytes into a buffer.

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put(int, byte).
    // This method does not affect the position.
    bbuf.put(0, (byte)0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put(byte)
    bbuf.put((byte)0xFF);

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

Why emulator is very slow in Android Studio?

For those who enabled HAXM and the emulator still works slow here is what you should do:

  1. If Avast antivirus is running on your computer, it is most likely the culprit.

as per HAXM Release_Notes.txt (Version 7.5.2):

  • On Windows, Avast Antivirus may interfere with HAXM and cause Android Emulator or QEMU to run very slowly. A workaround is to uncheck "Use nested virtualization where available" in Avast Settings > Troubleshooting.

So open your Avast dashboard > Menu > Settings > Troubleshooting and disable "Enable hardware-assisted virtualization"

enter image description here

  1. Give a higher priority to your emulator's process in the Task Manager:

    Locate your emulator's process in the Task Manager > Details tab:

    Right-click on it and Set Priority -> Above normal enter image description here

Sorry that the screenshot is not in English but you got the point, right? That helped me significantly! I hope it will help you as well.

Also, one thing as per the Release Notes:

  • On Windows 8, 8.1 and 10, it is recommended to disable Hyper-V from Windows Features in order for the HAXM driver to properly function.

In my case, I didn't have any "Hyper-V" feature on my Windows 8.1 but you probably should try it, just in case. To locate and disable that feature see this article: https://support.bluestacks.com/hc/en-us/articles/115004254383-How-do-I-disable-Hyper-V-on-Windows-

How to list files in a directory in a C program?

Below code will only print files within directory and exclude directories within given directory while traversing.

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    char path[1000]="/home/joy/Downloads";
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Condition to check regular file.
            if(dir->d_type==DT_REG){
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("%s\n",full_path);
            }
        }
        closedir(d);
    }
    return(0);     
}

JSON Stringify changes time of date because of UTC

I'm a little late but you can always overwrite the toJson function in case of a Date using Prototype like so:

Date.prototype.toJSON = function(){
    return Util.getDateTimeString(this);
};

In my case, Util.getDateTimeString(this) return a string like this: "2017-01-19T00:00:00Z"

Mythical man month 10 lines per developer day - how close on large projects?

Without actually checking my copy of "The Mythical Man-Month" (everybody reading this should really have a copy readily available), there was a chapter in which Brooks looked at productivity by lines written. The interesting point, to him, was not the actual number of lines written per day, but the fact that it seemed to be roughly the same in assembler and in PL/I (I think that was the higher-level language used).

Brooks wasn't about to throw out some sort of arbitrary figure of productivity, but he was working from data on real projects, and for all I can remember they might have been 12 lines/day on the average.

He did point out that productivity could be expected to vary. He said that compilers were three times as hard as application programs, and operating systems three times as hard as compilers. (He seems to have liked using multipliers of three to separate categories.)

I don't know if he appreciated then the individual differences between programmer productivity (although in an order-of-magnitude argument he did postulate a factor of seven difference), but as we know superior productivity isn't just a matter of writing more code, but also writing the right code to do the job.

There's also the question of the environment. Brooks speculated a bit about what would make developers faster or slower. Like lots of people, he questioned whether the current fads (interactive debugging using time-sharing systems) were any better than the old ways (careful preplanning for a two-hour shot using the whole machine).

Given that, I would disregard any actual productivity number he came up with as useless; the continuing value of the book is in the principles and more general lessons that people persist in not learning. (Hey, if everybody had learned them, the book would be of historical interest only, much like all of Freud's arguments that there is something like a subconscious mind.)

plot.new has not been called yet

In my case, I was trying to call plot(x, y) and lines(x, predict(yx.lm), col="red") in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

There's no magical solution of displaying something outside an overflow hidden container.

A similar effect can be achieved by having an absolute positioned div that matches the size of its parent by positioning it inside your current relative container (the div you don't wish to clip should be outside this div):

#1 .mask {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 1;
  overflow: hidden;
}

Take in mind that if you only have to clip content on the x axis (which appears to be your case, as you only have set the div's width), you can use overflow-x: hidden.

SQL QUERY replace NULL value in a row with a value from the previous known value

Here's a MySQL solution:

UPDATE mytable
SET number = (@n := COALESCE(number, @n))
ORDER BY date;

This is concise, but won't necessary work in other brands of RDBMS. For other brands, there might be a brand-specific solution that is more relevant. That's why it's important to tell us the brand you're using.

It's nice to be vendor-independent, as @Pax commented, but failing that, it's also nice to use your chosen brand of database to its fullest advantage.


Explanation of the above query:

@n is a MySQL user variable. It starts out NULL, and is assigned a value on each row as the UPDATE runs through rows. Where number is non-NULL, @n is assigned the value of number. Where number is NULL, the COALESCE() defaults to the previous value of @n. In either case, this becomes the new value of the number column and the UPDATE proceeds to the next row. The @n variable retains its value from row to row, so subsequent rows get values that come from the prior row(s). The order of the UPDATE is predictable, because of MySQL's special use of ORDER BY with UPDATE (this is not standard SQL).

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

Image UriSource and Data Binding

This article by Atul Gupta has sample code that covers several scenarios:

  1. Regular resource image binding to Source property in XAML
  2. Binding resource image, but from code behind
  3. Binding resource image in code behind by using Application.GetResourceStream
  4. Loading image from file path via memory stream (same is applicable when loading blog image data from database)
  5. Loading image from file path, but by using binding to a file path Property
  6. Binding image data to a user control which internally has image control via dependency property
  7. Same as point 5, but also ensuring that the file doesn't get's locked on hard-disk

How do you get the magnitude of a vector in Numpy?

If you are worried at all about speed, you should instead use:

mag = np.sqrt(x.dot(x))

Here are some benchmarks:

>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372

EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop

In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True

Opacity CSS not working in IE8

Apparently alpha transparency only works on block level elements in IE 8. Set display: block.

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

Swift apply .uppercaseString to only the first letter of a string

If you want to capitalised each word of string you can use this extension

Swift 4 Xcode 9.2

extension String {
    var wordUppercased: String {
        var aryOfWord = self.split(separator: " ")
        aryOfWord =  aryOfWord.map({String($0.first!).uppercased() + $0.dropFirst()})
        return aryOfWord.joined(separator: " ")
    }
}

Used

print("simple text example".wordUppercased) //output:: "Simple Text Example"

Hide particular div onload and then show div after click

At first if you want to hide div element with id = "abc" on load and then toggle between hide and show using a button with id = "btn" then,

$(document).ready(function() {
 $("#abc").hide(); 
  $("#btn").click(function() {
     $("#abc").toggle();
  });
});

CSS animation delay in repeating

I had a similar problem and used

@-webkit-keyframes pan {
   0%, 10%       { -webkit-transform: translate3d( 0%, 0px, 0px); }
   90%, 100%     { -webkit-transform: translate3d(-50%, 0px, 0px); }
}

Bit irritating that you have to fake your duration to account for 'delays' at either end.

How to use bluetooth to connect two iPhone?

You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.

For more information, you can also look at the responses to these questions:

Disable Chrome strict MIME type checking

The server should respond with the correct MIME Type for JSONP application/javascript and your request should tell jQuery you are loading JSONP dataType: 'jsonp'

Please see this answer for further details ! You can also have a look a this one as it explains why loading .js file with text/plain won't work.

MySQL Insert query doesn't work with WHERE clause

INSERT INTO Users(weight, desiredWeight )
SELECT '$userWeight', '$userDesiredWeight'  
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

Removing all script tags from html with JS Regular Expression

Try this:

var text = text.replace(/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/g, "")

Using Jquery Ajax to retrieve data from Mysql


You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

Why doesn't git recognize that my file has been changed, therefore git add not working

I had the same issue. And the files that I needed to be committed were never declared in the .gitignore file as well.

In my case adding the files forcefully using the -f flag elevated to staging and fixed the issue.

git add -f <path to file>

Manifest Merger failed with multiple errors in Android Studio

Remove <activity android:name=".MainActivity"/> from your mainfest file. As you have already defined it as:

 <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

So, Manifest file showing ambiguity.

How to access Anaconda command prompt in Windows 10 (64-bit)

I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.

performSelector may cause a leak because its selector is unknown

@c-road provides the right link with problem description here. Below you can see my example, when performSelector causes a memory leak.

@interface Dummy : NSObject <NSCopying>
@end

@implementation Dummy

- (id)copyWithZone:(NSZone *)zone {
  return [[Dummy alloc] init];
}

- (id)clone {
  return [[Dummy alloc] init];
}

@end

void CopyDummy(Dummy *dummy) {
  __unused Dummy *dummyClone = [dummy copy];
}

void CloneDummy(Dummy *dummy) {
  __unused Dummy *dummyClone = [dummy clone];
}

void CopyDummyWithLeak(Dummy *dummy, SEL copySelector) {
  __unused Dummy *dummyClone = [dummy performSelector:copySelector];
}

void CloneDummyWithoutLeak(Dummy *dummy, SEL cloneSelector) {
  __unused Dummy *dummyClone = [dummy performSelector:cloneSelector];
}

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    Dummy *dummy = [[Dummy alloc] init];
    for (;;) { @autoreleasepool {
      //CopyDummy(dummy);
      //CloneDummy(dummy);
      //CloneDummyWithoutLeak(dummy, @selector(clone));
      CopyDummyWithLeak(dummy, @selector(copy));
      [NSThread sleepForTimeInterval:1];
    }} 
  }
  return 0;
}

The only method, which causes memory leak in my example is CopyDummyWithLeak. The reason is that ARC doesn't know, that copySelector returns retained object.

If you'll run Memory Leak Tool you can see the following picture: enter image description here ...and there are no memory leaks in any other case: enter image description here

Create excel ranges using column numbers in vba?

Range.EntireColumn

Yes! You can use Range.EntireColumn MSDN

dim column : column = 4

dim column_range : set column_range = Sheets(1).Cells(column).EntireColumn

Range("ColumnName:ColumnName")

If you were after a specific column, you could create a hard coded column range with the syntax e.g. Range("D:D").

However, I'd use entire column as it provides more flexibility to change that column at a later time.

Worksheet.Columns

Worksheet.Columns provides Range access to a column within a worksheet. MSDN

If you would like access to the first column of the first sheet. You would call the Columns function on the worksheet.

dim column_range: set column_range = Sheets(1).Columns(1)

The Columns property is also available on any Range MSDN

EntireRow can also be useful if you have a range for a single cell but would like to reach other cells on the row, akin to a LOOKUP

dim id : id = 12345


dim found : set found = Range("A:A").Find(id)

if not found is Nothing then
    'Get the fourth cell from the match
    MsgBox found.EntireRow.Cells(4)
end if

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Pandas DataFrame Groupby two columns and get counts

Followed by @Andy's answer, you can do following to solve your second question:

In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]: 
      0
col2   
A     3
B     2
C     1
D     3

Hadoop cluster setup - java.net.ConnectException: Connection refused

Hi Edit your conf/core-site.xml and change localhost to 0.0.0.0. Use the conf below. That should work.

<configuration>
  <property>
 <name>fs.default.name</name>
 <value>hdfs://0.0.0.0:9000</value>
</property>

Using Linq to get the last N elements of a collection?

If you don't mind dipping into Rx as part of the monad, you can use TakeLast:

IEnumerable<int> source = Enumerable.Range(1, 10000);

IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();

Ways to implement data versioning in MongoDB

Another option is to use mongoose-history plugin.

let mongoose = require('mongoose');
let mongooseHistory = require('mongoose-history');
let Schema = mongoose.Schema;

let MySchema = Post = new Schema({
    title: String,
    status: Boolean
});

MySchema.plugin(mongooseHistory);
// The plugin will automatically create a new collection with the schema name + "_history".
// In this case, collection with name "my_schema_history" will be created.

C# Connecting Through Proxy

Automatic proxy detection is a process by which a Web proxy server is identified by the system and used to send requests on behalf of the client. This feature is also known as Web Proxy Auto-Discovery (WPAD). When automatic proxy detection is enabled, the system attempts to locate a proxy configuration script that is responsible for returning the set of proxies that can be used for the request.

http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx

How do I get the max ID with Linq to Entity?

Note that none of these answers will work if the key is a varchar since it is tempting to use MAX in a varchar column that is filled with "ints".

In a database if a column e.g. "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.

So in your local database everything will work fine since while developing you will never get above 100 test records, then, at some moment during production you get a weird support ticket. Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....

(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...)

So use:

Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control.

EditorFor: This control is bit smart. It renders HTML markup based on the datatype of the property. E.g. suppose there is a boolean property in model. To render this property in the view as a checkbox either we can use CheckBoxFor or EditorFor. Both will be generate the same markup.

What is the advantage of using EditorFor?

As we know, depending on the datatype of the property it generates the html markup. So suppose tomorrow if we change the datatype of property in the model, no need to change anything in the view. EditorFor control will change the html markup automatically.

How to permanently remove few commits from remote branch

Just note to use the last_working_commit_id, when reverting a non-working commit

git reset --hard <last_working_commit_id>

So we must not reset to the commit_id that we don't want.

Then sure, we must push to remote branch:

git push --force

Convenient C++ struct initialisation

Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC.

#include <iostream>
#include <filesystem>

struct hello_world {
    const char* hello;
    const char* world;
};

int main () 
{
    hello_world hw = {
        .hello = "hello, ",
        .world = "world!"
    };
    
    std::cout << hw.hello << hw.world << std::endl;
    return 0;
}

GCC Demo MSVC Demo

Update 20201

As @Code Doggo noted, anyone who is using Visual Studio 2019 will need to set /std:c++latest  for the "C++ Language Standard" field contained under Configuration Properties -> C/C++ -> Language.

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

Factorial using Recursion in Java

What happens is that the recursive call itself results in further recursive behaviour. If you were to write it out you get:

 fact(4)
 fact(3) * 4;
 (fact(2) * 3) * 4;
 ((fact(1) * 2) * 3) * 4;
 ((1 * 2) * 3) * 4;

What is the difference between a var and val definition in Scala?

"val means immutable and var means mutable."

To paraphrase, "val means value and var means variable".

A distinction that happens to be extremely important in computing (because those two concepts define the very essence of what programming is all about), and that OO has managed to blur almost completely, because in OO, the only axiom is that "everything is an object". And that as a consequence, lots of programmers these days tend not to understand/appreciate/recognize, because they have been brainwashed into "thinking the OO way" exclusively. Often leading to variable/mutable objects being used like everywhere, when value/immutable objects might/would often have been better.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Modify a Column's Type in sqlite3

SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.

See also:

Error: Execution failed for task ':app:clean'. Unable to delete file

simple solution :

in android or any jetbrains products when you click to you will find 'invalidate cache and restart ' click on it and all the problems will be solved

fatal: Not a valid object name: 'master'

Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.

Python xml ElementTree from a string source?

If you're using xml.etree.ElementTree.parse to parse from a file, then you can use xml.etree.ElementTree.fromstring to parse from text.

See xml.etree.ElementTree

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

Adding close button in div to close the box

You can use this jsFiddle

And HTML:

<div id="previewBox">
    <button id="closeButton">Close</button>
<a class="fragment" href="google.com">
    <div>
    <img src ="http://placehold.it/116x116" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
    </p>
</div>
</a>
</div>

With JS (jquery required):

$(document).ready(function() {
    $('#closeButton').on('click', function(e) { 
        $('#previewBox').remove(); 
    });
});

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

EOFException - how to handle?

Put your code inside the try catch block: i.e :

try{
  if(in.available()!=0){
    // ------
  }
}catch(EOFException eof){
  //
}catch(Exception e){
  //
}
}

dll missing in JDBC

In my case after spending many days on this issues a gentleman help on this issue below is the solution and it worked for me. Issue: While trying to connect SqlServer DB with Service account authentication using spring boot it throws below exception.

com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:ab942951-31f6-44bf-90aa-7ac4cec2e206 at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2392) ~[mssql-jdbc-6.1.0.jre8.jar!/:na] Caused by: java.lang.UnsatisfiedLinkError: sqljdbc_auth (Not found in java.library.path) at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:1462) ~[na:2.9 (04-02-2020)] Solution: Use JTDS driver with the following steps

  1. Use JTDS driver insteadof sqlserver driver.

    ----------------- Dedicated Pick Update properties PROD using JTDS ----------------

    datasource.dedicatedpicup.url=jdbc:jtds:sqlserver://YourSqlServer:PortNo/DatabaseName;instance=InstanceName;domain=DomainName
    datasource.dedicatedpicup.jdbcUrl=${datasource.dedicatedpicup.url}
    datasource.dedicatedpicup.username=$da-XYZ
    datasource.dedicatedpicup.password=ENC(XYZ)
    datasource.dedicatedpicup.driver-class-name=net.sourceforge.jtds.jdbc.Driver
    
  1. Remove Hikari in configuration properties.

    #datasource.dedicatedpicup.hikari.connection-timeout=60000 #datasource.dedicatedpicup.hikari.maximum-pool-size=5

  2. Add sqljdbc4 dependency.

    com.microsoft.sqlserver sqljdbc4 4.0
  3. Add Tomcatjdbc dependency.

    org.apache.tomcat tomcat-jdbc
  4. Exclude HikariCP from spring-boot-starter-jdbc dependency.

    org.springframework.boot spring-boot-starter-jdbc com.zaxxer HikariCP

ADB - Android - Getting the name of the current activity

I prefer parsing results of dumpsys window windows over dumpsys activity

adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'

Keyguard or Recent tasks list used to not show up as Activities but you were able to see them with mCurrentFocus. I have explained why in this answer.

MySQL Select Date Equal to Today

You can use the CONCAT with CURDATE() to the entire time of the day and then filter by using the BETWEEN in WHERE condition:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))

npm install error - unable to get local issuer certificate

Try

npm config set strict-ssl false

This is a alternative shared in this url https://github.com/nodejs/node/issues/3742

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Html.Partial: returns MvcHtmlString and slow

Html.RenderPartial: directly render/write on output stream and returns void and it's very fast in comparison to Html.Partial

How to connect to MySQL Database?

you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.

Or you can run below command in Package Manager Console

PM> Install-Package MySql.Data

NUGET Mysql.Data

android: how to change layout on button click?

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.

javax.persistence.NoResultException: No entity found for query

When you don't know whether there are any results, use getResultList().

List<User> foundUsers = (List<User>) query.getResultList();
        if (foundUsers == null || foundUsers.isEmpty()) {
            return false;
        }
User foundUser = foundUsers.get(0);

SQLite3 database or disk is full / the database disk image is malformed

I use the following script for repairing malformed sqlite files:

#!/bin/bash

cat <( sqlite3 "$1" .dump | grep "^ROLLBACK" -v ) <( echo "COMMIT;" ) | sqlite3 "fix_$1"

Most of the time when a sqlite database is malformed it is still possible to make a dump. This dump is basically a lot of SQL statements that rebuild the database.

Some rows might be missing from the dump (probably becasue they are corrupted). If this is the case the INSERT statements of the missing rows will be replaced with some comments and the script will end with a ROLLBACK TRANSACTION.

So what we do here is we make the dump (malformed rows are excluded) and we replace the ROLLBACK with a COMMIT so that the entire dump script will be committed in stead of rolled back.

This method saved my life a couple of 100 times already \o/

Generating HTML email body in C#

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

fatal: does not appear to be a git repository

I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.

  • git pull origin feature-branch-name
  • git push

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

Spring-boot default profile for integration tests

You could put an application.properties file in your test/resources folder. There you set

spring.profiles.active=test

This is kind of a default test profile while running tests.

Referencing system.management.automation.dll in Visual Studio

A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

bash: shortest way to get n-th column of output

Because you seem to be unfamiliar with scripts, here is an example.

#!/bin/sh
# usage: svn st | x 2 | xargs rm
col=$1
shift
awk -v col="$col" '{print $col}' "${@--}"

If you save this in ~/bin/x and make sure ~/bin is in your PATH (now that is something you can and should put in your .bashrc) you have the shortest possible command for generally extracting column n; x n.

The script should do proper error checking and bail if invoked with a non-numeric argument or the incorrect number of arguments, etc; but expanding on this bare-bones essential version will be in unit 102.

Maybe you will want to extend the script to allow a different column delimiter. Awk by default parses input into fields on whitespace; to use a different delimiter, use -F ':' where : is the new delimiter. Implementing this as an option to the script makes it slightly longer, so I'm leaving that as an exercise for the reader.


Usage

Given a file file:

1 2 3
4 5 6

You can either pass it via stdin (using a useless cat merely as a placeholder for something more useful);

$ cat file | sh script.sh 2
2
5

Or provide it as an argument to the script:

$ sh script.sh 2 file
2
5

Here, sh script.sh is assuming that the script is saved as script.sh in the current directory; if you save it with a more useful name somewhere in your PATH and mark it executable, as in the instructions above, obviously use the useful name instead (and no sh).

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In case someone makes the same silly mistake I did...

I was getting this error because in renaming my source file, I accidentally removed the. from the filename and so the compiler treated the file as a plain text file and not as source to compile.

so I meant to rename the file to MyProtocol.swift but accidently named it MyProtocolswift

It's a simple mistake, but it was not readily obvious that this is what was going on.

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

In my case, I had replaced math library files from a previous Game Engine Graphics course with GLM. The problem was that I didn't add them to the project within Visual Studio's Solution Explorer (even though they were in the project repository).

How to create a responsive image that also scales up in Bootstrap 3

If setting a fixed width on the image is not an option, here's an alternative solution.

Having a parent div with display: table & table-layout: fixed. Then setting the image to display: table-cell and max-width to 100%. That way the image will fit to the width of its parent.

Example:

<style>
    .wrapper { float: left; clear: left; display: table; table-layout: fixed; }
    img.img-responsive { display: table-cell; max-width: 100%; }
</style>
<div class="wrapper col-md-3">
    <img class="img-responsive" src="https://www.google.co.uk/images/srpr/logo11w.png"/>
</div>

Fiddle: http://jsfiddle.net/5y62c4af/

Extracting extension from filename in Python

def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

Apache won't run in xampp

Take a look at this site:

http://www.lukebrowning.com/blog/nt-kernel-system-using-port-80/

In my case, it was the SQL Server Reporting Service, but others have seen IIS or the Web Deployment Agent Service.

Open a cmd window and run services.msc, find the service, and stop it. Then try to start Apache. If it works, disable the other service.

Hashing with SHA1 Algorithm in C#

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

Field 'id' doesn't have a default value?

Since mysql 5.6, there is a new default that makes sure you are explicitly inserting every field that doesn't have a default value set in the table definition.

to disable and test this: see this answer here: mysql error 1364 Field doesn't have a default values

I would recommend you test without it, then reenable it and make sure all your tables have default values for fields you are not explicitly passing in every INSERT query.

If a third party mysql viewer is giving this error, you are probably limited to the fix in that link.

System.Net.WebException: The operation has timed out

I remember I had the same problem a while back using WCF due the quantity of the data I was passing. I remember I changed timeouts everywhere but the problem persisted. What I finally did was open the connection as stream request, I needed to change the client and the server side, but it work that way. Since it was a stream connection, the server kept reading until the stream ended.

How to empty a redis database?

You have two options:

  • FLUSHDB - clears currently active database
  • FLUSHALL - clears all the existing databases

Align a div to center

floating divs to center "works" with the combination of display:inline-block and text-align:center.

Try changing width of the outer div by resizing the window of this jsfiddle

<div class="outer">
    <div class="block">one</div>
    <div class="block">two</div>
    <div class="block">three</div>
    <div class="block">four</div>
    <div class="block">five</div>
</div>

and the css:

.outer {
    text-align:center;
    width: 50%;
    background-color:lightgray;
}

.block {
    width: 50px;
    height: 50px;
    border: 1px solid lime;
    display: inline-block;
    margin: .2rem;
    background-color: white;
}

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

How should I log while using multiprocessing in Python?

For whoever might need this, I wrote a decorator for multiprocessing_logging package that adds the current process name to logs, so it becomes clear who logs what.

It also runs install_mp_handler() so it becomes unuseful to run it before creating a pool.

This allows me to see which worker creates which logs messages.

Here's the blueprint with an example:

import sys
import logging
from functools import wraps
import multiprocessing
import multiprocessing_logging

# Setup basic console logger as 'logger'
logger = logging.getLogger()
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter(u'%(asctime)s :: %(levelname)s :: %(message)s'))
logger.setLevel(logging.DEBUG)
logger.addHandler(console_handler)


# Create a decorator for functions that are called via multiprocessing pools
def logs_mp_process_names(fn):
    class MultiProcessLogFilter(logging.Filter):
        def filter(self, record):
            try:
                process_name = multiprocessing.current_process().name
            except BaseException:
                process_name = __name__
            record.msg = f'{process_name} :: {record.msg}'
            return True

    multiprocessing_logging.install_mp_handler()
    f = MultiProcessLogFilter()

    # Wraps is needed here so apply / apply_async know the function name
    @wraps(fn)
    def wrapper(*args, **kwargs):
        logger.removeFilter(f)
        logger.addFilter(f)
        return fn(*args, **kwargs)

    return wrapper


# Create a test function and decorate it
@logs_mp_process_names
def test(argument):
    logger.info(f'test function called via: {argument}')


# You can also redefine undecored functions
def undecorated_function():
    logger.info('I am not decorated')


@logs_mp_process_names
def redecorated(*args, **kwargs):
    return undecorated_function(*args, **kwargs)


# Enjoy
if __name__ == '__main__':
    with multiprocessing.Pool() as mp_pool:
        # Also works with apply_async
        mp_pool.apply(test, ('mp pool',))
        mp_pool.apply(redecorated)
        logger.info('some main logs')
        test('main program')

Eclipse: The declared package does not match the expected package

The only thing that worked for me is deleting the project and then importing it again. Works like a charm :)

Unsupported method: BaseConfig.getApplicationIdSuffix()

First, open your application module build.gradle file.

Check the classpath according to your project dependency. If not change the version of this classpath.

from:

classpath 'com.android.tools.build:gradle:1.0.0'

To:

classpath 'com.android.tools.build:gradle:2.3.2'

or higher version according to your gradle of android studio.

If its still problem, then change buildToolsVersion:

From:

buildToolsVersion '21.0.0'

To:

buildToolsVersion '25.0.0'

then hit 'Try again' and gradle will automatically sync. This will solve it.

Is it possible to use a div as content for Twitter's Popover

Building on jävi's answer, this can be done without IDs or additional button attributes like this:

http://jsfiddle.net/isherwood/E5Ly5/

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My first popover content goes here.</div>

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My second popover content goes here.</div>

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My third popover content goes here.</div>

$('.popper').popover({
    container: 'body',
    html: true,
    content: function () {
        return $(this).next('.popper-content').html();
    }
});

How to detect if a string contains special characters?

Assuming SQL Server:

e.g. if you class special characters as anything NOT alphanumeric:

DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'

IF (@MyString LIKE '%[^a-zA-Z0-9]%')
    PRINT 'Contains "special" characters'
ELSE
    PRINT 'Does not contain "special" characters'

Just add to other characters you don't class as special, inside the square brackets

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

Close application and launch home screen on Android

It is not recommended, but you can still use this. Better go with this solution in case you need to quit the app.

According to me, the best solution is to finish every activity in your app like below.

Step 1. Maintain a static variable in mainactivity. Say,

public static boolean isQuit = false;

Step 2. On click event of an button, set this variable to true.

mainactivity.isQuit = true;
finish();

Step 3. And in every activity of your application, have the onrestart method as below.

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    if(mainactivity.isQuit)
        finish();
}

Count cells that contain any text

COUNTIF function will only count cells that contain numbers in your specified range.

COUNTA(range) will count all values in the list of arguments. Text entries and numbers are counted, even when they contain an empty string of length 0.

Example: Function in A7 =COUNTA(A1:A6)

Range:

A1 a

A2 b

A3 banana

A4 42

A5

A6

A7 4 -> result

Google spreadsheet function list contains a list of all available functions for future reference https://support.google.com/drive/table/25273?hl=en.

Get day of week using NSDate

The simple answer (swift 3):

Calendar.current.component(.weekday, from: Date())

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Windows 7, 8 & 10

This is dead easy since Windows 7. In File Explorer, right click anywhere and create a new file. Type the new filename as .something. (notice the appended period) and press enter twice, job done.

Demonstrating how to create a file with no name in File Explorer.

So instead of being prompted with

You must type a file name.

You will instead be prompted with

If you change a file name extension, the file might become unusable.

Note: If you're having issues then please ensure you have "file name extensions" visible, you can activate this under the "View" menu in File Explorer. Also, this method works for folders too.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

If your arrays aren't too big or you don't have too many of them, you might be able to get away with forcing the left hand side of == to be a string:

myRows = df[str(df['Unnamed: 5']) == 'Peter'].index.tolist()

But this is ~1.5 times slower if df['Unnamed: 5'] is a string, 25-30 times slower if df['Unnamed: 5'] is a small numpy array (length = 10), and 150-160 times slower if it's a numpy array with length 100 (times averaged over 500 trials).

a = linspace(0, 5, 10)
b = linspace(0, 50, 100)
n = 500
string1 = 'Peter'
string2 = 'blargh'
times_a = zeros(n)
times_str_a = zeros(n)
times_s = zeros(n)
times_str_s = zeros(n)
times_b = zeros(n)
times_str_b = zeros(n)
for i in range(n):
    t0 = time.time()
    tmp1 = a == string1
    t1 = time.time()
    tmp2 = str(a) == string1
    t2 = time.time()
    tmp3 = string2 == string1
    t3 = time.time()
    tmp4 = str(string2) == string1
    t4 = time.time()
    tmp5 = b == string1
    t5 = time.time()
    tmp6 = str(b) == string1
    t6 = time.time()
    times_a[i] = t1 - t0
    times_str_a[i] = t2 - t1
    times_s[i] = t3 - t2
    times_str_s[i] = t4 - t3
    times_b[i] = t5 - t4
    times_str_b[i] = t6 - t5
print('Small array:')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_a), mean(times_str_a)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_a)/mean(times_a)))

print('\nBig array')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_b), mean(times_str_b)))
print(mean(times_str_b)/mean(times_b))

print('\nString')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_s), mean(times_str_s)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_s)/mean(times_s)))

Result:

Small array:
Time to compare without str conversion: 6.58464431763e-06 s. With str conversion: 0.000173756599426 s
Ratio of time with/without string conversion: 26.3881526541

Big array
Time to compare without str conversion: 5.44309616089e-06 s. With str conversion: 0.000870866775513 s
159.99474375821288

String
Time to compare without str conversion: 5.89370727539e-07 s. With str conversion: 8.30173492432e-07 s
Ratio of time with/without string conversion: 1.40857605178

How to download the latest artifact from Artifactory repository?

Using shell/unix tools

  1. curl 'http://$artiserver/artifactory/api/storage/$repokey/$path/$version/?lastModified'

The above command responds with a JSON with two elements - "uri" and "lastModified"

  1. Fetching the link in the uri returns another JSON which has the "downloadUri" of the artifact.

  2. Fetch the link in the "downloadUri" and you have the latest artefact.

Using Jenkins Artifactory plugin

(Requires Pro) to resolve and download latest artifact, if Jenkins Artifactory plugin was used to publish to artifactory in another job:

  1. Select Generic Artifactory Integration
  2. Use Resolved Artifacts as ${repokey}:**/${component}*.jar;status=${STATUS}@${PUBLISH_BUILDJOB}#LATEST=>${targetDir}

Styling twitter bootstrap buttons

I know this is an older thread, but just to add another perspective. I'd assert that using overrides is really a bit of a code smell and will quickly get out of hand on larger projects. Today you're overriding Buttons, tomorrow Modals, the next day it Dropdowns, etc., etc.

I'd advise to try possibly commenting out the include for buttons.less and either define my own, or, find another Buttons library that's more suitable to my project. Shameless plug: here's an example of how easy it is to mix our Buttons library with TB: Using Buttons with Twitter Bootstrap. In practice, again, you'd likely want to remove the buttons.less include altogether to improve performance but this shows how you can make things look a bit less "generic". I haven't done this exercise yet myself but I'd imagine you could start by simply commenting out lines like:

https://github.com/twbs/bootstrap/blob/master/less/bootstrap.less#L17

And then recompiling using `lessc using one of your own buttons modules. That way you get the battle tested core of TB but can still customize things without resorting to major overrides. There's absolutely no reason not to use only parts of a library like Bootstrap. Of course the same applies to the Sass version of TB

Create or write/append in text file

Although there are many ways to do this. But if you want to do it in an easy way and want to format text before writing it to log file. You can create a helper function for this.

if (!function_exists('logIt')) {
    function logIt($logMe)
    {
        $logFilePath = storage_path('logs/cron.log.'.date('Y-m-d').'.log');
        $cronLogFile = fopen($logFilePath, "a");
        fwrite($cronLogFile, date('Y-m-d H:i:s'). ' : ' .$logMe. PHP_EOL);
        fclose($cronLogFile);
    }
}

Invalid date in safari

convert string to Date fromat (you have to know server timezone)

new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()  

where +08:00 = timeZone from server

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I was hitting this error in one Spring Boot app, but not in another. Finally, I found the Spring Boot version in the one not working was 2.0.0.RELEASE and the one that was working was 2.0.1.RELEASE. That led to a difference in the MySQL Connector -- 5.1.45 vs. 5.1.46. I updated the Spring Boot version for the app that was throwing this error at startup and now it works.

How to merge 2 JSON objects from 2 files using jq?

Since 1.4 this is now possible with the * operator. When given two objects, it will merge them recursively. For example,

jq -s '.[0] * .[1]' file1 file2

Important: Note the -s (--slurp) flag, which puts files in the same array.

Would get you:

{
  "value1": 200,
  "timestamp": 1382461861,
  "value": {
    "aaa": {
      "value1": "v1",
      "value2": "v2",
      "value3": "v3",
      "value4": 4
    },
    "bbb": {
      "value1": "v1",
      "value2": "v2",
      "value3": "v3"
    },
    "ccc": {
      "value1": "v1",
      "value2": "v2"
    },
    "ddd": {
      "value3": "v3",
      "value4": 4
    }
  },
  "status": 200
}

If you also want to get rid of the other keys (like your expected result), one way to do it is this:

jq -s '.[0] * .[1] | {value: .value}' file1 file2

Or the presumably somewhat more efficient (because it doesn't merge any other values):

jq -s '.[0].value * .[1].value | {value: .}' file1 file2

Redirecting Output from within Batch file

The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.

@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt

A better way - easier to write, and faster because the file is opened and positioned only once.

@echo off
>output.txt (
  command1
  command2
  ...
  commandN
)

Another good and fast way that only opens and positions the file once

@echo off
call :sub >output.txt
exit /b

:sub
command1
command2
...
commandN

Edit 2020-04-17

Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the & notation to reference the already opened files.

call :sub 9>File1.txt 8>File2.txt
exit /b

:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b

I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.

3>File1.txt ( 4>File2.txt call :sub)
exit /b

:sub
etc.

What's the difference between JPA and Hibernate?

JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

Bootstrap alert in a fixed floating div at the top of page

The simplest approach would be to use any of these class utilities that Bootstrap provides:

<div class="position-fixed">...</div>
<div class="position-sticky">...</div>
<div class="fixed-top">...</div>
<div class="fixed-bottom">...</div>
<div class="sticky-top">...</div>

https://getbootstrap.com/docs/4.0/utilities/position

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

Import a file from a subdirectory?

This basically covers all cases (make sure you have __init__.py in relative/path/to/your/lib/folder):

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/relative/path/to/your/lib/folder")
import someFileNameWhichIsInTheFolder
...
somefile.foo()

Example:

You have in your project folder:

/root/myproject/app.py

You have in another project folder:

/root/anotherproject/utils.py
/root/anotherproject/__init__.py

You want to use /root/anotherproject/utils.py and call foo function which is in it.

So you write in app.py:

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../anotherproject")
import utils

utils.foo()

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

If no data validation excuted, or the content is always returned in a new window, make sure these 3 lines are at the top of the view:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Generate random numbers with a given (numerical) distribution

Another answer, probably faster :)

distribution = [(1, 0.2), (2, 0.3), (3, 0.5)]  
# init distribution  
dlist = []  
sumchance = 0  
for value, chance in distribution:  
    sumchance += chance  
    dlist.append((value, sumchance))  
assert sumchance == 1.0 # not good assert because of float equality  

# get random value  
r = random.random()  
# for small distributions use lineair search  
if len(distribution) < 64: # don't know exact speed limit  
    for value, sumchance in dlist:  
        if r < sumchance:  
            return value  
else:  
    # else (not implemented) binary search algorithm  

The number of method references in a .dex file cannot exceed 64k API 17

I got this error message because while coding my project auto update compile version in my build.gradle file :

android {
    ...
    buildToolsVersion "23.0.2"
    ...
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0' }

Solve it by correcting the version:

android {
        ...
        buildToolsVersion "23.0.2"
        ...
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}

Find row where values for column is maximal in a pandas DataFrame

df.iloc[df['columnX'].argmax()]

argmax() would provide the index corresponding to the max value for the columnX. iloc can be used to get the row of the DataFrame df for this index.

Get exit code for command in bash/ksh

It should be $cmd instead of $($cmd). Works fine with that on my box.

Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd with "$@". And, do not run your script as command="some cmd"; safeRun command, run it as safeRun some cmd.

Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].

How do I do top 1 in Oracle?

Use:

SELECT x.*
  FROM (SELECT fname 
          FROM MyTbl) x
 WHERE ROWNUM = 1

If using Oracle9i+, you could look at using analytic functions like ROW_NUMBER() but they won't perform as well as ROWNUM.

How do I grep for all non-ASCII characters?

Searching for non-printable chars. TLDR; Executive Summary

  1. search for control chars AND extended unicode
  2. locale setting e.g. LC_ALL=C needed to make grep do what you might expect with extended unicode

SO the preferred non-ascii char finders:

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test

as in top answer, the inverse grep:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

as in top answer but WITH LC_ALL=C:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test

. . more . . excruciating detail on this: . . .

I agree with Harvey above buried in the comments, it is often more useful to search for non-printable characters OR it is easy to think non-ASCII when you really should be thinking non-printable. Harvey suggests "use this: "[^\n -~]". Add \r for DOS text files. That translates to "[^\x0A\x020-\x07E]" and add \x0D for CR"

Also, adding -c (show count of patterns matched) to grep is useful when searching for non-printable chars as the strings matched can mess up terminal.

I found adding range 0-8 and 0x0e-0x1f (to the 0x80-0xff range) is a useful pattern. This excludes the TAB, CR and LF and one or two more uncommon printable chars. So IMHO a quite a useful (albeit crude) grep pattern is THIS one:

grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" *

ACTUALLY, generally you will need to do this:

LC_ALL=C grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" *

breakdown:

LC_ALL=C - set locale to C, otherwise many extended chars will not match (even though they look like they are encoded > 0x80)
\x00-\x08 - non-printable control chars 0 - 7 decimal
\x0E-\x1F - more non-printable control chars 14 - 31 decimal
\x80-1xFF - non-printable chars > 128 decimal
-c - print count of matching lines instead of lines
-P - perl style regexps

Instead of -c you may prefer to use -n (and optionally -b) or -l
-n, --line-number
-b, --byte-offset
-l, --files-with-matches

E.g. practical example of use find to grep all files under current directory:

LC_ALL=C find . -type f -exec grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" {} + 

You may wish to adjust the grep at times. e.g. BS(0x08 - backspace) char used in some printable files or to exclude VT(0x0B - vertical tab). The BEL(0x07) and ESC(0x1B) chars can also be deemed printable in some cases.

Non-Printable ASCII Chars
** marks PRINTABLE but CONTROL chars that is useful to exclude sometimes
Dec   Hex Ctrl Char description           Dec Hex Ctrl Char description
0     00  ^@  NULL                        16  10  ^P  DATA LINK ESCAPE (DLE)
1     01  ^A  START OF HEADING (SOH)      17  11  ^Q  DEVICE CONTROL 1 (DC1)
2     02  ^B  START OF TEXT (STX)         18  12  ^R  DEVICE CONTROL 2 (DC2)
3     03  ^C  END OF TEXT (ETX)           19  13  ^S  DEVICE CONTROL 3 (DC3)
4     04  ^D  END OF TRANSMISSION (EOT)   20  14  ^T  DEVICE CONTROL 4 (DC4)
5     05  ^E  END OF QUERY (ENQ)          21  15  ^U  NEGATIVE ACKNOWLEDGEMENT (NAK)
6     06  ^F  ACKNOWLEDGE (ACK)           22  16  ^V  SYNCHRONIZE (SYN)
7     07  ^G  BEEP (BEL)                  23  17  ^W  END OF TRANSMISSION BLOCK (ETB)
8     08  ^H  BACKSPACE (BS)**            24  18  ^X  CANCEL (CAN)
9     09  ^I  HORIZONTAL TAB (HT)**       25  19  ^Y  END OF MEDIUM (EM)
10    0A  ^J  LINE FEED (LF)**            26  1A  ^Z  SUBSTITUTE (SUB)
11    0B  ^K  VERTICAL TAB (VT)**         27  1B  ^[  ESCAPE (ESC)
12    0C  ^L  FF (FORM FEED)**            28  1C  ^\  FILE SEPARATOR (FS) RIGHT ARROW
13    0D  ^M  CR (CARRIAGE RETURN)**      29  1D  ^]  GROUP SEPARATOR (GS) LEFT ARROW
14    0E  ^N  SO (SHIFT OUT)              30  1E  ^^  RECORD SEPARATOR (RS) UP ARROW
15    0F  ^O  SI (SHIFT IN)               31  1F  ^_  UNIT SEPARATOR (US) DOWN ARROW

UPDATE: I had to revisit this recently. And, YYMV depending on terminal settings/solar weather forecast BUT . . I noticed that grep was not finding many unicode or extended characters. Even though intuitively they should match the range 0x80 to 0xff, 3 and 4 byte unicode characters were not matched. ??? Can anyone explain this? YES. @frabjous asked and @calandoa explained that LC_ALL=C should be used to set locale for the command to make grep match.

e.g. my locale LC_ALL= empty

$ locale
LANG=en_IE.UTF-8
LC_CTYPE="en_IE.UTF-8"
.
.
LC_ALL=

grep with LC_ALL= empty matches 2 byte encoded chars but not 3 and 4 byte encoded:

$ grep -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" notes_unicode_emoji_test
5:© copyright c2a9
7:call  underscore c2a0
9:CTRL
31:5 © copyright
32:7 call  underscore

grep with LC_ALL=C does seem to match all extended characters that you would want:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test  
1:???? unicode dashes e28090
3:??? Heart With Arrow Emoji - Emojipedia == UTF8? f09f9298
5:? copyright c2a9
7:call? underscore c2a0
11:LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other e38182 e38184 . . e0a487
29:1 ???? unicode dashes
30:3 ??? Heart With Arrow Emoji - Emojipedia == UTF8 e28090
31:5 ? copyright
32:7 call? underscore
33:11 LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other
34:52 LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other
81:LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other

THIS perl match (partially found elsewhere on stackoverflow) OR the inverse grep on the top answer DO seem to find ALL the ~weird~ and ~wonderful~ "non-ascii" characters without setting locale:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test  

1 -- unicode dashes e28090
3  Heart With Arrow Emoji - Emojipedia == UTF8? f09f9298
5 © copyright c2a9
7 call  underscore c2a0
9 CTRL-H CHARS URK URK URK 
11 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other e38182 e38184 . . e0a487
29 1 -- unicode dashes
30 3  Heart With Arrow Emoji - Emojipedia == UTF8 e28090
31 5 © copyright
32 7 call  underscore
33 11 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other
34 52 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other
73 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other

SO the preferred non-ascii char finders:

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test

as in top answer, the inverse grep:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

as in top answer but WITH LC_ALL=C:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test

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

Just don't perform e.preventDefault();, or perform it conditionally.

You certainly can't alter when the original event action occurs.

If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach.

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

How to use the read command in Bash?

Do you need the pipe?

echo -ne "$MENU"
read NUMBER

Angular - "has no exported member 'Observable'"

Apparently (as you point in the error log), after updating to Angular 6.0.0 rxjs-compat is missing.

Run npm install rxjs-compat --save to install. Should fix it.

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

Update multiple columns in SQL

update T1
set T1.COST2=T1.TOT_COST+2.000,
T1.COST3=T1.TOT_COST+2.000,
T1.COST4=T1.TOT_COST+2.000,
T1.COST5=T1.TOT_COST+2.000,
T1.COST6=T1.TOT_COST+2.000,
T1.COST7=T1.TOT_COST+2.000,
T1.COST8=T1.TOT_COST+2.000,
T1.COST9=T1.TOT_COST+2.000,
T1.COST10=T1.TOT_COST+2.000,
T1.COST11=T1.TOT_COST+2.000,
T1.COST12=T1.TOT_COST+2.000,
T1.COST13=T1.TOT_COST+2.000
from DBRMAST T1 
inner join DBRMAST t2 on t2.CODE=T1.CODE

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I'm astonished to see so many replies requiring coding to change a single use case (GET) in one API instead of using a proper tool what has to be installed once and can be used for any API (own or 3rd party) and all use cases.

So the good answer is:

  1. If you only want to request json or other content type install Requestly or a similar tool and modify the Accept header.
  2. If you want to use POST too and have nicely formatted json, xml, etc. use a proper API testing extension like Postman or ARC.

How to remove item from a python list in a loop?

You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:

y = [s for s in x if len(s) == 2]

How to get the absolute path to the public_html folder?

with preg_replace function to find absolute path from __FILE__ you can easily find with anything home user. Here short my code :

$path_image_you_want = preg_replace('#/public_html/([^/]+?)/.*#', '/public_html/$1/images", __FILE__);

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);