Programs & Examples On #Numberformatter

numberformatter is a component of ICU - International Components for Unicode to format numbers. It is available in many programming languages incl. C, Java and PHP.

JQuery Number Formatting

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.

Eclipse "this compilation unit is not on the build path of a java project"

Like the message says, is the file somewhere on the project's Java Build Path (e.g. a Source folder)?

How to make div follow scrolling smoothly with jQuery?

There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.

It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

How to check if internet connection is present in Java?

I usually break it down into three steps.

  1. I first see if I can resolve the domain name to an IP address.
  2. I then try to connect via TCP (port 80 and/or 443) and close gracefully.
  3. Finally, I'll issue an HTTP request and check for a 200 response back.

If it fails at any point, I provide the appropriate error message to the user.

Priority queue in .Net

Here's my attempt at a .NET heap

public abstract class Heap<T> : IEnumerable<T>
{
    private const int InitialCapacity = 0;
    private const int GrowFactor = 2;
    private const int MinGrow = 1;

    private int _capacity = InitialCapacity;
    private T[] _heap = new T[InitialCapacity];
    private int _tail = 0;

    public int Count { get { return _tail; } }
    public int Capacity { get { return _capacity; } }

    protected Comparer<T> Comparer { get; private set; }
    protected abstract bool Dominates(T x, T y);

    protected Heap() : this(Comparer<T>.Default)
    {
    }

    protected Heap(Comparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)
    {
    }

    protected Heap(IEnumerable<T> collection)
        : this(collection, Comparer<T>.Default)
    {
    }

    protected Heap(IEnumerable<T> collection, Comparer<T> comparer)
    {
        if (collection == null) throw new ArgumentNullException("collection");
        if (comparer == null) throw new ArgumentNullException("comparer");

        Comparer = comparer;

        foreach (var item in collection)
        {
            if (Count == Capacity)
                Grow();

            _heap[_tail++] = item;
        }

        for (int i = Parent(_tail - 1); i >= 0; i--)
            BubbleDown(i);
    }

    public void Add(T item)
    {
        if (Count == Capacity)
            Grow();

        _heap[_tail++] = item;
        BubbleUp(_tail - 1);
    }

    private void BubbleUp(int i)
    {
        if (i == 0 || Dominates(_heap[Parent(i)], _heap[i])) 
            return; //correct domination (or root)

        Swap(i, Parent(i));
        BubbleUp(Parent(i));
    }

    public T GetMin()
    {
        if (Count == 0) throw new InvalidOperationException("Heap is empty");
        return _heap[0];
    }

    public T ExtractDominating()
    {
        if (Count == 0) throw new InvalidOperationException("Heap is empty");
        T ret = _heap[0];
        _tail--;
        Swap(_tail, 0);
        BubbleDown(0);
        return ret;
    }

    private void BubbleDown(int i)
    {
        int dominatingNode = Dominating(i);
        if (dominatingNode == i) return;
        Swap(i, dominatingNode);
        BubbleDown(dominatingNode);
    }

    private int Dominating(int i)
    {
        int dominatingNode = i;
        dominatingNode = GetDominating(YoungChild(i), dominatingNode);
        dominatingNode = GetDominating(OldChild(i), dominatingNode);

        return dominatingNode;
    }

    private int GetDominating(int newNode, int dominatingNode)
    {
        if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))
            return newNode;
        else
            return dominatingNode;
    }

    private void Swap(int i, int j)
    {
        T tmp = _heap[i];
        _heap[i] = _heap[j];
        _heap[j] = tmp;
    }

    private static int Parent(int i)
    {
        return (i + 1)/2 - 1;
    }

    private static int YoungChild(int i)
    {
        return (i + 1)*2 - 1;
    }

    private static int OldChild(int i)
    {
        return YoungChild(i) + 1;
    }

    private void Grow()
    {
        int newCapacity = _capacity*GrowFactor + MinGrow;
        var newHeap = new T[newCapacity];
        Array.Copy(_heap, newHeap, _capacity);
        _heap = newHeap;
        _capacity = newCapacity;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _heap.Take(Count).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

public class MaxHeap<T> : Heap<T>
{
    public MaxHeap()
        : this(Comparer<T>.Default)
    {
    }

    public MaxHeap(Comparer<T> comparer)
        : base(comparer)
    {
    }

    public MaxHeap(IEnumerable<T> collection, Comparer<T> comparer)
        : base(collection, comparer)
    {
    }

    public MaxHeap(IEnumerable<T> collection) : base(collection)
    {
    }

    protected override bool Dominates(T x, T y)
    {
        return Comparer.Compare(x, y) >= 0;
    }
}

public class MinHeap<T> : Heap<T>
{
    public MinHeap()
        : this(Comparer<T>.Default)
    {
    }

    public MinHeap(Comparer<T> comparer)
        : base(comparer)
    {
    }

    public MinHeap(IEnumerable<T> collection) : base(collection)
    {
    }

    public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)
        : base(collection, comparer)
    {
    }

    protected override bool Dominates(T x, T y)
    {
        return Comparer.Compare(x, y) <= 0;
    }
}

Some tests:

[TestClass]
public class HeapTests
{
    [TestMethod]
    public void TestHeapBySorting()
    {
        var minHeap = new MinHeap<int>(new[] {9, 8, 4, 1, 6, 2, 7, 4, 1, 2});
        AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());

        minHeap = new MinHeap<int> { 7, 5, 1, 6, 3, 2, 4, 1, 2, 1, 3, 4, 7 };
        AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());

        var maxHeap = new MaxHeap<int>(new[] {1, 5, 3, 2, 7, 56, 3, 1, 23, 5, 2, 1});
        AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());

        maxHeap = new MaxHeap<int> {2, 6, 1, 3, 56, 1, 4, 7, 8, 23, 4, 5, 7, 34, 1, 4};
        AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());
    }

    private static void AssertHeapSort(Heap<int> heap, IEnumerable<int> expected)
    {
        var sorted = new List<int>();
        while (heap.Count > 0)
            sorted.Add(heap.ExtractDominating());

        Assert.IsTrue(sorted.SequenceEqual(expected));
    }
}

Make absolute positioned div expand parent div height

There is a better way to do this now. You can use the bottom property.

    .my-element {
      position: absolute;
      bottom: 30px;
    }

Python executable not finding libpython shared library

This answer would be helpful to those who have limited auth access on the server.

I had a similar problem for python3.5 in HostGator's shared hosting. Python3.5 had to be enabled every single damn time after login. Here are my 10 steps for resolution:

  1. Enable the python through scl script python_enable_3.5 or scl enable rh-python35 bash.

  2. Verify that it's enabled by executing python3.5 --version. This should give you your python version.

  3. Execute which python3.5 to get its path. In my case, it was /opt/rh/rh-python35/root/usr/bin/python3.5. You can use this path get the version again (just to verify that this path is working for you.)

  4. Awesome, now please exit out of current shell by scl.

  5. Now, lets get the version again through this complete python3.5 path /opt/rh/rh-python35/root/usr/bin/python3.5 --version.

    It won't give you the version but an error. In my case, it was

/opt/rh/rh-python35/root/usr/bin/python3.5: error while loading shared libraries: libpython3.5m.so.rh-python35-1.0: cannot open shared object file: No such file or directory
  1. As mentioned in Tamas' answer, we gotta find that so file. locate doesn't work in shared hosting and you can't install that too.

    Use the following command to find where that file is located:

find /opt/rh/rh-python35 -name "libpython3.5m.so.rh-python35-1.0"
  1. Above command would print the complete path (second line) of the file once located. In my case, output was
