Programs & Examples On #Repaint

Repaint refers to issues relating to re-rendering or redrawing user interface screens or portions of those screens.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

CSS scale down image to fit in containing div, without specifing original size

Hope this will answer the age old problem (Without using CSS background property)

Html

<div class="card-cont">
 <img src="demo.png" />
</div>

Css

.card-cont{
  width:100%;
  height:150px;
}

.card-cont img{
  max-width: 100%;
  min-width: 100%;
  min-height: 150px;
}

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

how to check if input field is empty

use .val(), it will return the value of the <input>

$("#spa").val().length > 0

And you had a typo, length not lenght.

Python list of dictionaries search

You can achieve this with the usage of filter and next methods in Python.

filter method filters the given sequence and returns an iterator. next method accepts an iterator and returns the next element in the list.

So you can find the element by,

my_dict = [
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5},
    {"name": "Pam", "age": 7}
]

next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)

and the output is,

{'name': 'Pam', 'age': 7}

Note: The above code will return None incase if the name we are searching is not found.

bash: npm: command not found?

If you have already installed nodejs and still getting this error. npm: command not found..

run this

apt-get install -y npm

Customize list item bullets using CSS

I just found a solution that I think works really well and gets around all of the pitfalls of custom symbols. The main problem with the li:before solution is that if list-items are longer than one line will not indent properly after the first line of text. By using text-indent with a negative padding we can circumvent that problem and have all the lines aligned properly:

ul{
    padding-left: 0; // remove default padding
}

li{
    list-style-type: none;  // remove default styles
    padding-left: 1.2em;    
    text-indent:-1.2em;     // remove padding on first line
}

li::before{
    margin-right:     0.5em; 
    width:            0.7em; // margin-right and width must add up to the negative indent-value set above
    height:           0.7em;

    display:          inline-block;
    vertical-align:   middle;
    border-radius: 50%;
    background-color: orange;
    content:          ' '
}

Can you disable tabs in Bootstrap?

Old question but it kind of pointed me in the right direction. The method I went for was to add the disabled class to the li and then added the following code to my Javascript file.

$('.nav-tabs li.disabled > a[data-toggle=tab]').on('click', function(e) {
    e.stopImmediatePropagation();
});

This will disable any link where the li has a class of disabled. Kind of similar to totas's answer but it won't run the if every time a user clicks any tab link and it doesn't use return false.

Hopefully it'll be useful to someone!

Where are Docker images stored on the host machine?

Expanding on Tristan's answer, in Windows with Hyper-V you can move the image with these steps from matthuisman:

In Windows 10,

  1. Stop docker etc
  2. Type "Hyper-V Manager" in task-bar search box and run it.
  3. Select your PC in the left hand pane (Mine is called DESKTOP-CBP**)
  4. Right click on the correct virtual machine (Mine is called MobyLinuxVM)
  5. Select "Turn off" (If it is running)
  6. Right click on it again and select "Move"
  7. Follow the prompts

FromBody string parameter is giving null

When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:

"test"

Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers

Similar answer string value is Empty when using FromBody in asp.net web api

 

How can I search sub-folders using glob.glob module?

Here is a adapted version that enables glob.glob like functionality without using glob2.

def find_files(directory, pattern='*'):
    if not os.path.exists(directory):
        raise ValueError("Directory not found {}".format(directory))

    matches = []
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            full_path = os.path.join(root, filename)
            if fnmatch.filter([full_path], pattern):
                matches.append(os.path.join(root, filename))
    return matches

So if you have the following dir structure

tests/files
+-- a0
¦   +-- a0.txt
¦   +-- a0.yaml
¦   +-- b0
¦       +-- b0.yaml
¦       +-- b00.yaml
+-- a1

You can do something like this

files = utils.find_files('tests/files','**/b0/b*.yaml')
> ['tests/files/a0/b0/b0.yaml', 'tests/files/a0/b0/b00.yaml']

Pretty much fnmatch pattern match on the whole filename itself, rather than the filename only.

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

How to call a View Controller programmatically?

Swift

This gets a view controller from the storyboard and presents it.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller name, and view controller id as appropriate.

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

Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>.

It allows you to pass in an IEntitySorter<T> into your service methods and use it like this:

public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
    using (var db = ContextFactory.CreateContext())
    {
        IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);

        return sortedList.ToArray();
    }
}

And you can create an EntitiySorter like this:

IEntitySorter<Person> sorter = EntitySorter<Person>
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Id);

Or like this:

var sorter = EntitySorter<Person>
     .OrderByDescending("Address.City")
     .ThenBy("Id");

Compiled vs. Interpreted Languages

The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.

Android TabLayout Android Design

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:app="http://schemas.android.com/apk/res-auto"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/main_content"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    android:fitsSystemWindows="true"_x000D_
    tools:context=".ui.MainActivity"_x000D_
    >_x000D_
    <android.support.design.widget.AppBarLayout_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">_x000D_
_x000D_
        <android.support.v7.widget.Toolbar_x000D_
            android:id="@+id/toolbar"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            android:layout_alignParentTop="true"_x000D_
            android:background="?attr/colorPrimary"_x000D_
            android:elevation="6dp"_x000D_
            android:minHeight="?attr/actionBarSize"_x000D_
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"_x000D_
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />_x000D_
_x000D_
        <android.support.design.widget.TabLayout_x000D_
            android:id="@+id/tabs"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            app:tabMode="fixed"_x000D_
            app:tabGravity="fill"_x000D_
            >_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_1" />_x000D_
_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem2"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_2" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem3"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_3" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tItemab4"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_4" />_x000D_
        </android.support.design.widget.TabLayout>_x000D_
    </android.support.design.widget.AppBarLayout>_x000D_
    <android.support.v4.view.ViewPager_x000D_
        android:id="@+id/container"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_below="@id/tabs"_x000D_
        app:layout_behavior="@string/appbar_scrolling_view_behavior"_x000D_
        tools:ignore="NotSibling"/>_x000D_
</android.support.constraint.ConstraintLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/activity_main"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    tools:context=".ui.MainActivity">_x000D_
    <include layout="@layout/tabs"></include>_x000D_
    <LinearLayout_x000D_
        android:orientation="vertical"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_marginBottom="@dimen/activity_vertical_margin"_x000D_
        android:layout_marginLeft="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginRight="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginTop="80dp">_x000D_
        <FrameLayout android:id="@+id/tabContent"_x000D_
            android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">_x000D_
        </FrameLayout>_x000D_
    </LinearLayout>_x000D_
</RelativeLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
public class MainActivity extends  AppCompatActivity{_x000D_
_x000D_
  private Toolbar toolbar;_x000D_
    private TabLayout tabLayout;_x000D_
    private ViewPagerAdapter adapter;_x000D_
_x000D_
    private final static int[] tabIcons = {_x000D_
            R.drawable.ic_action_car,_x000D_
            android.R.drawable.ic_menu_mapmode,_x000D_
            android.R.drawable.ic_dialog_email,_x000D_
            R.drawable.ic_action_settings_x000D_
    };_x000D_
_x000D_
protected void onCreate(Bundle savedInstanceState) {_x000D_
        super.onCreate(savedInstanceState);_x000D_
        setContentView(R.layout.activity_main);_x000D_
        _x000D_
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);_x000D_
       setSupportActionBar(toolbar);_x000D_
_x000D_
        ViewPager viewPager = (ViewPager)         findViewById(R.id.container);_x000D_
        setupViewPager(viewPager);_x000D_
_x000D_
_x000D_
        tabLayout = (TabLayout) findViewById(R.id.tabs);_x000D_
        tabLayout.setupWithViewPager(viewPager);_x000D_
        setupTabIcons();_x000D_
_x000D_
        _x000D_
        }_x000D_
            private void setupTabIcons() {_x000D_
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);_x000D_
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);_x000D_
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);_x000D_
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);_x000D_
    }_x000D_