find: `/opt/rh/rh-python35/root/root': Permission denied
/opt/rh/rh-python35/root/usr/lib64/libpython3.5m.so.rh-python35-1.0
  1. Here is the complete command for the python3.5 to work in such shared hosting which would give the version,
LD_LIBRARY_PATH=/opt/rh/rh-python35/root/usr/lib64 /opt/rh/rh-python35/root/usr/bin/python3.5 --version
  1. Finally, for shorthand, append the following alias in your ~/.bashrc
alias python351='LD_LIBRARY_PATH=/opt/rh/rh-python35/root/usr/lib64 /opt/rh/rh-python35/root/usr/bin/python3.5'
  1. For verification, reload the .bashrc by source ~/.bashrc and execute python351 --version.

Well, there you go, now whenever you login again, you have got python351 to welcome you.

This is not just limited to python3.5, but can be helpful in case of other scl installed softwares.

Running the new Intel emulator for Android

Using SDK Manager to download Intel HAX did not work.

Downloading and installing it from the Intel website did work. http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/

Top Tip: making the change in my BIOS to enable virtualization and then using "restart" did not enable virtualization. Doing a cold boot (i.e. shutdown and restart) suddenly made it appear.

The first step (on Windows) is to make sure that the Micrsoft Hardware-Assisted Virtualization Tool reports that "this computer is configured with hardware-assisted virtualization". http://www.microsoft.com/en-us/download/details.aspx?id=592

AngularJS ui-router login authentication

Here is how we got out of the infinite routing loop and still used $state.go instead of $location.path

if('401' !== toState.name) {
  if (principal.isIdentityResolved()) authorization.authorize();
}

No submodule mapping found in .gitmodule for a path that's not a submodule

Just git rm subdir will be ok. that will remove the subdir as an index.

Date formatting in WPF datagrid

Very late to the party here but in case anyone else stumbles across this page...

You can do it by setting the AutoGeneratingColumn handler in XAML:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

And then in code behind do something like this:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}

How to get distinct values for non-key column fields in Laravel?

// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

add this to your my.cnf

innodb_buffer_pool_size=1G

restart your mysql to make it effect

Python regex for integer?

I prefer ^[-+]?([1-9]\d*|0)$ because ^[-+]?[0-9]+$ allows the string starting with 0.

RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')


class TestRE(unittest.TestCase):
    def test_int(self):
        self.assertFalse(RE_INT.match('+'))
        self.assertFalse(RE_INT.match('-'))

        self.assertTrue(RE_INT.match('1'))
        self.assertTrue(RE_INT.match('+1'))
        self.assertTrue(RE_INT.match('-1'))
        self.assertTrue(RE_INT.match('0'))
        self.assertTrue(RE_INT.match('+0'))
        self.assertTrue(RE_INT.match('-0'))

        self.assertTrue(RE_INT.match('11'))
        self.assertFalse(RE_INT.match('00'))
        self.assertFalse(RE_INT.match('01'))
        self.assertTrue(RE_INT.match('+11'))
        self.assertFalse(RE_INT.match('+00'))
        self.assertFalse(RE_INT.match('+01'))
        self.assertTrue(RE_INT.match('-11'))
        self.assertFalse(RE_INT.match('-00'))
        self.assertFalse(RE_INT.match('-01'))

        self.assertTrue(RE_INT.match('1234567890'))
        self.assertTrue(RE_INT.match('+1234567890'))
        self.assertTrue(RE_INT.match('-1234567890'))

Firing events on CSS class changes in jQuery

There is one more way without triggering an custom event

A jQuery Plug-in to monitor Html Element CSS Changes by Rick Strahl

Quoting from above

The watch plug-in works by hooking up to DOMAttrModified in FireFox, to onPropertyChanged in Internet Explorer, or by using a timer with setInterval to handle the detection of changes for other browsers. Unfortunately WebKit doesn’t support DOMAttrModified consistently at the moment so Safari and Chrome currently have to use the slower setInterval mechanism.

jsonify a SQLAlchemy result set in Flask

Here's my approach: https://github.com/n0nSmoker/SQLAlchemy-serializer

pip install SQLAlchemy-serializer

You can easily add mixin to your model and than just call .to_dict() method on it's instance

You also can write your own mixin on base of SerializerMixin

Difference between DOMContentLoaded and load events

  • domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.

  • loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.

source

How do I fix PyDev "Undefined variable from import" errors?

I find that these 2 steps work for me all the time:

  1. Confirm (else add) the parent folder of the module to the PYTHONPATH.
  2. Add FULL name of the module to forced builtins.

The things to note here:

  • Some popular modules install with some parent and child pair having the same name. In these cases you also have to add that parent to PYTHONPATH, in addition to its grandparent folder, which you already confirmed/added for everything else.

  • Use (for example) "google.appengine.api.memcache" when adding to forced builtins, NOT "memcache" only, where "google" in this example, is an immediate child of a folder defined in PYTHONPATH.

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

How to use jQuery in chrome extension?

In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

manifest.json

{
  "name": "JQuery Light",
  "version": "1",
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png"
  },

  "content_scripts": [
    {
      "matches": [
        "https://*.google.com/*"
      ],
      "js": [
        "jquery-3.3.1.min.js",
        "myscript.js"
      ]
    }
  ],

  "background": {
    "scripts": [
      "background.js"
    ]
  }

}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

myscript.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
        console.log('Hello world!')
        }
    }
);

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

How to close a Java Swing application from the code

If I understand you correctly you want to close the application even if the user did not click on the close button. You will need to register WindowEvents maybe with addWindowListener() or enableEvents() whichever suits your needs better.

You can then invoke the event with a call to processWindowEvent(). Here is a sample code that will create a JFrame, wait 5 seconds and close the JFrame without user interaction.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame implements WindowListener{

public ClosingFrame(){
    super("A Frame");
    setSize(400, 400);
            //in case the user closes the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            //enables Window Events on this Component
            this.addWindowListener(this);

            //start a timer
    Thread t = new Timer();
            t.start();
    }

public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){}

    //the event that we are interested in
public void windowClosed(WindowEvent e){
    System.exit(0);
}

public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

    //a simple timer 
    class Timer extends Thread{
           int time = 10;
           public void run(){
     while(time-- > 0){
       System.out.println("Still Waiting:" + time);
               try{
                 sleep(500);                     
               }catch(InterruptedException e){}
             }
             System.out.println("About to close");
    //close the frame
            ClosingFrame.this.processWindowEvent(
                 new WindowEvent(
                       ClosingFrame.this, WindowEvent.WINDOW_CLOSED));
           }
    }

    //instantiate the Frame
public static void main(String args[]){
          new ClosingFrame();
    }

}

As you can see, the processWindowEvent() method causes the WindowClosed event to be fired where you have an oportunity to do some clean up code if you require before closing the application.

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

How to change the remote a branch is tracking?

git fetch origin
git checkout --track -b local_branch_name origin/branch_name

or

git fetch
git checkout -b local_branch_name origin/branch_name

Need to combine lots of files in a directory

If you like to do this for open files on Notepad++, you can use Combine plugin: http://www.scout-soft.com/combine/

How do I reverse a C++ vector?

All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.

#include <vector>
#include <iostream>

template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
  --last;
  for(; first != last; ++first){
    std::cout << *first << delim;
  }
  std::cout << *first;
}

int main(){
  int a[] = { 1, 2, 3, 4, 5 };
  std::vector<int> v(a, a+5);
  print_range(v.begin(), v.end(), "->");
  std::cout << "\n=============\n";
  print_range(v.rbegin(), v.rend(), "<-");
}

Live example on Ideone. Output:

1->2->3->4->5
=============
5<-4<-3<-2<-1

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

the following points work for me. Try:

  1. start SSMS as administrator
  2. make sure SQL services are running. Change startup type to 'Automatic'

enter image description here

  1. In SSMS, in service instance property table, enable below:

enter image description here

Relative frequencies / proportions with dplyr

This answer is based upon Matifou's answer.

First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

getOption("scipen") 
options("scipen"=10) 
mtcars %>%
count(am, gear) %>% 
mutate(freq = (n / sum(n)) * 100)

socket.emit() vs. socket.send()

Simple and precise (Source: Socket.IO google group):

socket.emit allows you to emit custom events on the server and client

socket.send sends messages which are received with the 'message' event

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

In simple words

$.ajax("info.txt").done(function(data) {
  alert(data);
}).fail(function(data){
  alert("Try again champ!");
});

if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.

How do I get the "id" after INSERT into MySQL database with Python?

This might be just a requirement of PyMySql in Python, but I found that I had to name the exact table that I wanted the ID for:

In:

cnx = pymysql.connect(host='host',
                            database='db',
                            user='user',
                            password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22  ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()

batch_id

Out: 5
... or whatever the correct Batch_ID value actually is

How do you check for permissions to write to a directory or file?

When your code does the following:

  1. Checks the current user has permission to do something.
  2. Carries out the action that needs the entitlements checked in 1.

You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.

Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.

Example (derived from Josh's example):

//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

//2. Attempt the action but handle permission changes.
try
{
    using (FileStream fstream = new FileStream(filename, FileMode.Create))
    using (TextWriter writer = new StreamWriter(fstream))
    {
        writer.WriteLine("sometext");
    }
}
catch (UnauthorizedAccessException ex)
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.

Post Build exited with code 1

Get process monitor from SysInternals set it up to watch for the Lunaverse.DbVerse (on the Path field) look at the operation result. It should be obvious from there what went wrong

How to remove the first character of string in PHP?

To remove first Character of string in PHP,

$string = "abcdef";     
$new_string = substr($string, 1);

echo $new_string;
Generates: "bcdef"

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

Do the parentheses after the type name make a difference with new?

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize

  • new B - default construct (B::m is uninitialized)

  • new B() - default construct (B::m is uninitialized)

  • new C - default construct (C::m is zero-initialized)

  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

  • new B - default-initializes (leaves B::m uninitialized)

  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

  • new C - default-initializes C, which calls the default ctor.

  • new C() - value-initializes C, which calls the default ctor.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

And there's a difference in behavior between C++98 and C++03 for the case new B().

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

Check if two unordered lists are equal

You want to see if they contain the same elements, but don't care about the order.

You can use a set:

>>> set(['one', 'two', 'three']) == set(['two', 'one', 'three'])
True

But the set object itself will only contain one instance of each unique value, and will not preserve order.

>>> set(['one', 'one', 'one']) == set(['one'])
True

So, if tracking duplicates/length is important, you probably want to also check the length:

def are_eq(a, b):
    return set(a) == set(b) and len(a) == len(b)

Percentage width in a RelativeLayout

I have solved this creating a custom View:

public class FractionalSizeView extends View {
  public FractionalSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FractionalSizeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width * 70 / 100, 0);
  }
}

This is invisible strut I can use to align other views within RelativeLayout.

function declaration isn't a prototype

In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.

If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.

I suggest removing the extern, it is extraneous and is usually omitted.

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

How to increase request timeout in IIS?

Add this to your Web Config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx

Optional TimeSpan attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.

The default is "00:01:50" (110 seconds).

How do I get a UTC Timestamp in JavaScript?

I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.

Trying to add adb to PATH variable OSX

On my Macbook Pro, I've added the export lines to ~/.bash_profile, not .profile.

e.g.

export PATH=/Users/me/android-sdk-mac_86/platform-tools:/Users/me/android-sdk-mac_86/tools:$PATH

What design patterns are used in Spring framework?

Service Locator Pattern - ServiceLocatorFactoryBean keeps information of all the beans in the context. When client code asks for a service (bean) using name, it simply locates that bean in the context and returns it. Client code does not need to write spring related code to locate a bean.

Can regular expressions be used to match nested patterns?

as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm

Using Java with Nvidia GPUs (CUDA)

From the research I have done, if you are targeting Nvidia GPUs and have decided to use CUDA over OpenCL, I found three ways to use the CUDA API in java.

  1. JCuda (or alternative)- http://www.jcuda.org/. This seems like the best solution for the problems I am working on. Many of libraries such as CUBLAS are available in JCuda. Kernels are still written in C though.
  2. JNI - JNI interfaces are not my favorite to write, but are very powerful and would allow you to do anything CUDA can do.
  3. JavaCPP - This basically lets you make a JNI interface in Java without writing C code directly. There is an example here: What is the easiest way to run working CUDA code in Java? of how to use this with CUDA thrust. To me, this seems like you might as well just write a JNI interface.

All of these answers basically are just ways of using C/C++ code in Java. You should ask yourself why you need to use Java and if you can't do it in C/C++ instead.

If you like Java and know how to use it and don't want to work with all the pointer management and what-not that comes with C/C++ then JCuda is probably the answer. On the other hand, the CUDA Thrust library and other libraries like it can be used to do a lot of the pointer management in C/C++ and maybe you should look at that.

If you like C/C++ and don't mind pointer management, but there are other constraints forcing you to use Java, then JNI might be the best approach. Though, if your JNI methods are just going be wrappers for kernel commands you might as well just use JCuda.

There are a few alternatives to JCuda such as Cuda4J and Root Beer, but those do not seem to be maintained. Whereas at the time of writing this JCuda supports CUDA 10.1. which is the most up-to-date CUDA SDK.

Additionally there are a few java libraries that use CUDA, such as deeplearning4j and Hadoop, that may be able to do what you are looking for without requiring you to write kernel code directly. I have not looked into them too much though.

Aligning a float:left div to center?

CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.

This works fine in all newer browsers:

_x000D_
_x000D_
#container {_x000D_
  display:         flex;_x000D_
  flex-wrap:       wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
  width:              150px;_x000D_
  height:             150px;_x000D_
  background-color:   #cccccc;_x000D_
  margin:             10px;        _x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="block">1</div>    _x000D_
  <div class="block">2</div>    _x000D_
  <div class="block">3</div>    _x000D_
  <div class="block">4</div>    _x000D_
  <div class="block">5</div>        _x000D_
</div>
_x000D_
_x000D_
_x000D_

Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"

solution : first identified all jpg files and then replace keyword

find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \; 

Unable to get spring boot to automatically create database schema

This is what I did after reading all of the answers above.

  1. Add spring.jpa.hibernate.ddl-auto=update with other simple properties to application.properties
  2. run
  3. In the console, you can see the error. At one place in the error, you can find the SQL code generated by this software to create your entity table.
  4. Copy that SQL code and paste it separately into your DBMS to create the table.
  5. After that, run the app again.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Single quotes vs. double quotes in C or C++

A single quote is used for character, while double quotes are used for strings.

For example...

 printf("%c \n",'a');
 printf("%s","Hello World");

Output

a  
Hello World

If you used these in vice versa case and used a single quote for string and double quotes for a character, this will be the result:

  printf("%c \n","a");
  printf("%s",'Hello World');

output :

For the first line. You will get a garbage value or unexpected value or you may get an output like this:

?

While for the second statement, you will see nothing. One more thing, if you have more statements after this, they will also give you no result.

Note: PHP language gives you the flexibility to use single and double-quotes easily.

How to view file diff in git before commit

Did you try -v (or --verbose) option for git commit? It adds the diff of the commit in the message editor.

jQuery remove options from select

For jquery < 1.8 you can use :

$('#selectedId option').slice(index1,index2).remove()

to remove a especific range of the select options.

Why does JavaScript only work after opening developer tools in IE once?

I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:

        try {
            console.log(message);
        } catch (e) {
        }

It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

Converting unix timestamp string to readable date

There are two parts:

  1. Convert the unix timestamp ("seconds since epoch") to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

To display it, you could use any time format that is supported by your system e.g.:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

If you do not need a local time, to get a readable UTC time instead:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

INSERT SELECT statement in Oracle 11G

You don't need the 'values' clause when using a 'select' as your source.

insert into table1 (col1, col2) 
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;

Python way to clone a git repository

There is GitPython. Haven’t heard of it before and internally, it relies on having the git executables somewhere; additionally, they might have plenty of bugs. But it could be worth a try.

How to clone:

import git
git.Git("/your/directory/to/clone").clone("git://gitorious.org/git-python/mainline.git")

(It’s not nice and I don’t know if it is the supported way to do it, but it worked.)

How to convert hex to rgb using Java?

I guess this should do it:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}

How to break out of multiple loops?

This isn't the prettiest way to do it, but in my opinion, it's the best way.

def loop():
    while True:
    #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": return
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff

I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.

Auto increment primary key in SQL Server Management Studio 2012

Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .

Examle: before restart ID=11 after restart , you insert new row in the table, then the id will be 1012.

Can pm2 run an 'npm start' script

It's working fine on CentOS 7

PM2 version 4.2.1

let's take two scenarios:

1. npm start //server.js

pm2 start "npm -- start" --name myMainFile

2. npm run main //main.js

pm2 start "npm -- run main" --name myMainFile

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

React Native absolute positioning horizontal centre

You can try the code

<View
    style={{
      alignItems: 'center',
      justifyContent: 'center'
    }}
  >
    <View
      style={{
        position: 'absolute',
        margin: 'auto',
        width: 50,
        height: 50
      }}
    />
  </View>

What is the Git equivalent for revision number?

Git does not have the same concept of revision numbers as subversion. Instead each given snapshot made with a commit is tagged by a SHA1 checksum. Why? There are several problems with a running revno in a distributed version control system:

First, since development is not linear at all, the attachment of a number is rather hard as a problem to solve in a way which will satisfy your need as a programmer. Trying to fix this by adding a number might quickly become problematic when the number does not behave as you expect.

Second, revision numbers may be generated on different machines. This makes synchronization of numbers much harder - especially since connectivity is one-way; you may not even have access to all machines that has the repository.

Third, in git, somewhat pioneered by the now defunct OpenCM system, the identity of a commit (what the commit is) is equivalent to its name (the SHA id). This naming = identity concept is very strong. When you sit with a commit name in hand it also identifies the commit in an unforgeable way. This in turn lets you check all of your commits back to the first initial one for corruption with the git fsck command.

Now, since we have a DAG (Directed Acyclic Graph) of revisions and these constitute the current tree, we need some tools to solve your problem: How do we discriminate different versions. First, you can omit part of the hash if a given prefix, 1516bd say, uniquely identifies your commit. But this is also rather contrived. Instead, the trick is to use tags and or branches. A tag or branch is akin to a "yellow stick it note" you attach to a given commit SHA1-id. Tags are, in essence, meant to be non-moving whereas a branch will move when new commits are made to its HEAD. There are ways to refer to a commit around a tag or branch, see the man page of git-rev-parse.

Usually, if you need to work on a specific piece of code, that piece is undergoing changes and should as such be a branch with a saying topic name. Creating lots of branches (20-30 per programmer is not unheard of, with some 4-5 published for others to work on) is the trick for effective git. Every piece of work should start as its own branch and then be merged in when it is tested. Unpublished branches can be rewritten entirely and this part of destroying history is a force of git.

When the change is accepted into master it somewhat freezes and becomes archeology. At that point, you can tag it, but more often a reference to the particular commit is made in a bug tracker or issue tracker via the sha1 sum. Tags tend to be reserved for version bumps and branch points for maintenance branches (for old versions).

get next and previous day with PHP

Requirement: PHP 5 >= 5.2.0

You should make use of the DateTime and DateInterval classes in Php, and things will turn to be very easy and readable.

Example: Lets get the previous day.

// always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');

// create DateTime instance, holding the current datetime
$datetime = new DateTime();

// create one day interval
$interval = new DateInterval('P1D');

// modify the DateTime instance
$datetime->sub($interval);

// display the result, or print_r($datetime); for more insight 
echo $datetime->format('Y-m-d');


/** 
* TIP:
* if you dont want to change the default timezone, use
* use the DateTimeZone class instead.
*
* $myTimezone = new DateTimeZone('Europe/Berlin');
* $datetime->setTimezone($myTimezone); 
*
* or just include it inside the constructor 
* in this form new DateTime("now",   $myTimezone);
*/

References: Modern PHP, New Features and Good Practices By Josh Lockhart

ConfigurationManager.AppSettings - How to modify and save?

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

Phone validation regex

This regex matches any number with the common format 1-(999)-999-9999 and anything in between. Also, the regex will allow braces or no braces and separations with period, space or dash. "^([01][- .])?(\(\d{3}\)|\d{3})[- .]?\d{3}[- .]\d{4}$"

Importing variables from another file?

Actually this is not really the same to import a variable with:

from file1 import x1
print(x1)

and

import file1
print(file1.x1)

Altough at import time x1 and file1.x1 have the same value, they are not the same variables. For instance, call a function in file1 that modifies x1 and then try to print the variable from the main file: you will not see the modified value.

'Class' does not contain a definition for 'Method'

I had the same problem. I changed the Version of Assembly in AssemblyInfo.cs in the Properties Folder. But, I don't have any idea why this problem happened. Maybe the compiler doesn't understand that this dll is newer, just changing the version of Assembly.

How to pass the id of an element that triggers an `onclick` event to the event handling function

Use this:

<link onclick='doWithThisElement(this.attributes["id"].value)' />

In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).

How to print a percentage value in python?

Just to add Python 3 f-string solution

prob = 1.0/3.0
print(f"{prob:.0%}")

Calling a user defined function in jQuery

Just try this. It always works.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(function() {_x000D_
    $.fn.myFunction();_x000D_
  });_x000D_
  $.fn.myFunction = function() {_x000D_
    alert('hi');_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

In my case, the program was running fine, but after one day, I just ran into this problem without doing anything...

The solution was to manually add 'Main' as the Entry Point (before editing, the area was empty):

enter image description here

How to remove foreign key constraint in sql server?

Depending on the DB you are using there's a syntax or another.

If you're using Oracle you have to put what the other users told you:

ALTER TABLE table_name DROP CONSTRAINT fk_name;

But if you use MySQL then this will give you a syntax error, instead you can type:

ALTER TABLE table_name DROP INDEX fk_name;

Eclipse CDT project built but "Launch Failed. Binary Not Found"

I've got the same problem on Eclipse 3.8.1. For me it worked to set the artifact type to executable:

Right click on the project -> C/C++ Build -> Settings -> Build Artifact -> Artifact Type: Executable

Finally rebuilding the project produced the Binaries entry in the Project Explorer.

find filenames NOT ending in specific extensions on Unix?

find . ! \( -name "*.exe" -o -name "*.dll" \)

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

Another case that this might be happening is if your data was improperly written to your csv to have each row end with a comma. This will leave you with an unnamed column Unnamed: x at the end of your data when you try to read it into a df.

How to access a dictionary element in a Django template?

To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:

class Choice(models.Model):
    text = models.CharField(max_length=200)

    def calculateVotes(self):
        return Vote.objects.filter(choice=self).count()

    votes = property(calculateVotes)

And then in your template, you can do:

{% for choice in choices %}
    {{choice.choice}} - {{choice.votes}} <br />
{% endfor %}

The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.

I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.

Running a command as Administrator using PowerShell?

A number of the answers here are close, but a little more work than needed.

Create a shortcut to your script and configure it to "Run as Administrator":

  • Create the shortcut.
  • Right-click shortcut and open Properties...
  • Edit Target from <script-path> to powershell <script-path>
  • Click Advanced... and enable Run as administrator

Disable browsers vertical and horizontal scrollbars

Because Firefox has an arrow key short cut, you probably want to put a <div> around it with CSS style: overflow:hidden;.

How to make Unicode charset in cmd.exe by default?

Reg file

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9

Command Prompt

REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9

PowerShell

sp -t d HKCU:\Console CodePage 0xfde9

Cygwin

regtool set /user/Console/CodePage 0xfde9

SQL Inner join more than two tables

Please find inner join for more than 2 table here

Here are 4 table name like

  1. Orders
  2. Customers
  3. Student
  4. Lecturer

So the SQL code would be:

select o.orderid, c.customername, l.lname, s.studadd, s.studmarks 
from orders o 
    inner join customers c on o.customrid = c.customerid 
    inner join lecturer l  on o.customrid = l.id 
    inner join student s   on o.customrid=s.studmarks;

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

I had the same problem, try this works

DB_HOST=localhost

How do I get the day of week given a date?

here is how to convert a listof dates to date

import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)

How can I do an OrderBy with a dynamic string parameter?

You don't need an external library for this. The below code works for LINQ to SQL/entities.

    /// <summary>
    /// Sorts the elements of a sequence according to a key and the sort order.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of <paramref name="query" />.</typeparam>
    /// <param name="query">A sequence of values to order.</param>
    /// <param name="key">Name of the property of <see cref="TSource"/> by which to sort the elements.</param>
    /// <param name="ascending">True for ascending order, false for descending order.</param>
    /// <returns>An <see cref="T:System.Linq.IOrderedQueryable`1" /> whose elements are sorted according to a key and sort order.</returns>
    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> query, string key, bool ascending = true)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            return query;
        }

        var lambda = (dynamic)CreateExpression(typeof(TSource), key);

        return ascending 
            ? Queryable.OrderBy(query, lambda) 
            : Queryable.OrderByDescending(query, lambda);
    }

    private static LambdaExpression CreateExpression(Type type, string propertyName)
    {
        var param = Expression.Parameter(type, "x");

        Expression body = param;
        foreach (var member in propertyName.Split('.'))
        {
            body = Expression.PropertyOrField(body, member);
        }

        return Expression.Lambda(body, param);
    }