_x000D_
    private void setupViewPager(ViewPager viewPager) {_x000D_
        adapter = new ViewPagerAdapter(getSupportFragmentManager());_x000D_
        adapter.addFrag(new CarFragment());_x000D_
        adapter.addFrag(new LocationFragment());_x000D_
        adapter.addFrag(new MessageFragment());_x000D_
        adapter.addFrag(new SettingsFragment());_x000D_
        viewPager.setAdapter(adapter);_x000D_
    }_x000D_
    _x000D_
    class ViewPagerAdapter extends FragmentPagerAdapter {_x000D_
        private final List<Fragment> mFragmentList = new ArrayList<>();_x000D_
        ViewPagerAdapter(FragmentManager manager) {_x000D_
            super(manager);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public Fragment getItem(int position) {_x000D_
            return mFragmentList.get(position);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public int getCount() {_x000D_
            return mFragmentList.size();_x000D_
        }_x000D_
_x000D_
        void addFrag(Fragment fragment) {_x000D_
            mFragmentList.add(fragment);_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
        }
_x000D_
_x000D_
_x000D_

How can I programmatically get the MAC address of an iphone


NOTE As of iOS7, you can no longer retrieve device MAC addresses. A fixed value will be returned rather than the actual MAC


Somthing I stumbled across a while ago. Originally from here I modified it a bit and cleaned things up.

IPAddress.h
IPAddress.c

And to use it

InitAddresses();
GetIPAddresses();
GetHWAddresses();

int i;
NSString *deviceIP = nil;
for (i=0; i<MAXADDRS; ++i)
{
    static unsigned long localHost = 0x7F000001;        // 127.0.0.1
    unsigned long theAddr;

    theAddr = ip_addrs[i];

    if (theAddr == 0) break;
    if (theAddr == localHost) continue;

    NSLog(@"Name: %s MAC: %s IP: %s\n", if_names[i], hw_addrs[i], ip_names[i]);

        //decided what adapter you want details for
    if (strncmp(if_names[i], "en", 2) == 0)
    {
        NSLog(@"Adapter en has a IP of %s", ip_names[i]);
    }
}

Adapter names vary depending on the simulator/device as well as wifi or cell on the device.

jQuery - how can I find the element with a certain id?

This is one more option to find the element for above question

$("#tbIntervalos").find('td[id="'+horaInicial+'"]')

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Heroku deployment error H10 (App crashed)

I had this problem when trying to run Rails in a subdirectory, and not in /. For example, I had Angular/Node/Gulp app running in /client and a Rails app running in /server, but both of them were in the same git repo, so I could track changes across the front end and back end. I got this error when trying to deploy them to Heroku. For anyone else having this issue, here is a custom buildpack that will allow running Rails in a subdirectory.

https://github.com/aarongray/heroku-buildpack-ruby

How can I String.Format a TimeSpan object with a custom format in .NET?

If you want the duration format similar to youtube, given the number of seconds

int[] duration = { 0, 4, 40, 59, 60, 61, 400, 4000, 40000, 400000 };
foreach (int d in duration)
{
    Console.WriteLine("{0, 6} -> {1, 10}", d, d > 59 ? TimeSpan.FromSeconds(d).ToString().TrimStart("00:".ToCharArray()) : string.Format("0:{0:00}", d));
}

Output:

     0 ->       0:00
     4 ->       0:04
    40 ->       0:40
    59 ->       0:59
    60 ->       1:00
    61 ->       1:01
   400 ->       6:40
  4000 ->    1:06:40
 40000 ->   11:06:40
400000 -> 4.15:06:40

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

Multiple Where clauses in Lambda expressions

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)

or

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)

How to linebreak an svg text within javascript?

use HTML instead of javascript

_x000D_
_x000D_
<html>_x000D_
  <head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
  <body>_x000D_
    <h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
    <svg_x000D_
      xmlns="http://www.w3.org/2000/svg"_x000D_
      viewBox="0 0 300 300"_x000D_
      x="0" y="0" height="300" width="300"_x000D_
    >_x000D_
_x000D_
      <circle_x000D_
        r="142" cx="150" cy="150"_x000D_
        fill="none" stroke="#000000" stroke-width="2"_x000D_
      />_x000D_
_x000D_
      <foreignObject_x000D_
        x="50" y="50" width="200" height="200"_x000D_
      >_x000D_
        <div_x000D_
          xmlns="http://www.w3.org/1999/xhtml"_x000D_
          style="_x000D_
            width: 196px; height: 196px;_x000D_
            border: solid 2px #000000;_x000D_
            font-size: 32px;_x000D_
            overflow: auto; /* scroll */_x000D_
          "_x000D_
        >_x000D_
          <p>this is html in svg 1</p>_x000D_
          <p>this is html in svg 2</p>_x000D_
          <p>this is html in svg 3</p>_x000D_
          <p>this is html in svg 4</p>_x000D_
        </div>_x000D_
      </foreignObject>_x000D_
_x000D_
    </svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.

If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.

If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.

More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html

New Array from Index Range Swift

subscript

extension Array where Element : Equatable {
  public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
    if bounds.lowerBound > count { return [] }
    let lower = Swift.max(0, bounds.lowerBound)
    let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
    return self[lower..<upper]
  }
  
  public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
    let lower = lower ?? 0
    let upper = upper ?? count
    if lower > upper { return [] }
    return self[safe: lower..<upper]
  }
}

returns a copy of this range clamped to the given limiting range.

var arr = [1, 2, 3]
    
arr[safe: 0..<1]    // returns [1]  assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100]  // returns [3]  assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns []   assert(arr[safe: -100..<0] == [])

arr[safe: 0, 1]     // returns [1]  assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100]   // returns [3]  assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0]  // returns []   assert(arr[safe: -100, 0] == [])

How to get the url parameters using AngularJS

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'
});

Then in your controller inject $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;
  ...
}]);

With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"

Why doesn't CSS ellipsis work in table cell?

It's also important to put

table-layout:fixed;

Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.

Simple way to query connected USB devices info in Python?

I can think of a quick code like this.

Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device >

For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same.

import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
print devices

Sample output here will be:

[
{'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'},
{'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'},
{'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'},
{'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'}
]

Code Updated for Python 3

import re
import subprocess
device_re = re.compile(b"Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split(b'\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
            
print(devices)

selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)

Error

The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

Redirect output of mongo query to a csv file

Have a look at this

for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.

Eclipse Intellisense?

I once had the same problem, and then I searched and found this and it worked for me:

I had got some of the boxes unchecked, so I checked them again, then it worked. Just go to

Windows > Preferences > Java > Editor > Content Assist > Advanced

and check the boxes which you want .

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

How to hide column of DataGridView when using custom DataSource?

If you want to use the BrowsableAttribute, then you can look for it at runtime on the model and hide the column accordingly:

private void Form_Load(object sender, EventArgs e)
{
    //add this line after your DataGridView initialization
    HideColumns<MyModel>(myDvg);
}

private void HideColumns<T>(DataGridView dvg)
{
    var type = typeof(T);
    foreach (var column in dvg.Columns.Cast<DataGridViewColumn>())
        column.Visible = IsBrowsable(type.GetProperty(column.Name));
}

private bool IsBrowsable(PropertyInfo propertyInfo)
{
    var attribute = propertyInfo.GetCustomAttributes(true).FirstOrDefault(att => att.GetType() == typeof(BrowsableAttribute));
    return attribute == null || (attribute as BrowsableAttribute).Browsable;
}

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

Test if a string contains a word in PHP?

If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'

$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
 }

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

How to check if a windows form is already open, and close it if it is?

Form1 fc = Application.OpenForms["Form1 "] != null ? (Form1 ) Application.OpenForms["Form1 "] : null;
if (fc != null)
{
    fc.Close();
}

It will close the form1 you can open that form again if you want it using :

Form1 frm = New Form1();
frm.show();

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

Bootstrap 3 - set height of modal window according to screen size

Pure CSS solution, using calc

.modal-body {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

200px may be adjusted in accordance to height of header & footer

How to serialize an Object into a list of URL query parameters?

If you need a recursive function that will produce proper URL parameters based on the object given, try my Coffee-Script one.

@toParams = (params) ->
    pairs = []
    do proc = (object=params, prefix=null) ->
      for own key, value of object
        if value instanceof Array
          for el, i in value
            proc(el, if prefix? then "#{prefix}[#{key}][]" else "#{key}[]")
        else if value instanceof Object
          if prefix?
            prefix += "[#{key}]"
          else
            prefix = key
          proc(value, prefix)
        else
          pairs.push(if prefix? then "#{prefix}[#{key}]=#{value}" else "#{key}=#{value}")
    pairs.join('&')

or the JavaScript compiled...

toParams = function(params) {
  var pairs, proc;
  pairs = [];
  (proc = function(object, prefix) {
    var el, i, key, value, _results;
    if (object == null) object = params;
    if (prefix == null) prefix = null;
    _results = [];
    for (key in object) {
      if (!__hasProp.call(object, key)) continue;
      value = object[key];
      if (value instanceof Array) {
        _results.push((function() {
          var _len, _results2;
          _results2 = [];
          for (i = 0, _len = value.length; i < _len; i++) {
            el = value[i];
            _results2.push(proc(el, prefix != null ? "" + prefix + "[" + key + "][]" : "" + key + "[]"));
          }
          return _results2;
        })());
      } else if (value instanceof Object) {
        if (prefix != null) {
          prefix += "[" + key + "]";
        } else {
          prefix = key;
        }
        _results.push(proc(value, prefix));
      } else {
        _results.push(pairs.push(prefix != null ? "" + prefix + "[" + key + "]=" + value : "" + key + "=" + value));
      }
    }
    return _results;
  })();
  return pairs.join('&');
};

This will construct strings like so:

toParams({a: 'one', b: 'two', c: {x: 'eight', y: ['g','h','j'], z: {asdf: 'fdsa'}}})

"a=one&b=two&c[x]=eight&c[y][0]=g&c[y][1]=h&c[y][2]=j&c[y][z][asdf]=fdsa"

Why can't overriding methods throw exceptions broader than the overridden method?

In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).

Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.

Mockito: Inject real objects into private @Autowired fields

Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :

@Mock
private SomeService serviceMock;

private Demo demo;

/* ... */
@BeforeEach
public void beforeEach(){
   demo = new Demo(serviceMock);
}

Using Mockito spy for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks and @Spy also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy() javadoc before using that blindly (emphasis is not mine) :

Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.