(CreateExpression copied from https://stackoverflow.com/a/16208620/111438)

System.Drawing.Image to stream C#

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

Python convert csv to xlsx

Simple 1-to-1 CSV to XLSX file conversion without enumerating/looping through the rows:

import pyexcel

sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")
sheet.save_as("myFile.xlsx")

Notes:

  1. I have found that if the file_name is really long (>30 characters excluding path) then the resultant XLSX file will throw an error when Excel tries to load it. Excel will offer to fix the error which it does, but it is frustrating.
  2. There is a great answer previously provided that combines all of the CSV files in a directory into one XLSX workbook, which fits a different use case than just trying to do a 1-to-1 CSV file to XLSX file conversion.

Use dynamic variable names in JavaScript

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).

So if you create variables like this:

var a = 1,
    b = 2,
    c = 3;

In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

Those can get accessed by using the "dot" or "bracket" notation:

var name = window.a;

or

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

function foobar() {
   this.a = 1;
   this.b = 2;

   var name = window['a']; // === undefined
   alert(name);
   name = this['a']; // === 1
   alert(name);
}

new foobar();

new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:

var a = 1,
    b = 2;

Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).

How to encode text to base64 in python

For py3, base64 encode and decode string:

import base64

def b64e(s):
    return base64.b64encode(s.encode()).decode()