As usual you are going to read the partial mock warning: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How to use HTML to print header and footer on every printed page of a document?

I just spent the better half of my day coming up with a solution that actually worked for me and thought I would share what I did. The problem with the solutions above that I was having was that all of my paragraph elements would overlap with the footer I wanted at the bottom of the page. In order to get around this, I used the following CSS:

footer {
  font-size: 9px;
  color: #f00;
  text-align: center;
}

@page {
  size: A4;
  margin: 11mm 17mm 17mm 17mm;
}

@media print {
  footer {
    position: fixed;
    bottom: 0;
  }

  .content-block, p {
    page-break-inside: avoid;
  }

  html, body {
    width: 210mm;
    height: 297mm;
  }
}

The page-break-inside for p and content-block was crucial for me. Any time I have a p following an h*, I wrap them both in a div class = "content-block"> to ensure they stay together and don't break.

I'm hoping that someone finds this useful because it took me about 3 hours to figure out (I'm also new to CSS/HTML, so there's that...)

EDIT

Per a request in the comments, I am adding an example HTML document. You'll want to copy this into an HTML file, open it, and then choose to print the page. The print preview should show this working. It worked in Firefox and IE on my end, but Chrome made the font small enough to fit on one page, so it didn't work there.

_x000D_
_x000D_
footer {_x000D_
  font-size: 9px;_x000D_
  color: #f00;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
@page {_x000D_
  size: A4;_x000D_
  margin: 11mm 17mm 17mm 17mm;_x000D_
}_x000D_
_x000D_
@media print {_x000D_
  footer {_x000D_
    position: fixed;_x000D_
    bottom: 0;_x000D_
  }_x000D_
_x000D_
  .content-block, p {_x000D_
    page-break-inside: avoid;_x000D_
  }_x000D_
_x000D_
  html, body {_x000D_
    width: 210mm;_x000D_
    height: 297mm;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head></head>_x000D_
  <body>_x000D_
    <h1>_x000D_
      Example Document_x000D_
    </h1>_x000D_
    <div>_x000D_
      <p>_x000D_
        This is an example document that shows how to have a footer that repeats at the bottom of every page, but also isn't covered up by paragraph text._x000D_
      </p>_x000D_
    </div>_x000D_
    <div>_x000D_
      <h3>_x000D_
        Example Section I_x000D_
      </h3>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vestibulum metus sit amet urna lobortis sollicitudin. Nulla mattis purus porta lorem tempor, a cursus tellus facilisis. Aliquam pretium nibh vitae elit placerat vestibulum. Duis felis ipsum, consectetur id pellentesque in, porta sit amet sapien. Ut tristique enim sem, laoreet bibendum nisl fermentum vitae. Ut aliquet sem ac lorem malesuada sodales. Fusce iaculis ipsum ex, in mollis dolor dapibus sit amet. In convallis felis in orci fermentum gravida a vel orci. Sed tincidunt porta nibh sit amet varius. Donec et odio eget odio tempus auctor ac eget ex._x000D_
        _x000D_
        Pellentesque vitae augue sed purus dictum ultricies at eu neque. Nullam ut mauris a purus tristique euismod. Sed elementum, leo id placerat congue, leo tellus pharetra orci, eget ultricies odio quam sit amet ipsum. Praesent feugiat, lorem at commodo egestas, felis ligula pharetra sapien, in placerat mauris nisi aliquet tortor. Quisque nibh lectus, laoreet vel mollis a, tincidunt vel ipsum. Sed blandit vehicula sollicitudin. Donec et sapien justo. Ut fermentum ipsum imperdiet diam condimentum, eget varius sapien dictum. Sed sed elit egestas libero maximus finibus eu eget massa._x000D_
        _x000D_
        Duis finibus vestibulum finibus. Nunc lobortis lacus ut libero mattis tempor. Nulla a nunc at nisl elementum congue. Nunc eu consectetur mauris. Etiam non placerat massa. Etiam eu urna in metus tempus molestie sed eget diam. Nunc sem velit, elementum sit amet fringilla in, dictum sit amet sem. Quisque convallis faucibus purus dignissim dictum. Sed semper, mi vel accumsan sollicitudin, massa massa pellentesque justo, eget auctor sapien enim ac elit._x000D_
        _x000D_
        Nullam turpis augue, lacinia ut libero ac, rhoncus bibendum ligula. Mauris ullamcorper maximus turpis, a consequat turpis bibendum sit amet. Nam vitae dui nec velit hendrerit faucibus. Vivamus nunc diam, porta tristique augue nec, dignissim venenatis felis. Proin mattis id risus in feugiat. Etiam cursus faucibus nisi. In in nisi ullamcorper, convallis lectus et, ornare nulla. Cras tristique nulla eros, non maximus odio imperdiet eu. Nullam egestas dignissim est, et fringilla odio pretium eleifend. Nullam tincidunt sapien fermentum, rhoncus risus ac, ullamcorper libero. Vestibulum bibendum molestie dui nec tincidunt. Mauris tempus, orci ut congue vulputate, erat orci aliquam orci, sed eleifend orci dui sed tellus. Pellentesque pellentesque massa vulputate urna pretium, consectetur pulvinar orci pulvinar._x000D_
        _x000D_
        Donec aliquet imperdiet ex, et tincidunt risus convallis eget. Etiam eu fermentum lectus, molestie eleifend nisi. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam dignissim, erat vitae congue molestie, ante urna sagittis est, et sagittis lacus risus vitae est. Sed elementum ipsum et pellentesque dignissim. Sed vehicula feugiat pretium. Donec ex lacus, dictum faucibus lectus sit amet, tempus hendrerit ante. Ut sollicitudin sodales metus, at placerat risus viverra ut._x000D_
        _x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vestibulum metus sit amet urna lobortis sollicitudin. Nulla mattis purus porta lorem tempor, a cursus tellus facilisis. Aliquam pretium nibh vitae elit placerat vestibulum. Duis felis ipsum, consectetur id pellentesque in, porta sit amet sapien. Ut tristique enim sem, laoreet bibendum nisl fermentum vitae. Ut aliquet sem ac lorem malesuada sodales. Fusce iaculis ipsum ex, in mollis dolor dapibus sit amet. In convallis felis in orci fermentum gravida a vel orci. Sed tincidunt porta nibh sit amet varius. Donec et odio eget odio tempus auctor ac eget ex._x000D_
        _x000D_
        Duis finibus vestibulum finibus. Nunc lobortis lacus ut libero mattis tempor. Nulla a nunc at nisl elementum congue. Nunc eu consectetur mauris. Etiam non placerat massa. Etiam eu urna in metus tempus molestie sed eget diam. Nunc sem velit, elementum sit amet fringilla in, dictum sit amet sem. Quisque convallis faucibus purus dignissim dictum. Sed semper, mi vel accumsan sollicitudin, massa massa pellentesque justo, eget auctor sapien enim ac elit._x000D_
        _x000D_
        Nullam turpis augue, lacinia ut libero ac, rhoncus bibendum ligula. Mauris ullamcorper maximus turpis, a consequat turpis bibendum sit amet. Nam vitae dui nec velit hendrerit faucibus. Vivamus nunc diam, porta tristique augue nec, dignissim venenatis felis. Proin mattis id risus in feugiat. Etiam cursus faucibus nisi. In in nisi ullamcorper, convallis lectus et, ornare nulla. Cras tristique nulla eros, non maximus odio imperdiet eu. Nullam egestas dignissim est, et fringilla odio pretium eleifend. Nullam tincidunt sapien fermentum, rhoncus risus ac, ullamcorper libero._x000D_
      </p>_x000D_
    </div>_x000D_
    <div class="content-block">_x000D_
      <h3>Example Section II</h3>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vestibulum metus sit amet urna lobortis sollicitudin. Nulla mattis purus porta lorem tempor, a cursus tellus facilisis. Aliquam pretium nibh vitae elit placerat vestibulum. Duis felis ipsum, consectetur id pellentesque in, porta sit amet sapien. Ut tristique enim sem, laoreet bibendum nisl fermentum vitae. Ut aliquet sem ac lorem malesuada sodales. Fusce iaculis ipsum ex, in mollis dolor dapibus sit amet. In convallis felis in orci fermentum gravida a vel orci. Sed tincidunt porta nibh sit amet varius. Donec et odio eget odio tempus auctor ac eget ex._x000D_
        _x000D_
        Pellentesque vitae augue sed purus dictum ultricies at eu neque. Nullam ut mauris a purus tristique euismod. Sed elementum, leo id placerat congue, leo tellus pharetra orci, eget ultricies odio quam sit amet ipsum. Praesent feugiat, lorem at commodo egestas, felis ligula pharetra sapien, in placerat mauris nisi aliquet tortor. Quisque nibh lectus, laoreet vel mollis a, tincidunt vel ipsum. Sed blandit vehicula sollicitudin. Donec et sapien justo. Ut fermentum ipsum imperdiet diam condimentum, eget varius sapien dictum. Sed sed elit egestas libero maximus finibus eu eget massa._x000D_
      </p>_x000D_
    </div>_x000D_
    <footer>_x000D_
      This is the text that goes at the bottom of every page._x000D_
    </footer>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Performing Breadth First Search recursively

I couldn't find a way to do it completely recursive (without any auxiliary data-structure). But if the queue Q is passed by reference, then you can have the following silly tail recursive function:

BFS(Q)
{
  if (|Q| > 0)
     v <- Dequeue(Q)
     Traverse(v)
     foreach w in children(v)
        Enqueue(Q, w)    

     BFS(Q)
}

How to terminate a thread when main program ends?

Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.

E.g. for Python 3:

while threading.main_thread().isAlive():
    do.you.subthread.thing()
gracefully.close.the.thread()

See Check if the Main Thread is still alive from another thread.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

unzip name_of_the_zipfile.zip

worked fine for me, after installing the zip package from Info-ZIP:

sudo apt install -y zip

The above installation is for Debian/Ubuntu/Mint. For other Linux distros, see the second reference below.

References:
http://infozip.sourceforge.net/
https://www.tecmint.com/install-zip-and-unzip-in-linux/

IPhone/IPad: How to get screen width programmatically?

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);

Generate a sequence of numbers in Python

using numpy and list comprehension you can do the

import numpy as np
[num for num in np.arange(1,101) if (num%4 == 1 or num%4 == 2)]

Dynamically select data frame columns using $ and a character value

if you want to select column with specific name then just do

A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]

you can run it in loop as well reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this

A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x

again this can also be added in loop

"Submit is not a function" error in JavaScript

You can try

<form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data">

<input onclick="submitAction(this)" id="submit_value" type="button" name="submit_value" value="">

</form>

<script type="text/javascript">
function submitAction(element)
{
    element.form.submit();
}
</script>

Don't you have more than one form with the same name ?

Passing parameters to a Bash function

There are two typical ways of declaring a function. I prefer the second approach.

function function_name {
   command...
} 

or

function_name () {
   command...
} 

To call a function with arguments:

function_name "$arg1" "$arg2"

The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself.

Example:

function_name () {
   echo "Parameter #1 is $1"
}

Also, you need to call your function after it is declared.

#!/usr/bin/env sh

foo 1  # this will fail because foo has not been declared yet.

foo() {
    echo "Parameter #1 is $1"
}

foo 2 # this will work.

Output:

./myScript.sh: line 2: foo: command not found
Parameter #1 is 2

Reference: Advanced Bash-Scripting Guide.

What is the right way to POST multipart/form-data using curl?

This is what worked for me

curl --form file='@filename' URL

It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

Explanation

From the curl manpages; under the description for the option --form it says:

This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

Addendum

Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

On that same note, I will also recommend quoting the @ symbol.


You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Seeking useful Eclipse Java code templates

list_methods - generates the methods for add, removing, counting, and contains for a list

public void add${listname}(${listtype} toAdd){
    get${listname}s().add(toAdd);
}

public void remove${listname}(${listtype} toRemove){
    get${listname}s().remove(toRemove);
}

public ${listtype} get${listname}(int index){
    return get${listname}s().get(index);
}

public int get${listname}Count(){
    return get${listname}s().size();
}

public boolean contains${listname}(${listtype} toFind){
    return get${listname}s().contains(toFind);
}

${cursor}

id - inserts the annotations, imports, field, and getter for simple JPA @Id

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

public Long getId(){
    return id;
}

${cursor}
${:import (javax.persistence.GenerationType,javax.persistence.GeneratedValue,javax.persistence.Id)}

"Fatal error: Cannot redeclare <function>"

Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.

Get properties and values from unknown object

Yes, Reflection would be the way to go. First, you would get the Type that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType method on Object. Because it is on the Object class, it's callable by every object in .NET, as all types derive from Object (well, technically, not everything, but that's not important here).

Once you have the Type instance, you can call the GetProperties method to get the PropertyInfo instances which represent the run-time informationa about the properties on the Type.

Note, you can use the overloads of GetProperties to help classify which properties you retrieve.

From there, you would just write the information out to a file.

Your code above, translated, would be:

// The instance, it can be of any type.
object o = <some object>;

// Get the type.
Type type = o.GetType();

// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
    // Do something with the property info.
    DoSomething(info);
}

Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods or GetFields methods respectively.

Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.

Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as or is operator to help determine which base class/interface you are working with at runtime).

However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.

Which JRE am I using?

The Java system property System.getProperty(...) to consult is "java.runtime.name". This will distinguish between "OpenJDK Runtime Environment" and "Java(TM) SE Runtime Environment". They both have the same vendor - "Oracle Corporation".

This property is also included in the output for java -version.

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

How to add click event to a iframe with JQuery

Try using this : iframeTracker jQuery Plugin, like that :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

Call Stored Procedure within Create Trigger in SQL Server

finally...

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

GO
ALTER TRIGGER [dbo].[RA2Newsletter] 
   ON  [dbo].[Reiseagent] 
   AFTER INSERT
 AS
    declare
    @rAgent_Name nvarchar(50),
    @rAgent_Email nvarchar(50),
    @rAgent_IP nvarchar(50),
    @hotelID int,
    @retval int


BEGIN
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    Select @rAgent_Name=rAgent_Name,@rAgent_Email=rAgent_Email,@rAgent_IP=rAgent_IP,@hotelID=hotelID  From Inserted
    EXEC insert2Newsletter '','',@rAgent_Name,@rAgent_Email,@rAgent_IP,@hotelID,'RA', @retval

END

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