def b64d(s):
    return base64.b64decode(s).decode()

date format yyyy-MM-ddTHH:mm:ssZ

"o" format is different for DateTime vs DateTimeOffset :(

DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"

DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"

My final answer is

DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
DateTime.UtcNow.ToString("o")              //for DateTime type

php - How do I fix this illegal offset type error

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

How to append text to an existing file in Java?

Slightly expanding on Kip's answer, here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

Further notes:

  1. The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)).

  2. The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure:

    Path pathParent = path.getParent();
    if (!Files.exists(pathParent)) {
        Files.createDirectories(pathParent);
    }
    

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY


BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"




def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})


 if __name__ == '__main__':
     getquote(SECURITY_NAME, START_DATE, END_DATE)

Besides this is relatively modular and ready to use snippet.

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

Adding n hours to a date in Java?

Check Calendar class. It has add method (and some others) to allow time manipulation.

Something like this should work:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());               // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1);      // adds one hour
cal.getTime();                         // returns new date object plus one hour

Check API for more.

Mergesort with Python

    def merge(a,low,mid,high):
        l=a[low:mid+1]
        r=a[mid+1:high+1]
        #print(l,r)
        k=0;i=0;j=0;
        c=[0 for i in range(low,high+1)]
        while(i<len(l) and j<len(r)):
            if(l[i]<=r[j]):

                c[k]=(l[i])
                k+=1

                i+=1
            else:
                c[k]=(r[j])
                j+=1
                k+=1
        while(i<len(l)):
            c[k]=(l[i])
            k+=1
            i+=1

        while(j<len(r)):
            c[k]=(r[j])
            k+=1
            j+=1
        #print(c)  
        a[low:high+1]=c  

    def mergesort(a,low,high):
        if(high>low):
            mid=(low+high)//2


            mergesort(a,low,mid)
            mergesort(a,mid+1,high)
            merge(a,low,mid,high)

    a=[12,8,3,2,9,0]
    mergesort(a,0,len(a)-1)
    print(a)

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