android {
     compileSdkVersion 26
     buildToolsVersion '26.0.2'
     useLibrary 'org.apache.http.legacy'
 defaultConfig {
    applicationId "com.test"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}

this is working for me

How to set a default value for an existing column

This will work in SQL Server:

ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;

Enforcing the type of the indexed members of a Typescript object?

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

Detect and exclude outliers in Pandas data frame

I prefer to clip rather than drop. the following will clip inplace at the 2nd and 98th pecentiles.

df_list = list(df)
minPercentile = 0.02
maxPercentile = 0.98

for _ in range(numCols):
    df[df_list[_]] = df[df_list[_]].clip((df[df_list[_]].quantile(minPercentile)),(df[df_list[_]].quantile(maxPercentile)))

Git merge reports "Already up-to-date" though there is a difference

The same happened to me. But the scenario was a little different, I had master branch, and I carved out release_1 (say) out of it. Made some changes in release_1 branch and merged it into origin. then I did ssh and on the remote server I again checkout out release_1 using the command git checkout -b release_1 - which actually carves out a new branch release_! from the master rather than checking out the already existing branch release_1 from origin. Solved the problem by removing "-b" switch

Integer to hex string in C++

int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30

Make the console wait for a user input to close

A simple trick:

import java.util.Scanner;  

/* Add these codes at the end of your method ...*/

Scanner input = new Scanner(System.in);
System.out.print("Press Enter to quit...");
input.nextLine();

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Manually Set Value for FormBuilder Control

Updated: 19/03/2017

this.form.controls['dept'].setValue(selected.id);

OLD:

For now we are forced to do a type cast:

(<Control>this.form.controls['dept']).updateValue(selected.id)

Not very elegant I agree. Hope this gets improved in future versions.

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Getting a map() to return a list in Python 3.x

List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define lmap function (on the analogy of python2's imap) that returns list:

lmap = lambda func, *iterable: list(map(func, *iterable))

Then calling lmap instead of map will do the job: lmap(str, x) is shorter by 5 characters (30% in this case) than list(map(str, x)) and is certainly shorter than [str(v) for v in x]. You may create similar functions for filter too.

There was a comment to the original question:

I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58

It is possible to do that, but it is a very bad idea. Just for fun, here's how you may (but should not) do it:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

How to Display Multiple Google Maps per page with API V3

You haven't defined a div with id="map_canvas", you only have id="map_canvas2" and id="route2". The div ids need to match the argument in the GMap() constructor.

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show End of Line.

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Case insensitive regular expression without re.compile?

You can also define case insensitive during the pattern compile:

pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)

ThreeJS: Remove object from scene

You can use this

function removeEntity(object) {
    var scene = document.querySelectorAll("scene");                               //clear the objects from the scene
    for (var i = 0; i < scene.length; i++) {                                    //loop through to get all object in the scene
    var scene =document.getElementById("scene");                                  
    scene.removeChild(scene.childNodes[0]);                                        //remove all specified objects
  }   

In PHP, what is a closure and why does it use the "use" identifier?

closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).

javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.

there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.

<?php
    function generateComparisonFunctionForKey($key) {
        return function ($left, $right) use ($key) {
            if ($left[$key] == $right[$key])
                return 0;
            else
                return ($left[$key] < $right[$key]) ? -1 : 1;
        };
    }

    $myArray = array(
        array('name' => 'Alex', 'age' => 70),
        array('name' => 'Enrico', 'age' => 25)
    );

    $sortByName = generateComparisonFunctionForKey('name');
    $sortByAge  = generateComparisonFunctionForKey('age');

    usort($myArray, $sortByName);

    usort($myArray, $sortByAge);
?>

warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.

there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.

to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout(); (or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!

function getFunctionTextInASecond(value) {
    return function () {
        document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!
    }
}

var textToDisplay = prompt('text to show in a second', 'foo bar');

// this returns a function that sets the bodys innerHTML to the prompted value
var myFunction = getFunctionTextInASecond(textToDisplay);

window.setTimeout(myFunction, 1000);

myFunction returns a function with a kind-of predefined parameter!

to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.

How to Clone Objects

Painlessly: Using NClone library

Person a = new Person() { head = "big", feet = "small" };
Person b = Clone.ObjectGraph(a); 

How do I set an ASP.NET Label text from code behind on page load?

For this label:

<asp:label id="myLabel" runat="server" />

In the code behind use (C#):

myLabel.Text = "my text"; 

Update (following updated question):

You do not need to use FindControl - that whole line is superfluous:

  Label myLabel = this.FindControl("myLabel") as Label;
  myLabel.Text = "my text";

Should be just:

  myLabel.Text = "my text";

The Visual Studio designer should create a file with all the server side controls already added properly to the class (in a RankPage.aspx.designer.cs file, by default).

You are talking about a RankPage.cs file - the way Visual Studio would have named it is RankPage.aspx.cs. How are you linking these files together?

php implode (101) with quotes

No, the way that you're doing it is just fine. implode() only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I tried the main parts of each answer, to no avail. What finally fixed it for me was to export the following environment variables:

LD_LIBRARY_PATH=/usr/local/lib:~/Qt/5.9.1/gcc_64/lib
QT_QPA_PLATFORM_PLUGIN_PATH=~/Qt/5.9.1/gcc_64/plugins/ 

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

Nested Recycler view height doesn't wrap its content

An alternative to extend LayoutManager can be just set the size of the view manually.

Number of items per row height (if all the items have the same height and the separator is included on the row)

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mListView.getLayoutParams();
params.height = mAdapter.getItemCount() * getResources().getDimensionPixelSize(R.dimen.row_height);
mListView.setLayoutParams(params);

Is still a workaround, but for basic cases it works.

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Converting Columns into rows with their respective data in sql server

declare @T table (ScripName varchar(50), ScripCode varchar(50), Price int)
insert into @T values ('20 MICRONS', '533022', 39)

select 
  'ScripName' as ColName,
  ScripName as ColValue
from @T
union all
select 
  'ScripCode' as ColName,
  ScripCode as ColValue
from @T
union all
select 
  'Price' as ColName,
  cast(Price as varchar(50)) as ColValue
from @T

How to select only the first rows for each unique value of a column?

This will give you one row of each duplicate row. It will also give you the bit-type columns, and it works at least in MS Sql Server.

(select cname, address 
from (
  select cname,address, rn=row_number() over (partition by cname order by cname) 
  from customeraddresses  
) x 
where rn = 1) order by cname

If you want to find all the duplicates instead, just change the rn= 1 to rn > 1. Hope this helps

Can I force pip to reinstall the current version?

sudo pip3 install --upgrade --force-reinstall --no-deps --no-cache-dir <package-name>==<package-version>

Some relevant answers:

Difference between pip install options "ignore-installed" and "force-reinstall"

How to set Python's default version to 3.x on OS X?

Mac users just need to run the following code on terminal

brew switch python 3.x.x

3.x.x should be the new python version.

This will update all the system links.

Playing .mp3 and .wav in Java?

Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.

You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.

importing a CSV into phpmyadmin

This is happen due to the id(auto increment filed missing). If you edit it in a text editor by adding a comma for the ID field this will be solved.

How to encode URL parameters?

Just try encodeURI() and encodeURIComponent() yourself...

_x000D_
_x000D_
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
_x000D_
_x000D_

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...

You should not be using encodeURIComponent() or encodeURI(). You should use fixedEncodeURIComponent() and fixedEncodeURI(), according to the MDN Documentation.

Regarding encodeURI()...

If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

Regarding encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

So, what is the difference? fixedEncodeURI() and fixedEncodeURIComponent() convert the same set of values, but fixedEncodeURIComponent() also converts this set: +@?=:*#;,$&. This set is used in GET parameters (&, +, etc.), anchor tags (#), wildcard tags (*), email/username parts (@), etc..

For example -- If you use encodeURI(), [email protected]/?email=me@home will not properly send the second @ to the server, except for your browser handling the compatibility (as Chrome naturally does often).

Including a groovy script in another groovy

As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript AST transform annotation.

Example:

file MainScript.groovy:

abstract class MainScript extends Script {
    def meaningOfLife = 42
}

file test.groovy:

import groovy.transform.BaseScript
@BaseScript MainScript mainScript

println "$meaningOfLife" //works as expected

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

Move all files except one

If you use bash and have the extglob shell option set (which is usually the case):

mv ~/Linux/Old/!(Tux.png) ~/Linux/New/

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

Grep to find item in Perl array

I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.

Perhaps,

if (grep(/^$match$/, @array)) more apt.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

With Eclipse Collections, the method removeIf defined on MutableCollection will work:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.lessThan(3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

With Java 8 Lambda syntax this can be written as follows:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.cast(integer -> integer < 3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

The call to Predicates.cast() is necessary here because a default removeIf method was added on the java.util.Collection interface in Java 8.

Note: I am a committer for Eclipse Collections.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

Bash: If/Else statement in one line

pgrep -q some_process && echo 1 || echo 0

more oneliners here

How to create directory automatically on SD card

I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();

How do I debug Windows services in Visual Studio?

You should separate out all the code that will do stuff from the service project into a separate project, and then make a test application that you can run and debug normally.

The service project would be just the shell needed to implement the service part of it.

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

How do I POST JSON data with cURL?

You need to set your content-type to application/json. But -d (or --data) sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

Looking at the curl man page, I think you can use -H (or --header):

-H "Content-Type: application/json"

Full example:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"xyz","password":"xyz"}' \
  http://localhost:3000/api/login

(-H is short for --header, -d for --data)

Note that -request POST is optional if you use -d, as the -d flag implies a POST request.


On Windows, things are slightly different. See the comment thread.

how to implement a pop up dialog box in iOS

Although I already wrote an overview of different kinds of popups, most people just need an Alert.

How to implement a popup dialog box

enter image description here

class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
}

My fuller answer is here.

React-Native: Module AppRegistry is not a registered callable module

The one main reason of this problem could be where you would have installed a plugin and forget to link it.

try this:

react-native link

Re-run your app.

Hope this will help. Please let me know in comments. Thanks.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.

Stop form from submitting , Using Jquery

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

Here is an example of some added validation

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

Spring Boot not serving static content

Just to add yet another answer to an old question... People have mentioned the @EnableWebMvc will prevent WebMvcAutoConfiguration from loading, which is the code responsible for creating the static resource handlers. There are other conditions that will prevent WebMvcAutoConfiguration from loading as well. Clearest way to see this is to look at the source:

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java#L139-L141

In my case, I was including a library that had a class that was extending from WebMvcConfigurationSupport which is a condition that will prevent the autoconfiguration:

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

It's important to never extend from WebMvcConfigurationSupport. Instead, extend from WebMvcConfigurerAdapter.

UPDATE: The proper way to do this in 5.x is to implement WebMvcConfigurer

Integer value comparison

It's better to avoid unnecessary autoboxing for 2 reasons.

For one thing, it's a bit slower than int < int, as you're (sometimes) creating an extra object;

void doSomethingWith(Integer integerObject){ ...
  int i = 1000;
  doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));

The bigger issue is that hidden autoboxing can hide exceptions:

void doSomethingWith (Integer count){
  if (count>0)  // gets compiled into count.intValue()>0

Calling this method with null will throw a NullPointerException.

The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare() or intValue(), and if you've got the primitive just check the value directly.

Best way to remove duplicate entries from a data table

You can use the DefaultView.ToTable method of a DataTable to do the filtering like this (adapt to C#):

 Public Sub RemoveDuplicateRows(ByRef rDataTable As DataTable)
    Dim pNewDataTable As DataTable
    Dim pCurrentRowCopy As DataRow
    Dim pColumnList As New List(Of String)
    Dim pColumn As DataColumn

    'Build column list
    For Each pColumn In rDataTable.Columns
        pColumnList.Add(pColumn.ColumnName)
    Next

    'Filter by all columns
    pNewDataTable = rDataTable.DefaultView.ToTable(True, pColumnList.ToArray)

    rDataTable = rDataTable.Clone

    'Import rows into original table structure
    For Each pCurrentRowCopy In pNewDataTable.Rows
        rDataTable.ImportRow(pCurrentRowCopy)
    Next
End Sub

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

How do I align a number like this in C?

If you can't know the width in advance, then your only possible answer would depend on staging your output in a temporary buffer of some kind. For small reports, just collecting the data and deferring output until the input is bounded would be simplest.

For large reports, an intermediate file may be required if the collected data exceeds reasonable memory bounds.

Once you have the data, then it is simple to post-process it into a report using the idiom printf("%*d", width, value) for each value.

Alternatively if the output channel permits random access, you could just go ahead and write a draft of the report that assumes a (short) default width, and seek back and edit it any time your width assumption is violated. This also assumes that you can pad the report lines outside that field in some innocuous way, or that you are willing to replace the output so far by a read-modify-write process and abandon the draft file.

But unless you can predict the correct width in advance, it will not be possible to do what you want without some form of two-pass algorithm.

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

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

How to compare two dates?

datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2) will return True.

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(-1).

datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2) will return datetime.timedelta(1).

see the docs.

BULK INSERT with identity (auto-increment) column

Don't BULK INSERT into your real tables directly.

I would always

  1. insert into a staging table dbo.Employee_Staging (without the IDENTITY column) from the CSV file
  2. possibly edit / clean up / manipulate your imported data
  3. and then copy the data across to the real table with a T-SQL statement like:

    INSERT INTO dbo.Employee(Name, Address) 
       SELECT Name, Address
       FROM dbo.Employee_Staging
    

jQuery, checkboxes and .is(":checked")

<input id="widget-wpb_widget-3-custom_date" class="mycheck" type="checkbox" value="d/M/y" name="widget-wpb_widget[3][custom_date]" unchecked="true">    

var atrib = $('.mycheck').attr("unchecked",true);
$('.mycheck').click(function(){
if ($(this).is(":checked")) 
{
$('.mycheck').attr("unchecked",false);
   alert("checkbox checked");
}
else
{
$('.mycheck').attr("unchecked",true);
 alert("checkbox unchecked");
}
});

RegEx for Javascript to allow only alphanumeric

Even better than Gayan Dissanayake pointed out.

/^[-\w\s]+$/

Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$

You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.

Adding JPanel to JFrame

Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:

public class Test2 extends JPanel {

Test2(){

...

}

More details:

JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.

Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.

Eclipse Indigo - Cannot install Android ADT Plugin

Thanks to all for the posts but unfortunatley none of the above solved my problem. Eventually what got it all working for me was to download eclipse indigo 3.7.2 and (this is very important) EXTRACT IT DIRECTLY INTO MY PROGRAMS FOLDER. Before I would extract it to my desktop and copy into the programs folder (C:\Program Files) but I would jus get an error message saying "The Eclipse executable launcher was unable to locate its companion shared library" when trying to run eclipse.

After extracting eclipse directly to my programs folder I ran it and added the ADT plugin the way reccomended in on the android site and so far all is working well :)

I'm on a windows 7 x64 machine and had jre-7u2-windows-x64.exe, jdk-7u2-windows-x64.exe and installer_r16-windows.exe installed before extracting eclipse.

I hope this can help someone else too :)

A transport-level error has occurred when receiving results from the server

I had the same issue. I solved it, truncating the SQL Server LOG. Check doing that, and then tell us, if this solution helped you.

Calculate date/time difference in java

I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit class, but there were no answers using this in the way OP wanted it.

So here's another solution, should someone come by missing it ;-)

public class DateTesting {
    public static void main(String[] args) {
        String dateStart = "11/03/14 09:29:58";
        String dateStop = "11/03/14 09:33:43";

        // Custom date format
        SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");  

        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);
        } catch (ParseException e) {
            e.printStackTrace();
        }    

        // Get msec from each, and subtract.
        long diff = d2.getTime() - d1.getTime();

        long days = TimeUnit.MILLISECONDS.toDays(diff);
        long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
        long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
        long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
        long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);

        System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
    }
}

Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit is a highly overlooked class.