c# razor url parameter from view

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

Run as java application option disabled in eclipse

You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".

Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X to open up a context menu, then press J.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

It is not natively possible to run Android application under iOS (which powers iPhone, iPad, iPod, etc.)

This is because both runtime stacks use entirely different approaches. Android runs Dalvik (a "variant of Java") bytecode packaged in APK files while iOS runs Compiled (from Obj-C) code from IPA files. Excepting time/effort/money and litigations (!), there is nothing inherently preventing an Android implementation on Apple hardware, however.

It looks to package a small Dalvik VM with each application and targeted towards developers.

See iPhoDroid:

Looks to be a dual-boot solution for 2G/3G jailbroken devices. Very little information available, but there are some YouTube videos.

See iAndroid:

iAndroid is a new iOS application for jailbroken devices that simulates the Android operating system experience on the iPhone or iPod touch. While it’s still very far from completion, the project is taking shape.

I am not sure the approach(es) it uses to enable this: it could be emulation or just a simulation (e.g. "looks like"). The requirement of being jailbroken makes it sound like emulation might be used ..

See BlueStacks, per the Holo Dev's comment:

It looks to be an "Android App Player" for OS X (and Windows). However, afaik, it does not [currently] target iOS devices ..

YMMV

How do I concatenate a string with a variable?

It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer. The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.

How to pass parameters to a modal?

I tried as below.

I called ng-click to angularjs controller on Encourage button,

               <tr ng-cloak
                  ng-repeat="user in result.users">
                   <td>{{user.userName}}</rd>
                   <td>
                      <a class="btn btn-primary span11" ng-click="setUsername({{user.userName}})" href="#encouragementModal" data-toggle="modal">
                            Encourage
                       </a>
                  </td>
                </tr>

I set userName of encouragementModal from angularjs controller.

    /**
     * Encouragement controller for AngularJS
     * 
     * @param $scope
     * @param $http
     * @param encouragementService
     */
    function EncouragementController($scope, $http, encouragementService) {
      /**
       * set invoice number
       */
      $scope.setUsername = function (username) {
            $scope.userName = username;
      };
     }
    EncouragementController.$inject = [ '$scope', '$http', 'encouragementService' ];

I provided a place(userName) to get value from angularjs controller on encouragementModal.

<div id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

It worked and I saluted myself.

What is an attribute in Java?

Attributes is same term used alternativly for properties or fields or data members or class members.

How to update attributes without validation

try using

@record.assign_attributes({ ... })
@record.save(validate: false)