Importing modules from parent folder

It seems that the problem is not related to the module being in a parent directory or anything like that.

You need to add the directory that contains ptdraft to PYTHONPATH

You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.

align text center with android

Adding android:gravity="center" in your TextView will do the trick (be the parent layout is Relative/Linear)!

Also, you should avoid using dp for font size. Use sp instead.

Arrays in unix shell?

#!/bin/bash

# define a array, space to separate every item
foo=(foo1 foo2)

# access
echo "${foo[1]}"

# add or changes
foo[0]=bar
foo[2]=cat
foo[1000]=also_OK

You can read the ABS "Advanced Bash-Scripting Guide"

IOError: [Errno 2] No such file or directory trying to open a file

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

Also, the syntax:

with open(f): 

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

And finally:

write(line)

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

See: input / output in python.

Request string without GET arguments

Why so complicated? =)

$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];

this should really do it man ;)

How to vertically center an image inside of a div element in HTML using CSS?

In your example, the div's height is static and the image's height is static. Give the image a margin-top value of ( div_height - image_height ) / 2

If the image is 50px, then

img {
    margin-top: 25px;
}

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

TypeError: 'module' object is not callable

Add to the main __init__.py in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass

CSS text-overflow: ellipsis; not working?

You can also add float:left; inside this class #User_Apps_Content .DLD_App a

From ND to 1D arrays

For list of array with different size use following:

import numpy as np

# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]

# stack them
b = np.hstack(a)

print(b)

Output:

[1 2 3 4 5 6 7 8]

How to force input to only allow Alpha Letters?

A lot of the other solutions that use keypress will not work on mobile, you need to use input.

html

<input type="text" id="name"  data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />

jQuery

$('#name').on('input', function() {
    var cursor_pos = $(this).getCursorPosition()
    if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
        $(this).val($(this).attr('data-value'))
        $(this).setCursorPosition(cursor_pos - 1)
        return
    }
    $(this).attr('data-value', $(this).val())
})

$.fn.getCursorPosition = function() {
    if(this.length == 0) return -1
    return $(this).getSelectionStart()
}
$.fn.setCursorPosition = function(position) {
    if(this.lengh == 0) return this
    return $(this).setSelection(position, position)
}
$.fn.getSelectionStart = function(){
  if(this.lengh == 0) return -1
  input = this[0]
  var pos = input.value.length
  if (input.createTextRange) {
    var r = document.selection.createRange().duplicate()
    r.moveEnd('character', input.value.length)
    if (r.text == '') 
    pos = input.value.length
    pos = input.value.lastIndexOf(r.text)
  } else if(typeof(input.selectionStart)!="undefined")
  pos = input.selectionStart
  return pos
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
  if(this.lengh == 0) return this
  input = this[0]
  if(input.createTextRange) {
    var range = input.createTextRange()
    range.collapse(true)
    range.moveEnd('character', selectionEnd)
    range.moveStart('character', selectionStart)
    range.select()
  }
  else if (input.setSelectionRange) {
    input.focus()
    input.setSelectionRange(selectionStart, selectionEnd)
  }
  return this
}

How can I create and style a div using JavaScript?

You can just use the method below:

document.write()

It is very simple, in the doc below I explain

_x000D_
_x000D_
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
  background-color: red;
  padding: 5px;
  color: #fff;
  font-family: Arial;
  cursor: pointer;
}

.div:hover {
  background-color: blue;
  padding: 10px;
}

.div:hover:before {
  content: 'Hover! ';
}

.div:active {
  background-color: green;
  padding: 15px;
}

.div:active:after {
  content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_
_x000D_
_x000D_

How do I specify the JDK for a GlassFish domain?

In my case the problem was the JAVA_HOME variable was set an installed jre.

An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

Java equivalent to C# extension methods

Manifold provides Java with C#-style extension methods and several other features. Unlike other tools, Manifold has no limitations and does not suffer from issues with generics, lambdas, IDE etc. Manifold provides several other features such as F#-style custom types, TypeScript-style structural interfaces, and Javascript-style expando types.

Additionally, IntelliJ provides comprehensive support for Manifold via the Manifold plugin.

Manifold is an open source project available on github.

Excel: VLOOKUP that returns true or false?

You could wrap your VLOOKUP() in an IFERROR()

Edit: before Excel 2007, use =IF(ISERROR()...)

Get size of all tables in database

Above queries are good for finding the amount of space used by the table (indexes included), but if you want to compare how much space is used by indexes on the table use this query:

SELECT
    OBJECT_NAME(i.OBJECT_ID) AS TableName,
    i.name AS IndexName,
    i.index_id AS IndexID,
    8 * SUM(a.used_pages) AS 'Indexsize(KB)'
FROM
    sys.indexes AS i
    JOIN sys.partitions AS p ON p.OBJECT_ID = i.OBJECT_ID AND p.index_id = i.index_id
    JOIN sys.allocation_units AS a ON a.container_id = p.partition_id
WHERE
    i.is_primary_key = 0 -- fix for size discrepancy
GROUP BY
    i.OBJECT_ID,
    i.index_id,
    i.name
ORDER BY
    OBJECT_NAME(i.OBJECT_ID),
    i.index_id

How to use a jQuery plugin inside Vue

I use it like this:

import jQuery from 'jQuery'

ready: function() {
    var self = this;
    jQuery(window).resize(function () {
      self.$refs.thisherechart.drawChart();
    })
  },

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

PasswordDialog dlg = new PasswordDialog(this);

if(dlg.showDialog() == DialogResult.OK)

{

    //blabla, anything your self

}


public class PasswordDialog extends Dialog
{
    int dialogResult;
    Handler mHandler ;

    public PasswordDialog(Activity context, String mailName, boolean retry)
    {

        super(context);
        setOwnerActivity(context);
        onCreate();
        TextView promptLbl = (TextView) findViewById(R.id.promptLbl);
        promptLbl.setText("Input password/n" + mailName);
    }
    public int getDialogResult()
    {
        return dialogResult;
    }
    public void setDialogResult(int dialogResult)
    {
        this.dialogResult = dialogResult;
    }
    /** Called when the activity is first created. */

    public void onCreate() {
        setContentView(R.layout.password_dialog);
        findViewById(R.id.cancelBtn).setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View paramView)
            {
                endDialog(DialogResult.CANCEL);
            }
            });
        findViewById(R.id.okBtn).setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View paramView)
            {
                endDialog(DialogResult.OK);
            }
            });
        }

    public void endDialog(int result)
    {
        dismiss();
        setDialogResult(result);
        Message m = mHandler.obtainMessage();
        mHandler.sendMessage(m);
    }

    public int showDialog()
    {
        mHandler = new Handler() {
            @Override
              public void handleMessage(Message mesg) {
                  // process incoming messages here
                //super.handleMessage(msg);
                throw new RuntimeException();
              }
          };
        super.show();
        try {
            Looper.getMainLooper().loop();
        }
        catch(RuntimeException e2)
        {
        }
        return dialogResult;
    }

}

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

How to Execute a Python File in Notepad ++?

I wish people here would post steps instead of just overall concepts. I eventually got the cmd /k version to work.

The step-by-step instructions are:

  1. In NPP, click on the menu item: Run
  2. In the submenu, click on: Run
  3. In the Run... dialog box, in the field The Program to Run, delete any existing text and type in: cmd /K "$(FULL_CURRENT_PATH)" The /K is optional, it keeps open the window created when the script runs, if you want that.
  4. Hit the Save... button.
  5. The Shortcut dialogue box opens; fill it out if you want a keyboard shortcut (there's a note saying "This will disable the accelerator" whatever that is, so maybe you don't want to use the keyboard shortcut, though it probably doesn't hurt to assign one when you don't need an accelerator). Somewhere I think you have to tell NPP where the Python.exe file is (e.g., for me: C:\Python33\python.exe). I don't know where or how you do this, but in trying various things here, I was able to do that--I don't recall which attempt did the trick.

How do I declare a 2d array in C++ using new?

The purpose of this answer is not to add anything new that the others don't already cover, but to extend @Kevin Loney's answer.

You could use the lightweight declaration:

int *ary = new int[SizeX*SizeY]

and access syntax will be:

ary[i*SizeY+j]     // ary[i][j]

but this is cumbersome for most, and can lead to confusion. So, you can define a macro as follows:

#define ary(i, j)   ary[(i)*SizeY + (j)]

Now you can access the array using the very similar syntax ary(i, j) // means ary[i][j]. This has the advantages of being simple and beautiful, and at the same time, using expressions in place of the indices is also simpler and less confusing.

To access, say, ary[2+5][3+8], you can write ary(2+5, 3+8) instead of the complex-looking ary[(2+5)*SizeY + (3+8)] i.e. it saves parentheses and helps readability.

Caveats:

  • Although the syntax is very similar, it is NOT the same.
  • In case you pass the array to other functions, SizeY has to be passed with the same name (or instead be declared as a global variable).

Or, if you need to use the array in multiple functions, then you could add SizeY also as another parameter in the macro definition like so:

#define ary(i, j, SizeY)  ary[(i)*(SizeY)+(j)]

You get the idea. Of course, this becomes too long to be useful, but it can still prevent the confusion of + and *.

This is not recommended definitely, and it will be condemned as bad practice by most experienced users, but I couldn't resist sharing it because of its elegance.

Edit:
If you want a portable solution that works for any number of arrays, you can use this syntax:

#define access(ar, i, j, SizeY) ar[(i)*(SizeY)+(j)]

and then you can pass on any array to the call, with any size using the access syntax:

access(ary, i, j, SizeY)      // ary[i][j]

P.S.: I've tested these, and the same syntax works (as both an lvalue and an rvalue) on g++14 and g++11 compilers.

Is there a way to get version from package.json in nodejs code?

Just adding an answer because I came to this question to see the best way to include the version from package.json in my web application.

I know this question is targetted for Node.js however, if you are using Webpack to bundle your app just a reminder the recommended way is to use the DefinePlugin to declare a global version in the config and reference that. So you could do in your webpack.config.json

const pkg = require('../../package.json');

...

plugins : [
    new webpack.DefinePlugin({
      AppVersion: JSON.stringify(pkg.version),
...

And then AppVersion is now a global that is available for you to use. Also make sure in your .eslintrc you ignore this via the globals prop

Pandas DataFrame column to list

I'd like to clarify a few things:

  1. As other answers have pointed out, the simplest thing to do is use pandas.Series.tolist(). I'm not sure why the top voted answer leads off with using pandas.Series.values.tolist() since as far as I can tell, it adds syntax/confusion with no added benefit.
  2. tst[lookupValue][['SomeCol']] is a dataframe (as stated in the question), not a series (as stated in a comment to the question). This is because tst[lookupValue] is a dataframe, and slicing it with [['SomeCol']] asks for a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you remove the extra set of brackets, as in tst[lookupValue]['SomeCol'], then you are asking for just that one column rather than a list of columns, and thus you get a series back.
  3. You need a series to use pandas.Series.tolist(), so you should definitely skip the second set of brackets in this case. FYI, if you ever end up with a one-column dataframe that isn't easily avoidable like this, you can use pandas.DataFrame.squeeze() to convert it to a series.
  4. tst[lookupValue]['SomeCol'] is getting a subset of a particular column via chained slicing. It slices once to get a dataframe with only certain rows left, and then it slices again to get a certain column. You can get away with it here since you are just reading, not writing, but the proper way to do it is tst.loc[lookupValue, 'SomeCol'] (which returns a series).
  5. Using the syntax from #4, you could reasonably do everything in one line: ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()

Demo Code:

import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
                   'colB':[4,5,6]})
filter_value = 1

print "df"
print df
print type(df)

rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)

result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)

result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)

result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)

result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)

result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)

ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)

ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)

Result:

df
   colA  colB
0     1     4
1     2     5
2     1     6
<class 'pandas.core.frame.DataFrame'>

df['colA'] == filter_value
0     True
1    False
2     True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>

df[rows_to_keep]['colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df[rows_to_keep][['colB']]
   colB
0     4
2     6
<class 'pandas.core.frame.DataFrame'>

df[rows_to_keep][['colB']].squeeze()
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[df['colA'] == filter_value, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>

df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>

How to write new line character to a file in Java

Put this code wherever you want to insert a new line:

bufferedWriter.newLine();

When can I use a forward declaration?

I just want to add one important thing you can do with a forwarded class not mentioned in the answer of Luc Touraille.

What you can do with an incomplete type:

Define functions or methods which accept/return pointers/references to the incomplete type and forward that pointers/references to another function.

void  f6(X*)       {}
void  f7(X&)       {}
void  f8(X* x_ptr, X& x_ref) { f6(x_ptr); f7(x_ref); }

A module can pass through an object of a forward declared class to another module.

:first-child not working as expected

The h1:first-child selector means

Select the first child of its parent
if and only if it's an h1 element.

The :first-child of the container here is the ul, and as such cannot satisfy h1:first-child.

There is CSS3's :first-of-type for your case:

.detail_container h1:first-of-type
{
    color: blue;
} 

But with browser compatibility woes and whatnot, you're better off giving the first h1 a class, then targeting that class:

.detail_container h1.first
{
    color: blue;
}

Auto number column in SharePoint list

You can't add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.

There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can't edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.

Check out: Unique ID in SharePoint list

How do I get the domain originating the request in express.js?

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Maximum number of threads in a .NET app?

You can test it by using this snipped code:

private static void Main(string[] args)
{
   int threadCount = 0;
   try
   {
      for (int i = 0; i < int.MaxValue; i ++)
      {
         new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
         threadCount ++;
      }
   }
   catch
   {
      Console.WriteLine(threadCount);
      Console.ReadKey(true);
   }
}

Beware of 32-bit and 64-bit mode of application.

Keep SSH session alive

For those wondering, @edward-coast

If you want to set the keep alive for the server, add this to /etc/ssh/sshd_config:

ClientAliveInterval 60
ClientAliveCountMax 2

ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client.

ClientAliveCountMax: Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

XPath with multiple conditions

You can apply multiple conditions in xpath using and, or

//input[@class='_2zrpKA _1dBPDZ' and @type='text']

//input[@class='_2zrpKA _1dBPDZ' or @type='text']

Markdown: continue numbered list

Use four spaces to indent content between bullet points

1. item 1
2. item 2

    ```
    Code block
    ```
3. item 3

Produces:

  1. item 1
  2. item 2

    Code block

  3. item 3

How to abort a Task like aborting a Thread (Thread.Abort method)?

Everyone knows (hopefully) its bad to terminate thread. The problem is when you don't own a piece of code you're calling. If this code is running in some do/while infinite loop , itself calling some native functions, etc. you're basically stuck. When this happens in your own code termination, stop or Dispose call, it's kinda ok to start shooting the bad guys (so you don't become a bad guy yourself).

So, for what it's worth, I've written those two blocking functions that use their own native thread, not a thread from the pool or some thread created by the CLR. They will stop the thread if a timeout occurs:

// returns true if the call went to completion successfully, false otherwise
public static bool RunWithAbort(this Action action, int milliseconds) => RunWithAbort(action, new TimeSpan(0, 0, 0, 0, milliseconds));
public static bool RunWithAbort(this Action action, TimeSpan delay)
{
    if (action == null)
        throw new ArgumentNullException(nameof(action));

    var source = new CancellationTokenSource(delay);
    var success = false;
    var handle = IntPtr.Zero;
    var fn = new Action(() =>
    {
        using (source.Token.Register(() => TerminateThread(handle, 0)))
        {
            action();
            success = true;
        }
    });

    handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
    WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
    CloseHandle(handle);
    return success;
}

// returns what's the function should return if the call went to completion successfully, default(T) otherwise
public static T RunWithAbort<T>(this Func<T> func, int milliseconds) => RunWithAbort(func, new TimeSpan(0, 0, 0, 0, milliseconds));
public static T RunWithAbort<T>(this Func<T> func, TimeSpan delay)
{
    if (func == null)
        throw new ArgumentNullException(nameof(func));

    var source = new CancellationTokenSource(delay);
    var item = default(T);
    var handle = IntPtr.Zero;
    var fn = new Action(() =>
    {
        using (source.Token.Register(() => TerminateThread(handle, 0)))
        {
            item = func();
        }
    });

    handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
    WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
    CloseHandle(handle);
    return item;
}

[DllImport("kernel32")]
private static extern bool TerminateThread(IntPtr hThread, int dwExitCode);

[DllImport("kernel32")]
private static extern IntPtr CreateThread(IntPtr lpThreadAttributes, IntPtr dwStackSize, Delegate lpStartAddress, IntPtr lpParameter, int dwCreationFlags, out int lpThreadId);

[DllImport("kernel32")]
private static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32")]
private static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);

Add Expires headers

The easiest way to add these headers is a .htaccess file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.

Note that some hosting providers will not let you use .htaccess files, so check their terms if it doesn't seem to work.

The HTML5Boilerplate project has an excellent .htaccess file that covers the necessary settings. See the relevant part of the file at their Github repository

These are the important bits

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.

Eclipse jump to closing brace

With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.

Scanner is skipping nextLine() after using next() or nextFoo()?

The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

Twitter bootstrap modal-backdrop doesn't disappear

Try this

$('#something_clickable').on('click', function () {
  $("#my_modal").modal("hide");
  $("body").removeClass("modal-open");
  $('.modal-backdrop').remove();
 });

It works fine for me.

Set textbox to readonly and background color to grey in jquery

there are 2 solutions:

visit this jsfiddle

in your css you can add this:
     .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}

in your js do something like this:
     $('#test').attr('readonly', true);
     $('#test').addClass('input-disabled');

Hope this help.

Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.

Calculating powers of integers

A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:

/** Compute a**p, assume result fits in a 32-bit signed integer */ 
int pow(int a, int p)
{
    int res = 1;
    int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
    for (int i = i1; i >= 0; --i) {
        res *= res;
        if ((p & (1<<i)) > 0)
            res *= a;
    }
    return res;
}

The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

jQuery text() and newlines

Here is what I use:

function htmlForTextWithEmbeddedNewlines(text) {
    var htmls = [];
    var lines = text.split(/\n/);
    // The temporary <div/> is to perform HTML entity encoding reliably.
    //
    // document.createElement() is *much* faster than jQuery('<div></div>')
    // http://stackoverflow.com/questions/268490/
    //
    // You don't need jQuery but then you need to struggle with browser
    // differences in innerText/textContent yourself
    var tmpDiv = jQuery(document.createElement('div'));
    for (var i = 0 ; i < lines.length ; i++) {
        htmls.push(tmpDiv.text(lines[i]).html());
    }
    return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));