works for me

Relationship between hashCode and equals method in Java

Yes, it should be overridden. If you think you need to override equals(), then you need to override hashCode() and vice versa. The general contract of hashCode() is:

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Add a new column to existing table in a migration

If you're using Laravel 5, the command would be;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.

php artisan migrate is still the same though.

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

Using RegEX To Prefix And Append In Notepad++

In visual studio code i found that simple regex as ^ worked.

In C# check that filename is *possibly* valid (not that it exists)

I don't know of anything out of the box that can just validate all of that for you, however the Path class in .NET can help you out tremendously.

For starters, it has:

char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters

or:

Path.GetPathRoot(string); // will return the root.

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How can I use a carriage return in a HTML tooltip?

use data-html="true" and apply <br>.

Java "user.dir" property - what exactly does it mean?

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

Calculating the angle between the line defined by two points

A few answers here have tried to explain the "screen" issue where top left is 0,0 and bottom right is (positive) screen width, screen height. Most grids have the Y axis as positive above X not below.

The following method will work with screen values instead of "grid" values. The only difference to the excepted answer is the Y values are inverted.

/**
 * Work out the angle from the x horizontal winding anti-clockwise 
 * in screen space. 
 * 
 * The value returned from the following should be 315. 
 * <pre>
 * x,y -------------
 *     |  1,1
 *     |    \
 *     |     \
 *     |     2,2
 * </pre>
 * @param p1
 * @param p2
 * @return - a double from 0 to 360
 */
public static double angleOf(PointF p1, PointF p2) {
    // NOTE: Remember that most math has the Y axis as positive above the X.
    // However, for screens we have Y as positive below. For this reason, 
    // the Y values are inverted to get the expected results.
    final double deltaY = (p1.y - p2.y);
    final double deltaX = (p2.x - p1.x);
    final double result = Math.toDegrees(Math.atan2(deltaY, deltaX)); 
    return (result < 0) ? (360d + result) : result;
}

Why do I have ORA-00904 even when the column is present?

Its due to mismatch between column name defined in entity and the column name of table (in SQL db )

java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier e.g.java.sql.SQLException: ORA-00904: "STUDENT"."NAME": invalid identifier

issue can be like in Student.java(entity file) 
You have mentioned column name as "NAME" only.
But in STUDENT table ,column name is lets say "NMAE"

jquery ui Dialog: cannot call methods on dialog prior to initialization

I got this error message because I had the div tag on the partial view instead of the parent view

How do I get first name and last name as whole name in a MYSQL query?

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

As everyone else has said, there isn't one in html; however, you could use PUG/Jade. In fact I do this often.

It would look something like this:

select
  - var i = 1
  while i <= 100
    option=i++

This would produce: screenshot of htmltojade.org

Kotlin unresolved reference in IntelliJ

For me, it was due to the project missing Gradle Libraries in its project structure.

Just add in build.gradle: apply plugin: 'idea'

And then run: $ gradle idea

After that gradle rebuilds dependencies libraries and the references are recognized!

Show all current locks from get_lock

If you just want to determine whether a particular named lock is currently held, you can use IS_USED_LOCK:

SELECT IS_USED_LOCK('foobar');

If some connection holds the lock, that connection's ID will be returned; otherwise, the result is NULL.

How to check if a file exists in Go?

Let's look at few aspects first, both the function provided by os package of golang are not utilities but error checkers, what do I mean by that is they are just a wrapper to handle errors on cross platform.

So basically if os.Stat if this function doesn't give any error that means the file is existing if it does you need to check what kind of error it is, here comes the use of these two function os.IsNotExist and os.IsExist.

This can be understood as the Stat of the file throwing error because it doesn't exists or is it throwing error because it exist and there is some problem with it.

The parameter that these functions take is of type error, although you might be able to pass nil to it but it wouldn't make sense.

This also points to the fact that IsExist is not same as !IsNotExist, they are way two different things.

So now if you want to know if a given file exist in go, I would prefer the best way is:

if _, err := os.Stat(path/to/file); !os.IsNotExist(err){
   //TODO
} 

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

Download TS files from video stream

---> Open Firefox

---> open page the video

---> Play Video

Click ---> Open menu

Click ---> open web developer tools

Click ---> Developer Toolbar

Click ---> Network

---> Go to Filter URLs ---> Write "M3u8" --> for Find "m3u8"

---> Copy URL ".m3u8"

========================

Now Download software "m3u8x" ----> https://tajaribsoft-en.blogspot.com/2016/06/m3u8x.html#downloadx12

---> open software "m3u8x"

---> paste URL "m3u8"

---> chose option "One...One"

---> Click Download

---> Start Download

========================

image "Open menu" ===>

a busy cat

image "Developer Toolbar" ===>

a busy cat

image "m3u8x" ===>

enter image description here

enter image description here

Flutter - Layout a Grid

A simple example loading images into the tiles.

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(

      color: Colors.white30,
      child: GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          padding: const EdgeInsets.all(4.0),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          children: <String>[
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
          ].map((String url) {
            return GridTile(
                child: Image.network(url, fit: BoxFit.cover));
          }).toList()),
    );
  }
}

The Flutter Gallery app contains a real world example, which can be found here.

enter image description here

spacing between form fields

I would wrap your rows in labels

<form action="doit" id="doit" method="post">
    <label>
        Name
        <input id="name" name="name" type="text" />
    </label>
    <label>
        Phone number
        <input id="phone" name="phone" type="text" />
    </label>
    <label>
        Year
        <input id="year" name="year" type="text" />
    </label>
</form>

And use

label, input {
    display: block;
}

label {
    margin-bottom: 20px;
}

Don't use brs for spacing!

Demo: http://jsfiddle.net/D8W2Q/

Bootstrap 3 collapsed menu doesn't close on click

All you need is data-target=".navbar-collapse" in the button, nothing else.

<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
</button>

Converting array to list in Java

It seems little late but here are my two cents. We cannot have List<int> as int is a primitive type so we can only have List<Integer>.

Java 8 (int array)

int[] ints = new int[] {1,2,3,4,5};
List<Integer> list11 =Arrays.stream(ints).boxed().collect(Collectors.toList()); 

Java 8 and below (Integer array)

Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 =  Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only

Need ArrayList and not List?

In case we want a specific implementation of List e.g. ArrayList then we can use toCollection as:

ArrayList<Integer> list24 = Arrays.stream(integers)
                          .collect(Collectors.toCollection(ArrayList::new));

Why list21 cannot be structurally modified?

When we use Arrays.asList the size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationException will be thrown. So we should go with list22 when we want to modify the list. If we have Java8 then we can also go with list23.

To be clear list21 can be modified in sense that we can call list21.set(index,element) but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.


If we want an immutable list then we can wrap it as:

List<Integer> list22 = Collections.unmodifiableList(Arrays.asList(integers));

Another point to note is that the method Collections.unmodifiableList returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.

We can have a truly immutable list in Java 9 and 10.

Truly Immutable list

Java 9:

String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);

Java 10 (Truly Immutable list):

We can use List.of introduced in Java 9. Also other ways:

  1. List.copyOf(Arrays.asList(integers))
  2. Arrays.stream(integers).collect(Collectors.toUnmodifiableList());

Bluetooth pairing without user confirmation

Well, this should really be broken into 2 parts:

  1. Can you pair 2 Bluetooth devices without going through a Bluetooth pairing handshake? No, you can't. That's baked into the protocol so there is no way around this.
  2. Can you perform the handshake without a user interface? Yes, you can: that's just code.

I'm not sure how you do it in Windows land, but in *nix land there are functions buried in the Bluez stack that let you receive notifications about when a new device appears, and send it the pairing code (clearly there have to be these functions: those are what the user interface use). Given sufficient time and experience I'm sure you could figure out how to write your own version of the Bluetooth Settings app that somehow:

  • Detected a new device had arrived
  • Looked at the name/bluetooth mac address and checked some internal database for the pairing code to use.
  • Sent the pairing code and completed the operation