Multiple parameters in a List. How to create without a class?

List only accepts one type parameter. The closest you'll get with List is:

 var list = new List<Tuple<string, int>>();
 list.Add(Tuple.Create("hello", 1));

Return JSON response from Flask view

Prior to Flask 0.11, jsonfiy would not allow returning an array directly. Instead, pass the list as a keyword argument.

@app.route('/get_records')
def get_records():
    results = [
        {
          "rec_create_date": "12 Jun 2016",
          "rec_dietary_info": "nothing",
          "rec_dob": "01 Apr 1988",
          "rec_first_name": "New",
          "rec_last_name": "Guy",
        },
        {
          "rec_create_date": "1 Apr 2016",
          "rec_dietary_info": "Nut allergy",
          "rec_dob": "01 Feb 1988",
          "rec_first_name": "Old",
          "rec_last_name": "Guy",
        },
    ]
    return jsonify(results=list)

How to show a confirm message before delete?

Try this. It works for me

 <a href="delete_methode_link" onclick="return confirm('Are you sure you want to Remove?');">Remove</a>

Add a default value to a column through a migration

**Rails 4.X +**

As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.

1. Run the migration from command line to add the new column

$ rails generate migration add_columnname_to_tablename columnname:boolean

The above command will add a new column in your table.

2. Set the new column value to TRUE/FALSE by editing the new migration file created.

class AddColumnnameToTablename < ActiveRecord::Migration
  def change
    add_column :table_name, :column_name, :boolean, default: false
  end
end

**3. To make the changes into your application database table, run the following command in terminal**

$ rake db:migrate

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How do I rewrite URLs in a proxy response in NGINX

We should first read the documentation on proxy_pass carefully and fully.

The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /. Absense of trailing slash means hat URI is absent.

Proxy_pass with URI:

location /some_dir/ {
    proxy_pass http://some_server/;
}

With the above, there's the following proxy:

http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/          some_subdir/some_file

Basically, /some_dir/ gets replaced by / to change the request path from /some_dir/some_subdir/some_file to /some_subdir/some_file.

Proxy_pass without URI:

location /some_dir/ {
    proxy_pass http://some_server;
}

With the second (no trailing slash): the proxy goes like this:

http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file

Basically, the full original request path gets passed on without changes.


So, in your case, it seems you should just drop the trailing slash to get what you want.


Caveat

Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:

location /some_dir/ {
  rewrite    /some_dir/(.*) /$1 break;
  proxy_pass $upstream_server;
}

There are other cases where rewrite wouldn't work, that's why reading documentation is a must.


Edit

Reading your question again, it seems I may have missed that you just want to edit the html output.

For that, you can use the sub_filter directive. Something like ...

location /admin/ {
    proxy_pass http://localhost:8080/;
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

Basically, the string you want to replace and the replacement string

DIV table colspan: how?

Trying to think in tableless design does not mean that you can not use tables :)

It is only that you can think of it that tabular data can be presented in a table, and that other elements (mostly div's) are used to create the layout of the page.

So I should say that you have to read some information on styling with div-elements, or use this page as a good example page!

Good luck ;)

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I found the game library Allegro easy to use back in the day. Might be worth a look.

How to add items into a numpy array

Appending a single scalar could be done a bit easier as already shown (and also without converting to float) by expanding the scalar to a python-list-type:

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10

b = np.hstack ((a, [[x]] * len (a) ))

returns b as:

array([[ 1,  3,  4, 10],
       [ 1,  2,  3, 10],
       [ 1,  2,  1, 10]])

Appending a row could be done by:

c = np.vstack ((a, [x] * len (a[0]) ))

returns c as:

array([[ 1,  3,  4],
       [ 1,  2,  3],
       [ 1,  2,  1],
       [10, 10, 10]])

Difference between Date(dateString) and new Date(dateString)

Date()

With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.

new Date()

With this you're creating a new instance of Date.

You can use only the following constructors:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.

See w3schools.


EDIT: new Date(dateString) uses one of these formats:

  • "October 13, 1975 11:13:00"
  • "October 13, 1975 11:13"
  • "October 13, 1975"

Why is Thread.Sleep so harmful

It is the 1).spinning and 2).polling loop of your examples that people caution against, not the Thread.Sleep() part. I think Thread.Sleep() is usually added to easily improve code that is spinning or in a polling loop, so it is just associated with "bad" code.

In addition people do stuff like:

while(inWait)Thread.Sleep(5000); 

where the variable inWait is not accessed in a thread-safe manner, which also causes problems.

What programmers want to see is the threads controlled by Events and Signaling and Locking constructs, and when you do that you won't have need for Thread.Sleep(), and the concerns about thread-safe variable access are also eliminated. As an example, could you create an event handler associated with the FileSystemWatcher class and use an event to trigger your 2nd example instead of looping?

As Andreas N. mentioned, read Threading in C#, by Joe Albahari, it is really really good.

Java logical operator short-circuiting

The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.

The & and | operators, when used as logical operators, always evaluate both sides.

There is only one case of short-circuiting for each operator, and they are:

  • false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
  • true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there

Let's compare the behaviour in a simple example:

public boolean longerThan(String input, int length) {
    return input != null && input.length() > length;
}

public boolean longerThan(String input, int length) {
    return input != null & input.length() > length;
}

The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.

How to get javax.comm API?

On ubuntu

 sudo apt-get install librxtx-java then 

add RXTX jars to the project which are in

 usr/share/java

div with dynamic min-height based on browser window height

You propably have to write some JavaScript, because there is no way to estimate the height of all the users of the page.

Get Character value from KeyCode in JavaScript... then trim

I recently wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

How do I do a not equal in Django queryset filtering?

Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x is 5. I believe this will do the trick:

results = Model.objects.filter(x=5).exclude(a=True)

To answer your specific question, there is no "not equal to" field lookup but that's probably because Django has both filter and exclude methods available so you can always just switch the logic around to get the desired result.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.