All without having to pop up a user interface.

If you go ahead and write the code I'd LOVE to get my hands on it.

Is there a "do ... until" in Python?

There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:

import itertools

def dowhile(predicate):
  it = itertools.repeat(None)
  for _ in it:
    yield
    if not predicate(): break

so, for example:

i=7; j=3
for _ in dowhile(lambda: i<j):
  print i, j
  i+=1; j-=1

executes one leg, as desired, even though the predicate's already false at the start.

It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:

def incandec(i, j, delta=1):
  while True:
    yield i, j
    if j <= i: break
    i+=delta; j-=delta

which you can use like:

for i, j in incandec(i=7, j=3):
  print i, j

It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).

How do I create a file at a specific path?

The besty practice is to use '/' and a so called 'raw string' to define file path in Python.

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

tSQL - Conversion from varchar to numeric works for all but integer

Presumably, you want to convert values before the decimal place to an integer. If so, use case and check for the right format:

SELECT (case when varcharcol not like '%.%' then cast(varcharcol as int)
             else cast(left(varcharcol, chardindex('.', varcharcol) - 1) as int)
        end) IntVal
FROM MyTable;

Best way to detect when a user leaves a web page?

I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:

window.onbeforeunload = function (e) {
        if ((window.event.clientY < 0)) {
            //window.localStorage.clear();
            //alert("Y coords: " + window.event.clientY)
        }
};

In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.

Saving image to file

You could try to save the image using this approach

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   int width = Convert.ToInt32(drawImage.Width); 
   int height = Convert.ToInt32(drawImage.Height); 
   Bitmap bmp = new Bitmap(width,height);        
   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);
   bmp.Save(dialog.FileName, ImageFormat.Jpeg);
}

Call angularjs function using jquery/javascript

Solution provide in the questions which you linked is correct. Problem with your implementation is that You have not specified the ID of element correctly.

Secondly you need to use load event to execute your code. Currently DOM is not loaded hence element is not found thus you are getting error.

HTML

<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
    Hi
</div>

JS Code

angular.module('MyModule', [])
    .controller('MyController', function ($scope) {
    $scope.myfunction = function (data) {
        alert("---" + data);
    };
});

window.onload = function () {
    angular.element(document.getElementById('YourElementId')).scope().myfunction('test');
}

DEMO

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Ignore 'Security Warning' running script from command line

It is very simple to do, open your PowerShell and write the following command if you have number of ps1 files. here you have to change the path with your path.

PS C:\Users> Get-ChildItem -Path "D:\downlod" -Recurse | Unblock-File

Redis - Connect to Remote Server

In addition to the excellent answer given by Orabîg:

I resolved this issue by removing the bind section entirely and setting protected-mode to no.

#bind 127.0.0.1
protected-mode no

Never use this method on publicly exposed servers.

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Get safe area inset top and bottom heights

Swift 5, Xcode 11.4

`UIApplication.shared.keyWindow` 

It will give deprecation warning. ''keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes' because of connected scenes. I use this way.

extension UIView {

    var safeAreaBottom: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.bottom
            }
         }
         return 0
    }

    var safeAreaTop: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.top
            }
         }
         return 0
    }
}

extension UIApplication {
    var keyWindowInConnectedScenes: UIWindow? {
        return windows.first(where: { $0.isKeyWindow })
    }
}

Purpose of a constructor in Java?

As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.

Example:

Say you have an Animal class something like

class Animal{
   private String name;
   private String type;
}

Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like

    Animal(String nameProvided, String typeProvided){
         this.name = nameProvided;
         this.type = typeProvided;
     }

Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.

Now you might ask what if I didn't provide an argument to my constructor something like

Animal xyz = new Animal();

This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null

Is there a way to make npm install (the command) to work behind proxy?

After tying different answers finally, @Kayvar answers's first four lines help me to solve the issue:

npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:[email protected]:8080
npm config set https-proxy http://myusername:[email protected]:8080
npm config set strict-ssl false

What's the difference between a method and a function?

From my understanding a method is any operation which can be performed on a class. It is a general term used in programming.

In many languages methods are represented by functions and subroutines. The main distinction that most languages use for these is that functions may return a value back to the caller and a subroutine may not. However many modern languages only have functions, but these can optionally not return any value.

For example, lets say you want to describe a cat and you would like that to be able to yawn. You would create a Cat class, with a Yawn method, which would most likely be a function without any return value.

Unicode character for "X" cancel / close?

Using modern browsers you can rotate a + sign:

.popupClose:before {
    content:'+';
}
.popupClose {
    position:relative;
    float:right;
    right:10px;
    top:0px;
    padding:2px;
    cursor:pointer;
    margin:2px;
    color:grey;
    font-size:32pt;
    transform:rotate(45deg);
}

then simply place the following html where you need:

 <span class='popupClose'></span>

'NOT NULL constraint failed' after adding to models.py

You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True and create and run migration.

Jquery onclick on div

Make sure it's within a document ready tagAlternatively, try using .live

$(document).ready(function(){

    $('#content').live('click', function(e) {  
        alert(1);
    });
});

Example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $('#content').click(function(e) {  _x000D_
      alert(1);_x000D_
    });_x000D_
});
_x000D_
#content {_x000D_
    padding: 20px;_x000D_
    background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
_x000D_
_x000D_

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$('#content').on( "click", function() {
    alert(1);
});

Android ViewPager with bottom dots

Here is how I did this, somewhat similar to the solutions above. Just make sure you call the loadDots() method after all images are downloaded.

    private int dotsCount;
    private TextView dotsTextView[];

    private void setupAdapter() {
        adapter = new SomeAdapter(getContext(), images);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
    }

    private final ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < dotsCount; i++)
                dotsTextView[i].setTextColor(Color.GRAY);

            dotsTextView[position].setTextColor(Color.WHITE);
        }

        @Override
        public void onPageScrollStateChanged(int state) {}
    };

    protected void loadDots() {
        dotsCount = adapter.getCount();
        dotsTextView = new TextView[dotsCount];
        for (int i = 0; i < dotsCount; i++) {
            dotsTextView[i] = new TextView(getContext());
            dotsTextView[i].setText(R.string.dot);
            dotsTextView[i].setTextSize(45);
            dotsTextView[i].setTypeface(null, Typeface.BOLD);
            dotsTextView[i].setTextColor(android.graphics.Color.GRAY);
            mDotsLayout.addView(dotsTextView[i]);
        }
        dotsTextView[0].setTextColor(Color.WHITE);
    }

XML

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:background="#00000000"/>


    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/introImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/image_count"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00000000"
        android:gravity="center|bottom"
        android:orientation="horizontal"/>
</FrameLayout>

How to clear react-native cache?

Here's a great discussion on GitHub which helped me a lot. Clearing the Cache of your React Native Project by Jarret Moses

There are solutions for 4 different instances.

  1. RN <0.50 -
    watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  2. RN >=0.50 - watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  3. NPM >=5 - watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache
  4. Windows - del %appdata%\Temp\react-native-* & cd android & gradlew clean & cd .. & del node_modules/ & npm cache clean --force & npm install & npm start -- --reset-cache

The solution is similar to Vikram Biwal's Answer.

And there is a discussion below in the given link, so even if the above 4 cases don't work for you, you can scroll through and find a possible solution.

css ellipsis on second line

What a shame that you can't get it to work over two lines! Would be awesome if the element was display block and had a height set to 2em or something, and when the text overflowed it would show an ellipsis!

For a single liner you can use:

.show-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

For multiple lines maybe you could use a Polyfill such as jQuery autoellipsis which is on github http://pvdspek.github.com/jquery.autoellipsis/

How to get the values of a ConfigurationSection of type NameValueSectionHandler

The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.

Seems pretty inefficient, but there you go.

I wrote an extension method to encapsulate this:

public static class ConfigurationSectionExtensions
{
    public static T GetAs<T>(this ConfigurationSection section)
    {
        var sectionInformation = section.SectionInformation;

        var sectionHandlerType = Type.GetType(sectionInformation.Type);
        if (sectionHandlerType == null)
        {
            throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
        }

        IConfigurationSectionHandler sectionHandler;
        try
        {
            sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
        }
        catch (InvalidCastException ex)
        {
            throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
        }

        var rawXml = sectionInformation.GetRawXml();
        if (rawXml == null)
        {
            return default(T);
        }

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(rawXml);

        return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
    }
}

The way you would call it in your example is:

var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();

How do I create an Android Spinner as a popup?

Adding a small attribute as android:spinnerMode="dialog" would show the spinner contents in a pop-up.

What is the difference between g++ and gcc?

gcc and g ++ are both GNU compiler. They both compile c and c++. The difference is for *.c files gcc treats it as a c program, and g++ sees it as a c ++ program. *.cpp files are considered to be c ++ programs. c++ is a super set of c and the syntax is more strict, so be careful about the suffix.

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

PHP: How do you determine every Nth iteration of a loop?

Use the modulo arithmetic operation found here in the PHP manual.

e.g.

$x = 3;

for($i=0; $i<10; $i++)
{
    if($i % $x == 0)
    {
        // display image
    }
}

For a more detailed understanding of modulus calculations, click here.

Should I declare Jackson's ObjectMapper as a static field?

Although ObjectMapper is thread safe, I would strongly discourage from declaring it as a static variable, especially in multithreaded application. Not even because it is a bad practice, but because you are running a heavy risk of deadlocking. I am telling it from my own experience. I created an application with 4 identical threads that were getting and processing JSON data from web services. My application was frequently stalling on the following command, according to the thread dump:

Map aPage = mapper.readValue(reader, Map.class);

Beside that, performance was not good. When I replaced static variable with the instance based variable, stalling disappeared and performance quadrupled. I.e. 2.4 millions JSON documents were processed in 40min.56sec., instead of 2.5 hours previously.

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

How to get the current taxonomy term ID (not the slug) in WordPress?

<?php 
$terms = get_the_terms( $post->ID, 'taxonomy');
foreach ( $terms as $term ) {
    $termID[] = $term->term_id;
}
echo $termID[0]; 
?>

check if variable empty

To check for null values you can use is_null() as is demonstrated below.

if (is_null($value)) {
   $value = "MY TEXT"; //define to suit
}

No log4j2 configuration file found. Using default configuration: logging only errors to the console

i had same problem, but i noticed that i have no log4j2.xml in my project after reading on the net about this problem, so i copied the related code in a notepad and reverted the notepad file to xml and add to my project under the folder resources. it works for me.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
  <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="DEBUG">
  <AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

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

And you can't use valueOf()?

Edit: Btw, there is nothing stopping you from using static { } in an enum.

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

How to determine the encoding of text?

If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)

SyntaxError: Unexpected Identifier in Chrome's Javascript console

copy this line and replace in your project

var myNewString = myOldString.replace ("username", visitorName);

there is a simple problem with coma (,)

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

How to sort in-place using the merge sort algorithm?

There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.

There are also links to more detailed theoretical analysis by the same author associated with this link.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit(1)
    else:
        # got a message, do something :)

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n) or socket.setblocking(False). In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)

while True:
    try:
        msg = s.recv(4096)
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep(1)
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit(1)
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit(1)
    else:
        if len(msg) == 0:
            print 'orderly shutdown on server end'
            sys.exit(0)
        else:
            # got a message do something :)

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv(2) and python socket for more details.

How to check if android checkbox is checked within its onClick method (declared in XML)?

This will do the trick:

  public void itemClicked(View v) {
    if (((CheckBox) v).isChecked()) {
        Toast.makeText(MyAndroidAppActivity.this,
           "Checked", Toast.LENGTH_LONG).show();
    }
  }

How to install a package inside virtualenv?

Sharing a personal case if it helps. It is that a virtual environment was previously arranged. Its path can be displayed by

echo $VIRTUAL_ENV

Make sure that the it is writable to the current user. If not, using

sudo ipython

would certainly clear off the warning message.

In anaconda, if $VIRTUAL_ENV is independently arranged, one can simply delete this folder or rename it, and then restart the shell. Anaconda will recover to its default setup.

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

Regex - how to match everything except a particular pattern

The complement of a regular language is also a regular language, but to construct it you have to build the DFA for the regular language, and make any valid state change into an error. See this for an example. What the page doesn't say is that it converted /(ac|bd)/ into /(a[^c]?|b[^d]?|[^ab])/. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before.

How to redirect to another page using PHP

On click BUTTON action

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

Why are there two ways to unstage a file in Git?

I'm surprised noone mentioned the git reflog (http://git-scm.com/docs/git-reflog):

# git reflog
<find the place before your staged anything>
# git reset HEAD@{1}

The reflog is a git history that not only tracks the changes to the repo, but also tracks the user actions (Eg. pull, checkout to different branch, etc) and allows to undo those actions. So instead of unstaging the file that was mistakingly staged, where you can revert to the point where you didn't stage the files.

This is similar to git reset HEAD <file> but in certain cases may be more granular.

Sorry - not really answering your question, but just pointing yet another way to unstage files that I use quite often (I for one like answers by Ryan Stewart and waldyrious very much.) ;) I hope it helps.

Git - How to close commit editor?

You Just clicking the key.

first press ESC + enter and then press :x + enter

How do I convert a String to an InputStream in Java?

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

In Python, how do I split a string and keep the separators?

Here is a simple .split solution that works without regex.

This is an answer for Python split() without removing the delimiter, so not exactly what the original post asks but the other question was closed as a duplicate for this one.

def splitkeep(s, delimiter):
    split = s.split(delimiter)
    return [substr + delimiter for substr in split[:-1]] + [split[-1]]

Random tests:

import random

CHARS = [".", "a", "b", "c"]
assert splitkeep("", "X") == [""]  # 0 length test
for delimiter in ('.', '..'):
    for _ in range(100000):
        length = random.randint(1, 50)
        s = "".join(random.choice(CHARS) for _ in range(length))
        assert "".join(splitkeep(s, delimiter)) == s

Setting the selected value on a Django forms.ChoiceField

This doesn't touch on the immediate question at hand, but this Q/A comes up for searches related to trying to assign the selected value to a ChoiceField.

If you have already called super().__init__ in your Form class, you should update the form.initial dictionary, not the field.initial property. If you study form.initial (e.g. print self.initial after the call to super().__init__), it will contain values for all the fields. Having a value of None in that dict will override the field.initial value.

e.g.

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # assign a (computed, I assume) default value to the choice field
        self.initial['choices_field_name'] = 'default value'
        # you should NOT do this:
        self.fields['choices_field_name'].initial = 'default value'

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

Your database, that apparently has the ORACLE_SID XE, is not defined in the listener.ora. That is no problem, since when the database normally opens, it will register itself to the default listener, being the one on port 1521 so that is ok.

  1. is the database open?
  2. what is the start order of listener/database?
  3. is the error persistent?

If the database starts before the listener, the database has no listener to register to. It will do so every few minutes so after a while, I expect the error will go away because of the registration has taken place. You can issue alter system register; to speed this. If the database is in restricted mode, the connections using a service will fail. You are using ORACLE_SID so that is not your problem.

Also check the names in use. Is localhost resolving to the same address as Brodyaga-PC? In the jdbc string you use localhost and the listener listens om Brodyaga-PC. Is localhost 127.0.0.1 ?